Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest of the ref snapshot already in memory.
2import * as NodeCrypto from "node:crypto";
3
4import * as Cause from "effect/Cause";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as PubSub from "effect/PubSub";
15import * as Ref from "effect/Ref";
16import * as Schedule from "effect/Schedule";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19import * as SynchronizedRef from "effect/SynchronizedRef";
20import type {
21 GitManagerServiceError,
22 VcsStatusInput,
23 VcsBranchStatus,
24 VcsStatusLocalResult,
25 VcsStatusRemoteResult,
26 VcsRefreshStatusResult,
27 VcsStatusResult,
28 VcsStatusStreamEvent,
29 VcsStatusSubscriptionInput,
30} from "@t3tools/contracts";
31import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts";
32import { mergeGitStatusParts } from "@t3tools/shared/git";
33import * as KeyedLock from "@t3tools/shared/KeyedLock";
34import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
35
36import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
37import * as GitWorkflowService from "../git/GitWorkflowService.ts";
38import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
39import * as ServerSettings from "../serverSettings.ts";
40import type * as GitVcsDriver from "./GitVcsDriver.ts";
41import { VcsAutomaticFetchInterval } from "./VcsAutomaticFetchInterval.ts";
42
43const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
44const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
45const VCS_STATUS_CACHE_CAPACITY = 256;
46const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
47// A held index.lock fails the read, and its removal moves no HEAD to trigger another.
48const CHECKOUT_REFRESH_RETRY = Schedule.exponential(Duration.seconds(1)).pipe(
49 Schedule.modifyDelay(({ duration }) =>
50 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
51 ),
52);
53const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
54
55function boundedDiagnosticValue(value: string): string {
56 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
57}
58
59function diagnosticValueTag(value: unknown): string {
60 try {
61 if (
62 typeof value === "object" &&
63 value !== null &&
64 "_tag" in value &&
65 typeof value._tag === "string"
66 ) {
67 return boundedDiagnosticValue(value._tag);
68 }
69 if (value instanceof Error) {
70 return boundedDiagnosticValue(value.name);
71 }
72 return typeof value;
73 } catch {
74 return "Uninspectable";
75 }
76}
77
78function diagnosticFailureOperation(value: unknown): string | undefined {
79 try {
80 if (
81 typeof value === "object" &&
82 value !== null &&
83 "operation" in value &&
84 typeof value.operation === "string"
85 ) {
86 return boundedDiagnosticValue(value.operation);
87 }
88 } catch {
89 return undefined;
90 }
91 return undefined;
92}
93
94function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
95 if (
96 value !== undefined &&
97 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
98 !values.includes(value)
99 ) {
100 values.push(value);
101 }
102}
103
104function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
105 const failureTags: Array<string> = [];
106 const failureOperations: Array<string> = [];
107 const defectTags: Array<string> = [];
108 let failureCount = 0;
109 let defectCount = 0;
110 let interruptionCount = 0;
111
112 for (const reason of cause.reasons) {
113 if (Cause.isFailReason(reason)) {
114 failureCount += 1;
115 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
116 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
117 continue;
118 }
119 if (Cause.isDieReason(reason)) {
120 defectCount += 1;
121 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
122 continue;
123 }
124 interruptionCount += 1;
125 }
126
127 return {
128 reasonCount: cause.reasons.length,
129 failureCount,
130 failureTags,
131 failureOperations,
132 defectCount,
133 defectTags,
134 interruptionCount,
135 };
136}
137
138interface VcsStatusChange {
139 readonly cwd: string;
140 readonly event: VcsStatusStreamEvent;
141}
142
143interface CachedValue<T> {
144 readonly fingerprint: string;
145 readonly value: T;
146}
147
148interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
149 readonly branch: string | null;
150}
151
152interface CachedLocalStatus extends CachedValue<VcsStatusLocalResult> {
153 readonly includesBranchChanges: boolean;
154}
155
156interface CachedVcsStatus {
157 readonly local: CachedLocalStatus | null;
158 readonly remote: CachedRemoteStatus | null;
159}
160
161interface ActiveHeadWatcher {
162 readonly fiber: Fiber.Fiber<void, never>;
163 readonly ready: Deferred.Deferred<void>;
164 readonly subscriberCount: number;
165}
166
167interface ActiveRemotePoller {
168 readonly fiber: Fiber.Fiber<void, never>;
169 readonly subscriberCount: number;
170 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
171}
172
173export class VcsAutoPullPolicy extends Context.Reference<{
174 readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
175}>("t3/vcs/VcsAutoPullPolicy", {
176 defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
177}) {}
178
179export const layerAutoPullPolicy = Layer.effect(
180 VcsAutoPullPolicy,
181 Effect.gen(function* () {
182 const projects = yield* ProjectStore.ProjectStoreV2;
183 const serverSettings = yield* ServerSettings.ServerSettingsService;
184 return {
185 isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
186 function* (cwd: string) {
187 const project = yield* projects.findActiveByWorkspaceRoot(cwd);
188 if (project._tag === "None") return false;
189 const settings = yield* serverSettings.getSettings;
190 return resolveProjectSettings(settings, project.value.projectId).settings.defaultAutoPull;
191 },
192 Effect.orElseSucceed(() => false),
193 ),
194 };
195 }),
196);
197
198function remoteRefreshFailureDelay(
199 consecutiveFailures: number,
200 configuredInterval: Duration.Duration,
201) {
202 const exponent = Math.max(0, consecutiveFailures - 1);
203 const backoffMs =
204 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
205 const cappedBackoff = Duration.min(
206 Duration.millis(backoffMs),
207 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
208 );
209 return Duration.max(configuredInterval, cappedBackoff);
210}
211
212export class VcsStatusBroadcaster extends Context.Service<
213 VcsStatusBroadcaster,
214 {
215 readonly streamBranchStatus: (
216 input: VcsStatusInput,
217 ) => Stream.Stream<VcsBranchStatus, GitManagerServiceError>;
218 readonly refreshBranchStatus: (
219 input: VcsStatusInput,
220 ) => Effect.Effect<VcsBranchStatus, GitManagerServiceError>;
221 readonly streamBranchChanges: Stream.Stream<{
222 readonly cwd: string;
223 readonly refName: string | null;
224 }>;
225 readonly getStatus: (
226 input: VcsStatusInput,
227 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
228 readonly refreshLocalStatus: (
229 cwd: string,
230 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
231 /**
232 * For a checkout someone is waiting on. Returns once the new branch is published, so the
233 * caller's reply does not outrun it, and finishes the slower remote read in the background.
234 */
235 readonly refreshAfterCheckout: (cwd: string) => Effect.Effect<void>;
236 readonly refreshStatus: (
237 cwd: string,
238 options?: { readonly localOnly?: boolean },
239 ) => Effect.Effect<VcsRefreshStatusResult, GitManagerServiceError>;
240 readonly refreshPullRequestStatus: (
241 cwd: string,
242 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
243 readonly streamStatus: (
244 input: VcsStatusSubscriptionInput,
245 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
246 }
247>()("t3/vcs/VcsStatusBroadcaster") {}
248
249function fingerprintStatusPart(status: unknown): string {
250 return JSON.stringify(status);
251}
252
253const normalizeCwd = (cwd: string) =>
254 Effect.service(FileSystem.FileSystem).pipe(
255 Effect.flatMap((fs) => fs.realPath(cwd)),
256 Effect.orElseSucceed(() => cwd),
257 );
258
259/** @public */
260export const make = Effect.gen(function* () {
261 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
262 const autoPullPolicy = yield* VcsAutoPullPolicy;
263 const workflow = yield* GitWorkflowService.GitWorkflowService;
264 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
265 const fs = yield* FileSystem.FileSystem;
266 const path = yield* Path.Path;
267 const changesPubSub = yield* Effect.acquireRelease(
268 PubSub.unbounded<VcsStatusChange>(),
269 (pubsub) => PubSub.shutdown(pubsub),
270 );
271 const branchChangesPubSub = yield* Effect.acquireRelease(
272 PubSub.unbounded<{
273 readonly cwd: string;
274 readonly refName: string | null;
275 readonly isRepo: boolean;
276 readonly revision: number;
277 }>(),
278 (pubsub) => PubSub.shutdown(pubsub),
279 );
280 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
281 Scope.close(scope, Exit.void),
282 );
283 const detailedSubscribers = new Map<string, number>();
284 const branches = new Map<
285 string,
286 {
287 readonly refName: string | null;
288 readonly isRepo: boolean;
289 readonly revision: number;
290 readonly observation: number;
291 }
292 >();
293 let branchRevision = 0;
294 // A slow detailed read must not replace a newer HEAD-only observation.
295 let branchObservation = 0;
296 const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
297 cwd: string,
298 { refName, isRepo }: { readonly refName: string | null; readonly isRepo: boolean },
299 observation: number,
300 ) {
301 const previous = branches.get(cwd);
302 if (previous && previous.observation > observation) return;
303 if (previous?.refName === refName && previous.isRepo === isRepo) {
304 branches.set(cwd, { ...previous, observation });
305 return;
306 }
307 const revision = ++branchRevision;
308 branches.set(cwd, { refName, isRepo, revision, observation });
309 yield* PubSub.publish(branchChangesPubSub, { cwd, refName, isRepo, revision });
310 });
311 const localRefreshLocks = yield* KeyedLock.make<string>();
312 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
313 // One permit per cwd for remote reads that write the cache. Without it a
314 // periodic poll that started before an agent creates a PR can finish after the
315 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
316 const remoteWriteLocks = yield* KeyedLock.make<string>();
317 const activeRemoteReads = new Map<string, number>();
318 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
319 Effect.acquireUseRelease(
320 Effect.sync(() => activeRemoteReads.set(cwd, (activeRemoteReads.get(cwd) ?? 0) + 1)),
321 () => remoteWriteLocks.withLock(cwd, effect),
322 () =>
323 Effect.sync(() => {
324 const remaining = (activeRemoteReads.get(cwd) ?? 1) - 1;
325 if (remaining === 0) activeRemoteReads.delete(cwd);
326 else activeRemoteReads.set(cwd, remaining);
327 }).pipe(Effect.andThen(trimCachedStatuses)),
328 );
329 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
330 const headWatchersRef = yield* SynchronizedRef.make(new Map<string, ActiveHeadWatcher>());
331 // A refresh that started after a request saw every change that request could mean, so queued
332 // callers share it instead of each running git status again.
333 const localRefreshRequests = new Map<string, number>();
334 // Upstream details the turn-end refreshLocalStatus just read, handed once to the PR lookup that
335 // follows it so the same no-fetch read is not repeated. Any remote write in between drops them.
336 const upstreamReads = new Map<string, GitVcsDriver.GitRemoteStatusDetails>();
337 const localRefreshResults = new Map<
338 string,
339 {
340 readonly startedAt: number;
341 readonly local: VcsStatusLocalResult;
342 readonly includesBranchChanges: boolean;
343 }
344 >();
345
346 // Keep watched snapshots and remote operations coherent until their consumers finish.
347 const evictExcessStatuses = (cache: Map<string, CachedVcsStatus>, retainedCwd?: string) => {
348 for (const candidate of cache.keys()) {
349 if (cache.size <= VCS_STATUS_CACHE_CAPACITY) break;
350 if (
351 candidate === retainedCwd ||
352 detailedSubscribers.has(candidate) ||
353 activeRemoteReads.has(candidate)
354 )
355 continue;
356 cache.delete(candidate);
357 // A queued caller can read git again. Keep the monotonic request counter so it cannot
358 // mistake an older result for a later request.
359 localRefreshResults.delete(candidate);
360 upstreamReads.delete(candidate);
361 }
362 return cache;
363 };
364 const trimCachedStatuses = Ref.update(cacheRef, (cache) => evictExcessStatuses(new Map(cache)));
365 const retainCachedStatus = (
366 cache: ReadonlyMap<string, CachedVcsStatus>,
367 cwd: string,
368 status: CachedVcsStatus,
369 ) => {
370 const next = new Map(cache);
371 next.delete(cwd);
372 next.set(cwd, status);
373 return evictExcessStatuses(next, cwd);
374 };
375
376 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
377 cwd: string,
378 ) {
379 return yield* Ref.modify(cacheRef, (cache) => {
380 const cached = cache.get(cwd) ?? null;
381 return [cached, cached ? retainCachedStatus(cache, cwd, cached) : cache] as const;
382 });
383 });
384
385 // Only full subscribers and direct reads show Changes totals. Command palette rows subscribe
386 // without remote status and skip them, which halves the git processes a burst of rows spawns.
387 const branchChangesDemand = new Map<string, number>();
388 const wantsBranchChanges = (cwd: string) => branchChangesDemand.has(cwd);
389 const acquireBranchChangesDemand = (cwd: string) =>
390 Effect.acquireRelease(
391 Effect.sync(() => {
392 branchChangesDemand.set(cwd, (branchChangesDemand.get(cwd) ?? 0) + 1);
393 }),
394 () =>
395 Effect.sync(() => {
396 const count = (branchChangesDemand.get(cwd) ?? 1) - 1;
397 if (count > 0) branchChangesDemand.set(cwd, count);
398 else branchChangesDemand.delete(cwd);
399 }),
400 );
401
402 const readLocalStatus = Effect.fn("VcsStatusBroadcaster.readLocalStatus")(function* (
403 cwd: string,
404 ) {
405 const includeBranchChanges = wantsBranchChanges(cwd);
406 const local = yield* workflow.localStatus({ cwd }, { includeBranchChanges });
407 // A subscriber that shows totals arrived during the read and must not receive it without them.
408 if (!includeBranchChanges && wantsBranchChanges(cwd)) {
409 return {
410 local: yield* workflow.localStatus({ cwd }, { includeBranchChanges: true }),
411 includesBranchChanges: true,
412 };
413 }
414 return { local, includesBranchChanges: includeBranchChanges };
415 });
416
417 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
418 function* (
419 cwd: string,
420 read: { readonly local: VcsStatusLocalResult; readonly includesBranchChanges: boolean },
421 observation: number,
422 options?: { publish?: boolean },
423 ) {
424 const { local, includesBranchChanges } = read;
425 const nextLocal = {
426 fingerprint: fingerprintStatusPart(local),
427 value: local,
428 includesBranchChanges,
429 };
430 const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
431 const previous = cache.get(cwd) ?? { local: null, remote: null };
432 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
433 return [
434 [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
435 retainCachedStatus(cache, cwd, { local: nextLocal, remote }),
436 ] as const;
437 });
438 yield* publishBranch(cwd, local, observation);
439 if (options?.publish && remoteCleared) {
440 yield* PubSub.publish(changesPubSub, {
441 cwd,
442 event: { _tag: "remoteUpdated", remote: null },
443 });
444 }
445 if (options?.publish && localChanged) {
446 yield* PubSub.publish(changesPubSub, {
447 cwd,
448 event: { _tag: "localUpdated", local },
449 });
450 }
451 return local;
452 },
453 );
454
455 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
456 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
457 upstreamReads.delete(cwd);
458 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
459 const previous = cache.get(cwd) ?? { local: null, remote: null };
460 const next = remote?.branch === previous.local?.value.refName ? remote : null;
461 return [
462 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
463 retainCachedStatus(cache, cwd, { ...previous, remote: next }),
464 ] as const;
465 });
466 if (options?.publish && changed) {
467 yield* PubSub.publish(changesPubSub, {
468 cwd,
469 event: { _tag: "remoteUpdated", remote: value },
470 });
471 }
472 return value;
473 },
474 );
475
476 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
477 cwd: string,
478 options?: { publish?: boolean },
479 ) {
480 const observation = ++branchObservation;
481 return yield* updateCachedLocalStatus(cwd, yield* readLocalStatus(cwd), observation, options);
482 });
483
484 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
485 function* (cwd: string) {
486 const cached = yield* getCachedStatus(cwd);
487 if (cached?.local) {
488 if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) {
489 const branch = yield* workflow.currentBranch(cwd);
490 if (branch === cached.local.value.refName) return cached.local.value;
491 }
492 yield* workflow.invalidateLocalStatus(cwd);
493 return yield* loadLocalStatus(cwd, { publish: true });
494 }
495 return yield* loadLocalStatus(cwd);
496 },
497 );
498
499 const getOrLoadLocalStatus = (cwd: string) =>
500 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
501
502 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
503 const cached = yield* getCachedStatus(cwd);
504 if (cached?.local) {
505 return { local: cached.local.value, remote: cached.remote?.value ?? null };
506 }
507 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
508 });
509
510 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
511
512 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
513 "VcsStatusBroadcaster.getStatus",
514 )(function* (input) {
515 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
516 yield* acquireBranchChangesDemand(cwd);
517 yield* getOrLoadLocalStatus(cwd);
518 const cached = yield* getCachedStatus(cwd);
519 if (cached?.local && cached.remote) {
520 return mergeGitStatusParts(cached.local.value, cached.remote.value);
521 }
522 return yield* withRemoteWriteLock(
523 cwd,
524 Effect.gen(function* () {
525 const latest = yield* getCachedStatus(cwd);
526 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
527 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
528 yield* updateCachedRemoteStatus(cwd, remote);
529 const parts = yield* getStatusParts(cwd);
530 return mergeGitStatusParts(parts.local, parts.remote);
531 }),
532 );
533 }, Effect.scoped);
534
535 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
536 function* (cwd: string) {
537 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
538 localRefreshRequests.set(cwd, requestedAt);
539 return yield* localRefreshLocks.withLock(
540 cwd,
541 Effect.gen(function* () {
542 const shared = localRefreshResults.get(cwd);
543 if (
544 shared !== undefined &&
545 shared.startedAt >= requestedAt &&
546 (shared.includesBranchChanges || !wantsBranchChanges(cwd))
547 ) {
548 return shared.local;
549 }
550 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
551 yield* workflow.invalidateLocalStatus(cwd);
552 const observation = ++branchObservation;
553 const read = yield* readLocalStatus(cwd);
554 localRefreshResults.set(cwd, { startedAt, ...read });
555 return yield* updateCachedLocalStatus(cwd, read, observation, { publish: true });
556 }),
557 );
558 },
559 );
560
561 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
562 "VcsStatusBroadcaster.refreshLocalStatus",
563 )(function* (rawCwd) {
564 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
565 upstreamReads.delete(cwd);
566 const local = yield* refreshLocalStatusCore(cwd);
567 const cached = yield* getCachedStatus(cwd);
568 // Divergence is local Git data; a slow forge lookup must not delay turn-end updates.
569 if (cached?.remote?.value?.hasUpstream) {
570 const divergence = yield* workflow.upstreamDivergence(cwd);
571 const latest = yield* getCachedStatus(cwd);
572 if (divergence && latest?.remote?.value && latest.remote.branch === divergence.refName) {
573 const value = {
574 ...latest.remote.value,
575 aheadCount: divergence.aheadCount,
576 behindCount: divergence.behindCount,
577 };
578 yield* updateCachedRemoteStatus(
579 cwd,
580 {
581 branch: divergence.refName,
582 value,
583 fingerprint: fingerprintStatusPart(value),
584 },
585 { publish: true },
586 );
587 upstreamReads.set(cwd, divergence.details);
588 }
589 }
590 return local;
591 });
592
593 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
594 cwd: string,
595 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
596 ) {
597 const branch = yield* workflow.currentBranch(cwd);
598 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
599 yield* workflow.invalidateRemoteStatus(cwd);
600 const previousRemote = (yield* getCachedStatus(cwd))?.remote;
601 const { statusDetails, ...remoteOptions } = options ?? {};
602 const remote = yield* workflow.remoteStatus(
603 { cwd },
604 statusDetails?.branch === branch ? { ...remoteOptions, statusDetails } : remoteOptions,
605 );
606 const latest = yield* getCachedStatus(cwd);
607 // An overlapping turn refresh and fetch can both move divergence during the forge lookup.
608 const refreshed =
609 remote?.hasUpstream && latest?.remote !== previousRemote && latest?.remote?.branch === branch
610 ? yield* workflow.upstreamDivergence(cwd)
611 : null;
612 const value =
613 remote && refreshed?.refName === branch
614 ? { ...remote, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount }
615 : remote;
616 const currentBranch = yield* workflow.currentBranch(cwd);
617 const cached = yield* getCachedStatus(cwd);
618 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
619 yield* refreshLocalStatusCore(cwd);
620 }
621 return branch === currentBranch
622 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
623 : null;
624 });
625
626 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
627 cwd: string,
628 remoteRead: CachedRemoteStatus | null,
629 policyCwds: ReadonlyArray<string>,
630 ) {
631 const remote = remoteRead?.value ?? null;
632 let pullAttempted = false;
633 return yield* Effect.gen(function* () {
634 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
635 concurrency: "unbounded",
636 })).some(Boolean);
637 if (
638 remote === null ||
639 !remote.hasUpstream ||
640 remote.aheadCount > 0 ||
641 remote.behindCount <= 0 ||
642 !autoPullEnabled
643 ) {
644 return null;
645 }
646
647 yield* workflow.invalidateLocalStatus(cwd);
648 const local = yield* workflow.localStatus({ cwd });
649 if (
650 !local.isRepo ||
651 !local.isDefaultRef ||
652 local.hasWorkingTreeChanges ||
653 local.refName !== remoteRead?.branch
654 )
655 return null;
656
657 pullAttempted = true;
658 yield* workflow.pullCurrentBranch(cwd);
659 yield* workflow.invalidateStatus(cwd);
660 yield* refreshLocalStatusCore(cwd);
661 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
662 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
663 return yield* getStatusParts(cwd);
664 }).pipe(
665 Effect.catch((error) =>
666 Effect.gen(function* () {
667 yield* Effect.logWarning("Automatic project pull failed", {
668 cwdLength: cwd.length,
669 errorTag: error._tag,
670 });
671 if (!pullAttempted) return null;
672 // A pull or its follow-up reads can fail after local state has changed.
673 // Let a failed reconciliation reach the caller instead of publishing old status.
674 yield* refreshLocalStatusCore(cwd);
675 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
676 return yield* getStatusParts(cwd);
677 }),
678 ),
679 );
680 });
681
682 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
683 cwd: string,
684 options?: {
685 readonly refreshUpstream?: boolean;
686 readonly policyCwds?: ReadonlyArray<string>;
687 /** Refs seen by this caller's last local read; skips the re-read while they hold. */
688 readonly refsAtLocalRead?: Ref.Ref<string | null>;
689 },
690 ) {
691 return yield* withRemoteWriteLock(
692 cwd,
693 Effect.gen(function* () {
694 const remoteRead = yield* readRemoteStatus(cwd, options);
695 const pulled =
696 options?.refreshUpstream === false
697 ? null
698 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
699 if (pulled !== null) return pulled.remote;
700 // Base refs and merge bases can move without changing divergence counts.
701 const refsAtLocalRead = options?.refsAtLocalRead;
702 if (refsAtLocalRead === undefined) {
703 yield* refreshLocalStatusCore(cwd);
704 } else {
705 const refs = yield* workflow.readLocalStatusRefSnapshot(cwd);
706 if (refs === null || refs !== (yield* Ref.get(refsAtLocalRead))) {
707 yield* Ref.set(refsAtLocalRead, null);
708 yield* refreshLocalStatusCore(cwd);
709 yield* Ref.set(refsAtLocalRead, refs);
710 }
711 }
712 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
713 }),
714 );
715 });
716
717 const refreshRemoteAndLocalTotals = Effect.fn("VcsStatusBroadcaster.refreshRemoteAndLocalTotals")(
718 function* (cwd: string, policyCwd: string, refsBeforeLocalRead: string | null) {
719 return yield* withRemoteWriteLock(
720 cwd,
721 Effect.gen(function* () {
722 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
723 // Bump the PR lookup epoch after earlier remote writers have finished.
724 yield* workflow.invalidateStatus(cwd);
725 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
726 // Without a fetch, the cached behind count cannot justify an automatic pull.
727 const pulled = refreshUpstream
728 ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd])
729 : null;
730 if (pulled !== null) {
731 return { status: mergeGitStatusParts(pulled.local, pulled.remote), refs: null };
732 }
733 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
734 // A fetch, ours or not, can move the base used for local Changes totals.
735 const refs =
736 refsBeforeLocalRead === null ? null : yield* workflow.readLocalStatusRefSnapshot(cwd);
737 if (refs === null || refs !== refsBeforeLocalRead) {
738 yield* refreshLocalStatusCore(cwd);
739 }
740 const parts = yield* getStatusParts(cwd);
741 return { status: mergeGitStatusParts(parts.local, parts.remote), refs };
742 }),
743 );
744 },
745 );
746
747 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
748 "VcsStatusBroadcaster.refreshStatus",
749 )(function* (rawCwd, options) {
750 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
751 yield* acquireBranchChangesDemand(cwd);
752 // Lets the client keep its cached branch list when refs and worktree paths match its last refresh.
753 const withRefsDigest = (status: VcsStatusResult, refs: string | null) =>
754 refs === null
755 ? status
756 : {
757 ...status,
758 refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32),
759 };
760 if (options?.localOnly) {
761 const [refs] = yield* Effect.all(
762 [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)],
763 { concurrency: "unbounded" },
764 );
765 // Never cache a remote here: readers take `value: null` as "read and found no PR".
766 const parts = yield* getStatusParts(cwd);
767 return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs);
768 }
769 const refsBeforeLocalRead = yield* workflow.readLocalStatusRefSnapshot(cwd);
770 yield* refreshLocalStatusCore(cwd);
771 const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead);
772 return withRefsDigest(
773 status,
774 refs === null ? null : yield* workflow.readRefSnapshot(cwd, refs),
775 );
776 }, Effect.scoped);
777
778 const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn(
779 "VcsStatusBroadcaster.refreshAfterCheckout",
780 )(function* (rawCwd) {
781 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
782 const localDone = yield* Deferred.make<void>();
783 // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct.
784 yield* refreshLocalStatusCore(cwd).pipe(
785 Effect.ensuring(Deferred.succeed(localDone, undefined)),
786 Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd, null)),
787 Effect.ignoreCause({ log: true }),
788 Effect.forkIn(broadcasterScope),
789 );
790 yield* Deferred.await(localDone);
791 });
792
793 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
794 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
795 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
796 return yield* withRemoteWriteLock(
797 cwd,
798 Effect.gen(function* () {
799 const cached = yield* getCachedStatus(cwd);
800 if (!cached || cached.remote?.value === null) return null;
801 // Turn completion must update divergence even when background polling is paused.
802 const statusDetails = upstreamReads.get(cwd);
803 upstreamReads.delete(cwd);
804 const remoteRead = yield* readRemoteStatus(cwd, {
805 refreshUpstream: false,
806 refreshMissingPullRequest: true,
807 ...(statusDetails ? { statusDetails } : {}),
808 });
809 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
810 }),
811 );
812 });
813
814 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
815 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
816 cwd: string,
817 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
818 refreshImmediately: boolean,
819 ) {
820 const consecutiveFailuresRef = yield* Ref.make(0);
821 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
822 const refsAtLocalReadRef = yield* Ref.make<string | null>(null);
823 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
824 const configuredInterval = yield* automaticFetchInterval;
825 const activeInterval = Duration.isZero(configuredInterval)
826 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
827 : configuredInterval;
828 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
829 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
830 return activeInterval;
831 }
832
833 const demandCwds = yield* Ref.get(demandCwdsRef);
834 const shouldRun =
835 needsInitialRefresh ||
836 (yield* Effect.forEach(
837 [...demandCwds.keys()],
838 (demandCwd) =>
839 backgroundPolicy.shouldRunScopeWork({
840 type: "vcs-status",
841 cwd: demandCwd,
842 }),
843 { concurrency: "unbounded" },
844 )).some(Boolean);
845 if (!shouldRun) {
846 return activeInterval;
847 }
848
849 const exit = yield* refreshRemoteStatus(cwd, {
850 refreshUpstream: !Duration.isZero(configuredInterval),
851 policyCwds: [...demandCwds.keys()],
852 refsAtLocalRead: refsAtLocalReadRef,
853 }).pipe(Effect.exit);
854 if (Exit.isSuccess(exit)) {
855 yield* Ref.set(needsInitialRefreshRef, false);
856 yield* Ref.set(consecutiveFailuresRef, 0);
857 return activeInterval;
858 }
859
860 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
861 if (interruptionReasons.length > 0) {
862 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
863 }
864
865 const consecutiveFailures = yield* Ref.updateAndGet(
866 consecutiveFailuresRef,
867 (count) => count + 1,
868 );
869 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
870 yield* Effect.logWarning("VCS remote status refresh failed", {
871 cwdLength: cwd.length,
872 ...remoteRefreshFailureDiagnostics(exit.cause),
873 consecutiveFailures,
874 nextDelayMs: Duration.toMillis(nextDelay),
875 });
876 return nextDelay;
877 });
878
879 if (!refreshImmediately) {
880 const configuredInterval = yield* automaticFetchInterval;
881 yield* Effect.sleep(
882 Duration.isZero(configuredInterval)
883 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
884 : configuredInterval,
885 );
886 }
887
888 return yield* refreshRemoteStatusIfEnabled.pipe(
889 Effect.repeat(
890 Schedule.identity<Duration.Duration>().pipe(
891 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
892 ),
893 ),
894 Effect.asVoid,
895 );
896 });
897
898 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
899 cwd: string,
900 demandCwd: string,
901 refreshImmediately: boolean,
902 ) {
903 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
904 const existing = activePollers.get(cwd);
905 if (existing) {
906 return Ref.update(existing.demandCwds, (demandCwds) => {
907 const next = new Map(demandCwds);
908 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
909 return next;
910 }).pipe(
911 Effect.map(() => {
912 const nextPollers = new Map(activePollers);
913 nextPollers.set(cwd, {
914 ...existing,
915 subscriberCount: existing.subscriberCount + 1,
916 });
917 return [undefined, nextPollers] as const;
918 }),
919 );
920 }
921
922 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
923 Effect.flatMap((demandCwds) =>
924 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
925 Effect.forkIn(broadcasterScope),
926 Effect.map((fiber) => {
927 const nextPollers = new Map(activePollers);
928 nextPollers.set(cwd, {
929 fiber,
930 subscriberCount: 1,
931 demandCwds,
932 });
933 return [undefined, nextPollers] as const;
934 }),
935 ),
936 ),
937 );
938 });
939 });
940
941 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
942 cwd: string,
943 demandCwd: string,
944 ) {
945 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
946 const existing = activePollers.get(cwd);
947 if (!existing) {
948 return Effect.succeed([null, activePollers] as const);
949 }
950
951 if (existing.subscriberCount > 1) {
952 return Ref.update(existing.demandCwds, (demandCwds) => {
953 const nextDemandCwds = new Map(demandCwds);
954 const count = nextDemandCwds.get(demandCwd) ?? 0;
955 if (count <= 1) {
956 nextDemandCwds.delete(demandCwd);
957 } else {
958 nextDemandCwds.set(demandCwd, count - 1);
959 }
960 return nextDemandCwds;
961 }).pipe(
962 Effect.as([
963 null,
964 new Map(activePollers).set(cwd, {
965 ...existing,
966 subscriberCount: existing.subscriberCount - 1,
967 }),
968 ] as const),
969 );
970 }
971
972 return Effect.succeed([
973 existing.fiber,
974 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
975 ] as const);
976 });
977
978 if (pollerToInterrupt) {
979 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
980 }
981 });
982
983 // A request made during a refresh needs a read that starts after it, so overlapping requests
984 // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it.
985 // Missing means idle; null means running with no follow-up queued.
986 type SharedRefresh = Deferred.Deferred<VcsRefreshStatusResult, GitManagerServiceError>;
987 const queuedRefreshesRef = yield* Ref.make(new Map<string, SharedRefresh | null>());
988
989 const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* (
990 rawCwd: string,
991 first: SharedRefresh,
992 ) {
993 let next: SharedRefresh | null = first;
994 while (next !== null) {
995 yield* Deferred.into(refreshStatus(rawCwd), next);
996 next = yield* Ref.modify(queuedRefreshesRef, (queued) => {
997 const followUp = queued.get(rawCwd) ?? null;
998 const nextQueued = new Map(queued);
999 if (followUp === null) {
1000 nextQueued.delete(rawCwd);
1001 } else {
1002 nextQueued.set(rawCwd, null);
1003 }
1004 return [followUp, nextQueued] as const;
1005 });
1006 }
1007 });
1008
1009 const shareQueuedRefreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
1010 "VcsStatusBroadcaster.shareQueuedRefreshStatus",
1011 )(function* (rawCwd, options) {
1012 if (options?.localOnly) return yield* refreshStatus(rawCwd, options);
1013 const requested = yield* Deferred.make<VcsRefreshStatusResult, GitManagerServiceError>();
1014 // Registering and forking together keeps an interrupt from leaving an entry with no worker.
1015 const shared = yield* Effect.uninterruptible(
1016 Effect.gen(function* () {
1017 const followUp = yield* Ref.modify(
1018 queuedRefreshesRef,
1019 (queued): readonly [SharedRefresh | undefined, Map<string, SharedRefresh | null>] => {
1020 if (!queued.has(rawCwd)) return [undefined, new Map(queued).set(rawCwd, null)];
1021 const followUp = queued.get(rawCwd) ?? requested;
1022 return [followUp, new Map(queued).set(rawCwd, followUp)];
1023 },
1024 );
1025 if (followUp !== undefined) return followUp;
1026 // The broadcaster scope owns the work, so one caller's interrupt does not cancel it for the rest.
1027 yield* runQueuedRefreshes(rawCwd, requested).pipe(Effect.forkIn(broadcasterScope));
1028 return requested;
1029 }),
1030 );
1031 return yield* Deferred.await(shared);
1032 });
1033
1034 const readHeadBranch = Effect.fn("VcsStatusBroadcaster.readHeadBranch")(function* (cwd: string) {
1035 const observation = ++branchObservation;
1036 const refName = yield* workflow.currentBranch(cwd);
1037 // A null branch is a detached HEAD or a checkout that is gone, such as a removed worktree.
1038 const isRepo = refName !== null || (yield* workflow.repositoryRoot(cwd)) !== null;
1039 return { observation, refName, isRepo };
1040 });
1041
1042 // Keep cache invalidation serialized with detailed reads and refreshes.
1043 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
1044 (cwd: string) =>
1045 localRefreshLocks.withLock(
1046 cwd,
1047 Effect.gen(function* () {
1048 if (detailedSubscribers.has(cwd)) {
1049 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
1050 return (
1051 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
1052 );
1053 }
1054 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1055 // HEAD cannot certify working-tree totals, even when it has not moved.
1056 localRefreshResults.delete(cwd);
1057 yield* workflow.invalidateLocalStatus(cwd);
1058 yield* Ref.update(cacheRef, (cache) => {
1059 const previous = cache.get(cwd);
1060 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
1061 });
1062 if (detailedSubscribers.has(cwd)) {
1063 const local = yield* loadLocalStatus(cwd, { publish: true });
1064 return (
1065 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
1066 );
1067 }
1068 yield* publishBranch(cwd, { refName, isRepo }, observation);
1069 return branches.get(cwd) ?? { refName, isRepo, revision: 0 };
1070 }),
1071 ),
1072 );
1073
1074 // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
1075 // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
1076 const publishCheckedOutRef = Effect.fn("VcsStatusBroadcaster.publishCheckedOutRef")(function* (
1077 cwd: string,
1078 ) {
1079 if (!detailedSubscribers.has(cwd)) return yield* refreshBranchStatusCore(cwd);
1080 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1081 yield* publishBranch(cwd, { refName, isRepo }, observation);
1082 });
1083
1084 const reconcileCheckedOutRef = Effect.fn("VcsStatusBroadcaster.reconcileCheckedOutRef")(
1085 function* (cwd: string) {
1086 if (!detailedSubscribers.has(cwd)) return;
1087 if ((yield* getCachedStatus(cwd))?.remote) {
1088 yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
1089 } else {
1090 yield* refreshLocalStatusCore(cwd);
1091 }
1092 },
1093 );
1094
1095 const retryCheckedOutRef = <E>(cwd: string, refresh: Effect.Effect<unknown, E>) =>
1096 refresh.pipe(
1097 Effect.retry(CHECKOUT_REFRESH_RETRY),
1098 Effect.catchCause((cause) =>
1099 Effect.logWarning("VCS checked-out ref refresh failed", {
1100 cwdLength: cwd.length,
1101 ...remoteRefreshFailureDiagnostics(cause),
1102 }),
1103 ),
1104 );
1105
1106 // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
1107 const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
1108 const headPath = yield* workflow.headPath(cwd);
1109 if (headPath === null) return;
1110 const headDirectory = path.dirname(headPath);
1111 // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
1112 yield* fs
1113 .watch(headDirectory, {
1114 onReady: () => Deferred.doneUnsafe(ready, Exit.void),
1115 })
1116 .pipe(
1117 // On Windows a watch outlives its deleted directory and reports it ~150k times a second.
1118 Stream.takeUntilEffect((event) =>
1119 event._tag === "Remove"
1120 ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists))
1121 : Effect.succeed(false),
1122 ),
1123 Stream.filter((event) => path.basename(event.path) === "HEAD"),
1124 // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
1125 Stream.buffer({ capacity: 1, strategy: "sliding" }),
1126 Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))),
1127 // Detailed status waits behind its own reads; the branch keeps up on the stage above.
1128 Stream.buffer({ capacity: 1, strategy: "sliding" }),
1129 Stream.runForEach(() => retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd))),
1130 );
1131 });
1132
1133 const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
1134 cwd: string,
1135 ) {
1136 const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
1137 const existing = activeWatchers.get(cwd);
1138 if (existing && existing.fiber.pollUnsafe() === undefined) {
1139 const nextWatchers = new Map(activeWatchers).set(cwd, {
1140 ...existing,
1141 subscriberCount: existing.subscriberCount + 1,
1142 });
1143 return Effect.succeed([existing.ready, nextWatchers] as const);
1144 }
1145 // A watch that ended, say before the repository existed, restarts for everyone holding it.
1146 return Effect.gen(function* () {
1147 const ready = yield* Deferred.make<void>();
1148 const fiber = yield* watchHead(cwd, ready).pipe(
1149 Effect.catchCause((cause) =>
1150 Effect.logWarning("VCS HEAD watch failed", {
1151 cwdLength: cwd.length,
1152 ...remoteRefreshFailureDiagnostics(cause),
1153 }),
1154 ),
1155 // Subscribers wait for the watch, so one that cannot start must not hold them.
1156 Effect.ensuring(Deferred.succeed(ready, undefined)),
1157 Effect.forkIn(broadcasterScope),
1158 );
1159 const nextWatchers = new Map(activeWatchers).set(cwd, {
1160 fiber,
1161 ready,
1162 subscriberCount: (existing?.subscriberCount ?? 0) + 1,
1163 });
1164 return [ready, nextWatchers] as const;
1165 });
1166 });
1167 yield* Deferred.await(ready);
1168 });
1169
1170 const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
1171 cwd: string,
1172 ) {
1173 const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
1174 const existing = activeWatchers.get(cwd);
1175 if (!existing) return [null, activeWatchers] as const;
1176 const nextWatchers = new Map(activeWatchers);
1177 if (existing.subscriberCount > 1) {
1178 nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
1179 return [null, nextWatchers] as const;
1180 }
1181 nextWatchers.delete(cwd);
1182 return [existing.fiber, nextWatchers] as const;
1183 });
1184 if (watcherToInterrupt) {
1185 yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
1186 }
1187 });
1188
1189 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
1190 Stream.unwrap(
1191 Effect.gen(function* () {
1192 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1193 yield* Effect.acquireRelease(
1194 Effect.sync(() => {
1195 const previous = detailedSubscribers.get(cwd) ?? 0;
1196 detailedSubscribers.set(cwd, previous + 1);
1197 }),
1198 () =>
1199 Effect.sync(() => {
1200 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
1201 if (remaining === 0) detailedSubscribers.delete(cwd);
1202 else detailedSubscribers.set(cwd, remaining);
1203 }).pipe(Effect.andThen(trimCachedStatuses)),
1204 );
1205 if (input.includeRemote !== false) yield* acquireBranchChangesDemand(cwd);
1206 const subscription = yield* PubSub.subscribe(changesPubSub);
1207 // Watch before reading so a checkout in between still publishes.
1208 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1209 const initialLocal = yield* getOrLoadLocalStatus(cwd);
1210 const cachedStatus = yield* getCachedStatus(cwd);
1211 const initialRemote = cachedStatus?.remote?.value ?? null;
1212 if (input.includeRemote !== false) {
1213 yield* retainRemotePoller(
1214 cwd,
1215 input.cwd,
1216 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
1217 );
1218 }
1219 const release =
1220 input.includeRemote === false
1221 ? Effect.void
1222 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
1223
1224 return Stream.concat(
1225 Stream.make({
1226 _tag: "snapshot" as const,
1227 local: initialLocal,
1228 remote: initialRemote,
1229 }),
1230 Stream.fromSubscription(subscription).pipe(
1231 Stream.filter((event) => event.cwd === cwd),
1232 Stream.map((event) => event.event),
1233 ),
1234 ).pipe(Stream.ensuring(release));
1235 }),
1236 );
1237
1238 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
1239 "VcsStatusBroadcaster.refreshBranchStatus",
1240 )(function* (input) {
1241 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1242 if (!detailedSubscribers.has(cwd)) {
1243 const { refName, isRepo } = yield* refreshBranchStatusCore(cwd);
1244 return { refName, isRepo };
1245 }
1246 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1247 yield* publishBranch(cwd, { refName, isRepo }, observation);
1248 yield* refreshBranchStatusCore(cwd).pipe(
1249 Effect.catchCause((cause) =>
1250 Effect.logWarning("VCS branch refresh failed", {
1251 cwdLength: cwd.length,
1252 ...remoteRefreshFailureDiagnostics(cause),
1253 }),
1254 ),
1255 Effect.forkIn(broadcasterScope),
1256 );
1257 return { refName, isRepo };
1258 });
1259
1260 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
1261 Stream.unwrap(
1262 Effect.gen(function* () {
1263 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1264 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
1265 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1266 const branch = yield* refreshBranchStatusCore(cwd);
1267 return Stream.concat(
1268 Stream.make({ refName: branch.refName, isRepo: branch.isRepo }),
1269 Stream.fromSubscription(subscription).pipe(
1270 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
1271 Stream.map(({ refName, isRepo }) => ({ refName, isRepo })),
1272 ),
1273 ).pipe(
1274 Stream.changesWith(
1275 (left, right) => left.refName === right.refName && left.isRepo === right.isRepo,
1276 ),
1277 );
1278 }),
1279 );
1280
1281 return VcsStatusBroadcaster.of({
1282 streamBranchStatus,
1283 refreshBranchStatus,
1284 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
1285 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
1286 ),
1287 getStatus,
1288 refreshLocalStatus,
1289 refreshAfterCheckout,
1290 refreshStatus: shareQueuedRefreshStatus,
1291 refreshPullRequestStatus,
1292 streamStatus,
1293 });
1294});
1295
1296export const layer = Layer.effect(VcsStatusBroadcaster, make);