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