Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VcsStatusBroadcaster.ts

1,338 lines51.5 KB

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);
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 }
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;
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 }
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 };
137​
138interface VcsStatusChange {
139 readonly cwd: string;
140 readonly event: VcsStatusStreamEvent;
142​
143interface CachedValue<T> {
144 readonly fingerprint: string;
145 readonly value: T;
147​
148interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
149 readonly branch: string | null;
151​
152interface CachedLocalStatus extends CachedValue<VcsStatusLocalResult> {
153 readonly includesBranchChanges: boolean;
155​
156interface CachedVcsStatus {
157 readonly local: CachedLocalStatus | null;
158 readonly remote: CachedRemoteStatus | null;
160​
161interface ActiveHeadWatcher {
162 readonly fiber: Fiber.Fiber<void, never>;
163 readonly ready: Deferred.Deferred<void>;
164 readonly subscriberCount: number;
166​
167interface ActiveRemotePoller {
168 readonly fiber: Fiber.Fiber<void, never>;
169 readonly subscriberCount: number;
170 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
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);
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);
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 // A branch read while a HEAD watch was ready stays current for that watch's lifetime: any
485 // checkout after it reaches the cache through the watch. A reconnect burst then forks git once.
486 const branchConfirmedUnder = new Map<string, Fiber.Fiber<void, never>>();
487 // Bumped on every HEAD event, so a read that a checkout overtook cannot confirm its branch.
488 const headGenerations = new Map<string, number>();
489 const readyHeadWatch = (cwd: string) =>
490 SynchronizedRef.get(headWatchersRef).pipe(
491 Effect.map((watchers) => {
492 const watcher = watchers.get(cwd);
493 return watcher &&
494 watcher.fiber.pollUnsafe() === undefined &&
495 Deferred.isDoneUnsafe(watcher.ready)
496 ? watcher.fiber
497 : undefined;
498 }),
499 );
500​
501 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
502 function* (cwd: string) {
503 const watch = yield* readyHeadWatch(cwd);
504 const generation = headGenerations.get(cwd);
505 const confirm = <A>(value: A) => {
506 if (watch !== undefined && headGenerations.get(cwd) === generation) {
507 branchConfirmedUnder.set(cwd, watch);
508 }
509 return value;
510 };
511 const cached = yield* getCachedStatus(cwd);
512 if (cached?.local) {
513 if (cached.local.includesBranchChanges || !wantsBranchChanges(cwd)) {
514 if (watch !== undefined && branchConfirmedUnder.get(cwd) === watch) {
515 return cached.local.value;
516 }
517 const branch = yield* workflow.currentBranch(cwd);
518 if (branch === cached.local.value.refName) return confirm(cached.local.value);
519 }
520 yield* workflow.invalidateLocalStatus(cwd);
521 return confirm(yield* loadLocalStatus(cwd, { publish: true }));
522 }
523 return confirm(yield* loadLocalStatus(cwd));
524 },
525 );
526​
527 const getOrLoadLocalStatus = (cwd: string) =>
528 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
529​
530 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
531 const cached = yield* getCachedStatus(cwd);
532 if (cached?.local) {
533 return { local: cached.local.value, remote: cached.remote?.value ?? null };
534 }
535 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
536 });
537​
538 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
539​
540 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
541 "VcsStatusBroadcaster.getStatus",
542 )(function* (input) {
543 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
544 yield* acquireBranchChangesDemand(cwd);
545 yield* getOrLoadLocalStatus(cwd);
546 const cached = yield* getCachedStatus(cwd);
547 if (cached?.local && cached.remote) {
548 return mergeGitStatusParts(cached.local.value, cached.remote.value);
549 }
550 return yield* withRemoteWriteLock(
551 cwd,
552 Effect.gen(function* () {
553 const latest = yield* getCachedStatus(cwd);
554 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
555 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
556 yield* updateCachedRemoteStatus(cwd, remote);
557 const parts = yield* getStatusParts(cwd);
558 return mergeGitStatusParts(parts.local, parts.remote);
559 }),
560 );
561 }, Effect.scoped);
562​
563 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
564 function* (cwd: string) {
565 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
566 localRefreshRequests.set(cwd, requestedAt);
567 return yield* localRefreshLocks.withLock(
568 cwd,
569 Effect.gen(function* () {
570 const shared = localRefreshResults.get(cwd);
571 if (
572 shared !== undefined &&
573 shared.startedAt >= requestedAt &&
574 (shared.includesBranchChanges || !wantsBranchChanges(cwd))
575 ) {
576 return shared.local;
577 }
578 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
579 yield* workflow.invalidateLocalStatus(cwd);
580 const observation = ++branchObservation;
581 const read = yield* readLocalStatus(cwd);
582 localRefreshResults.set(cwd, { startedAt, ...read });
583 return yield* updateCachedLocalStatus(cwd, read, observation, { publish: true });
584 }),
585 );
586 },
587 );
588​
589 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
590 "VcsStatusBroadcaster.refreshLocalStatus",
591 )(function* (rawCwd) {
592 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
593 upstreamReads.delete(cwd);
594 const local = yield* refreshLocalStatusCore(cwd);
595 const cached = yield* getCachedStatus(cwd);
596 // Divergence is local Git data; a slow forge lookup must not delay turn-end updates.
597 if (cached?.remote?.value?.hasUpstream) {
598 const divergence = yield* workflow.upstreamDivergence(cwd);
599 const latest = yield* getCachedStatus(cwd);
600 if (divergence && latest?.remote?.value && latest.remote.branch === divergence.refName) {
601 const value = {
602 ...latest.remote.value,
603 aheadCount: divergence.aheadCount,
604 behindCount: divergence.behindCount,
605 };
606 yield* updateCachedRemoteStatus(
607 cwd,
608 {
609 branch: divergence.refName,
610 value,
611 fingerprint: fingerprintStatusPart(value),
612 },
613 { publish: true },
614 );
615 upstreamReads.set(cwd, divergence.details);
616 }
617 }
618 return local;
619 });
620​
621 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
622 cwd: string,
623 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
624 ) {
625 const branch = yield* workflow.currentBranch(cwd);
626 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
627 yield* workflow.invalidateRemoteStatus(cwd);
628 const previousRemote = (yield* getCachedStatus(cwd))?.remote;
629 const { statusDetails, ...remoteOptions } = options ?? {};
630 const remote = yield* workflow.remoteStatus(
631 { cwd },
632 statusDetails?.branch === branch ? { ...remoteOptions, statusDetails } : remoteOptions,
633 );
634 const latest = yield* getCachedStatus(cwd);
635 // An overlapping turn refresh and fetch can both move divergence during the forge lookup.
636 const refreshed =
637 remote?.hasUpstream && latest?.remote !== previousRemote && latest?.remote?.branch === branch
638 ? yield* workflow.upstreamDivergence(cwd)
639 : null;
640 const value =
641 remote && refreshed?.refName === branch
642 ? { ...remote, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount }
643 : remote;
644 const currentBranch = yield* workflow.currentBranch(cwd);
645 const cached = yield* getCachedStatus(cwd);
646 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
647 yield* refreshLocalStatusCore(cwd);
648 }
649 return branch === currentBranch
650 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
651 : null;
652 });
653​
654 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
655 cwd: string,
656 remoteRead: CachedRemoteStatus | null,
657 policyCwds: ReadonlyArray<string>,
658 ) {
659 const remote = remoteRead?.value ?? null;
660 let pullAttempted = false;
661 return yield* Effect.gen(function* () {
662 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
663 concurrency: "unbounded",
664 })).some(Boolean);
665 if (
666 remote === null ||
667 !remote.hasUpstream ||
668 remote.aheadCount > 0 ||
669 remote.behindCount <= 0 ||
670 !autoPullEnabled
671 ) {
672 return null;
673 }
674​
675 yield* workflow.invalidateLocalStatus(cwd);
676 const local = yield* workflow.localStatus({ cwd });
677 if (
678 !local.isRepo ||
679 !local.isDefaultRef ||
680 local.hasWorkingTreeChanges ||
681 local.refName !== remoteRead?.branch
682 )
683 return null;
684​
685 pullAttempted = true;
686 yield* workflow.pullCurrentBranch(cwd);
687 yield* workflow.invalidateStatus(cwd);
688 yield* refreshLocalStatusCore(cwd);
689 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
690 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
691 return yield* getStatusParts(cwd);
692 }).pipe(
693 Effect.catch((error) =>
694 Effect.gen(function* () {
695 yield* Effect.logWarning("Automatic project pull failed", {
696 cwdLength: cwd.length,
697 errorTag: error._tag,
698 });
699 if (!pullAttempted) return null;
700 // A pull or its follow-up reads can fail after local state has changed.
701 // Let a failed reconciliation reach the caller instead of publishing old status.
702 yield* refreshLocalStatusCore(cwd);
703 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
704 return yield* getStatusParts(cwd);
705 }),
706 ),
707 );
708 });
709​
710 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
711 cwd: string,
712 options?: {
713 readonly refreshUpstream?: boolean;
714 readonly policyCwds?: ReadonlyArray<string>;
715 /** Refs seen by this caller's last local read; skips the re-read while they hold. */
716 readonly refsAtLocalRead?: Ref.Ref<string | null>;
717 },
718 ) {
719 return yield* withRemoteWriteLock(
720 cwd,
721 Effect.gen(function* () {
722 const remoteRead = yield* readRemoteStatus(cwd, options);
723 const pulled =
724 options?.refreshUpstream === false
725 ? null
726 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
727 if (pulled !== null) return pulled.remote;
728 // Base refs and merge bases can move without changing divergence counts.
729 const refsAtLocalRead = options?.refsAtLocalRead;
730 if (refsAtLocalRead === undefined) {
731 yield* refreshLocalStatusCore(cwd);
732 } else {
733 const refs = yield* workflow.readLocalStatusRefSnapshot(cwd);
734 if (refs === null || refs !== (yield* Ref.get(refsAtLocalRead))) {
735 yield* Ref.set(refsAtLocalRead, null);
736 yield* refreshLocalStatusCore(cwd);
737 yield* Ref.set(refsAtLocalRead, refs);
738 }
739 }
740 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
741 }),
742 );
743 });
744​
745 const refreshRemoteAndLocalTotals = Effect.fn("VcsStatusBroadcaster.refreshRemoteAndLocalTotals")(
746 function* (cwd: string, policyCwd: string, refsBeforeLocalRead: string | null) {
747 return yield* withRemoteWriteLock(
748 cwd,
749 Effect.gen(function* () {
750 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
751 // Bump the PR lookup epoch after earlier remote writers have finished.
752 yield* workflow.invalidateStatus(cwd);
753 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
754 // Without a fetch, the cached behind count cannot justify an automatic pull.
755 const pulled = refreshUpstream
756 ? yield* maybeAutoPull(cwd, remoteRead, [policyCwd])
757 : null;
758 if (pulled !== null) {
759 return { status: mergeGitStatusParts(pulled.local, pulled.remote), refs: null };
760 }
761 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
762 // A fetch, ours or not, can move the base used for local Changes totals.
763 const refs =
764 refsBeforeLocalRead === null ? null : yield* workflow.readLocalStatusRefSnapshot(cwd);
765 if (refs === null || refs !== refsBeforeLocalRead) {
766 yield* refreshLocalStatusCore(cwd);
767 }
768 const parts = yield* getStatusParts(cwd);
769 return { status: mergeGitStatusParts(parts.local, parts.remote), refs };
770 }),
771 );
772 },
773 );
774​
775 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
776 "VcsStatusBroadcaster.refreshStatus",
777 )(function* (rawCwd, options) {
778 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
779 yield* acquireBranchChangesDemand(cwd);
780 // Lets the client keep its cached branch list when refs and worktree paths match its last refresh.
781 const withRefsDigest = (status: VcsStatusResult, refs: string | null) =>
782 refs === null
783 ? status
784 : {
785 ...status,
786 refsDigest: NodeCrypto.createHash("sha256").update(refs).digest("hex").slice(0, 32),
787 };
788 if (options?.localOnly) {
789 const [refs] = yield* Effect.all(
790 [workflow.readRefSnapshot(cwd), refreshLocalStatusCore(cwd)],
791 { concurrency: "unbounded" },
792 );
793 // Never cache a remote here: readers take `value: null` as "read and found no PR".
794 const parts = yield* getStatusParts(cwd);
795 return withRefsDigest(mergeGitStatusParts(parts.local, parts.remote), refs);
796 }
797 const refsBeforeLocalRead = yield* workflow.readLocalStatusRefSnapshot(cwd);
798 yield* refreshLocalStatusCore(cwd);
799 const { status, refs } = yield* refreshRemoteAndLocalTotals(cwd, rawCwd, refsBeforeLocalRead);
800 return withRefsDigest(
801 status,
802 refs === null ? null : yield* workflow.readRefSnapshot(cwd, refs),
803 );
804 }, Effect.scoped);
805​
806 const refreshAfterCheckout: VcsStatusBroadcaster["Service"]["refreshAfterCheckout"] = Effect.fn(
807 "VcsStatusBroadcaster.refreshAfterCheckout",
808 )(function* (rawCwd) {
809 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
810 const localDone = yield* Deferred.make<void>();
811 // Owned by the broadcaster so a client disconnecting mid-switch still leaves status correct.
812 yield* refreshLocalStatusCore(cwd).pipe(
813 Effect.ensuring(Deferred.succeed(localDone, undefined)),
814 Effect.andThen(refreshRemoteAndLocalTotals(cwd, rawCwd, null)),
815 Effect.ignoreCause({ log: true }),
816 Effect.forkIn(broadcasterScope),
817 );
818 yield* Deferred.await(localDone);
819 });
820​
821 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
822 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
823 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
824 return yield* withRemoteWriteLock(
825 cwd,
826 Effect.gen(function* () {
827 const cached = yield* getCachedStatus(cwd);
828 if (!cached || cached.remote?.value === null) return null;
829 // Turn completion must update divergence even when background polling is paused.
830 const statusDetails = upstreamReads.get(cwd);
831 upstreamReads.delete(cwd);
832 const remoteRead = yield* readRemoteStatus(cwd, {
833 refreshUpstream: false,
834 refreshMissingPullRequest: true,
835 ...(statusDetails ? { statusDetails } : {}),
836 });
837 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
838 }),
839 );
840 });
841​
842 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
843 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
844 cwd: string,
845 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
846 refreshImmediately: boolean,
847 ) {
848 const consecutiveFailuresRef = yield* Ref.make(0);
849 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
850 const refsAtLocalReadRef = yield* Ref.make<string | null>(null);
851 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
852 const configuredInterval = yield* automaticFetchInterval;
853 const activeInterval = Duration.isZero(configuredInterval)
854 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
855 : configuredInterval;
856 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
857 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
858 return activeInterval;
859 }
860​
861 const demandCwds = yield* Ref.get(demandCwdsRef);
862 const shouldRun =
863 needsInitialRefresh ||
864 (yield* Effect.forEach(
865 [...demandCwds.keys()],
866 (demandCwd) =>
867 backgroundPolicy.shouldRunScopeWork({
868 type: "vcs-status",
869 cwd: demandCwd,
870 }),
871 { concurrency: "unbounded" },
872 )).some(Boolean);
873 if (!shouldRun) {
874 return activeInterval;
875 }
876​
877 const exit = yield* refreshRemoteStatus(cwd, {
878 refreshUpstream: !Duration.isZero(configuredInterval),
879 policyCwds: [...demandCwds.keys()],
880 refsAtLocalRead: refsAtLocalReadRef,
881 }).pipe(Effect.exit);
882 if (Exit.isSuccess(exit)) {
883 yield* Ref.set(needsInitialRefreshRef, false);
884 yield* Ref.set(consecutiveFailuresRef, 0);
885 return activeInterval;
886 }
887​
888 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
889 if (interruptionReasons.length > 0) {
890 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
891 }
892​
893 const consecutiveFailures = yield* Ref.updateAndGet(
894 consecutiveFailuresRef,
895 (count) => count + 1,
896 );
897 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
898 yield* Effect.logWarning("VCS remote status refresh failed", {
899 cwdLength: cwd.length,
900 ...remoteRefreshFailureDiagnostics(exit.cause),
901 consecutiveFailures,
902 nextDelayMs: Duration.toMillis(nextDelay),
903 });
904 return nextDelay;
905 });
906​
907 if (!refreshImmediately) {
908 const configuredInterval = yield* automaticFetchInterval;
909 yield* Effect.sleep(
910 Duration.isZero(configuredInterval)
911 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
912 : configuredInterval,
913 );
914 }
915​
916 return yield* refreshRemoteStatusIfEnabled.pipe(
917 Effect.repeat(
918 Schedule.identity<Duration.Duration>().pipe(
919 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
920 ),
921 ),
922 Effect.asVoid,
923 );
924 });
925​
926 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
927 cwd: string,
928 demandCwd: string,
929 refreshImmediately: boolean,
930 ) {
931 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
932 const existing = activePollers.get(cwd);
933 if (existing) {
934 return Ref.update(existing.demandCwds, (demandCwds) => {
935 const next = new Map(demandCwds);
936 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
937 return next;
938 }).pipe(
939 Effect.map(() => {
940 const nextPollers = new Map(activePollers);
941 nextPollers.set(cwd, {
942 ...existing,
943 subscriberCount: existing.subscriberCount + 1,
944 });
945 return [undefined, nextPollers] as const;
946 }),
947 );
948 }
949​
950 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
951 Effect.flatMap((demandCwds) =>
952 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
953 Effect.forkIn(broadcasterScope),
954 Effect.map((fiber) => {
955 const nextPollers = new Map(activePollers);
956 nextPollers.set(cwd, {
957 fiber,
958 subscriberCount: 1,
959 demandCwds,
960 });
961 return [undefined, nextPollers] as const;
962 }),
963 ),
964 ),
965 );
966 });
967 });
968​
969 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
970 cwd: string,
971 demandCwd: string,
972 ) {
973 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
974 const existing = activePollers.get(cwd);
975 if (!existing) {
976 return Effect.succeed([null, activePollers] as const);
977 }
978​
979 if (existing.subscriberCount > 1) {
980 return Ref.update(existing.demandCwds, (demandCwds) => {
981 const nextDemandCwds = new Map(demandCwds);
982 const count = nextDemandCwds.get(demandCwd) ?? 0;
983 if (count <= 1) {
984 nextDemandCwds.delete(demandCwd);
985 } else {
986 nextDemandCwds.set(demandCwd, count - 1);
987 }
988 return nextDemandCwds;
989 }).pipe(
990 Effect.as([
991 null,
992 new Map(activePollers).set(cwd, {
993 ...existing,
994 subscriberCount: existing.subscriberCount - 1,
995 }),
996 ] as const),
997 );
998 }
999​
1000 return Effect.succeed([
1001 existing.fiber,
1002 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
1003 ] as const);
1004 });
1005​
1006 if (pollerToInterrupt) {
1007 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
1009 });
1010​
1011 // A request made during a refresh needs a read that starts after it, so overlapping requests
1012 // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it.
1013 // Missing means idle; null means running with no follow-up queued.
1014 type SharedRefresh = Deferred.Deferred<VcsRefreshStatusResult, GitManagerServiceError>;
1015 const queuedRefreshesRef = yield* Ref.make(new Map<string, SharedRefresh | null>());
1016​
1017 const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* (
1018 rawCwd: string,
1019 first: SharedRefresh,
1020 ) {
1021 let next: SharedRefresh | null = first;
1022 while (next !== null) {
1023 yield* Deferred.into(refreshStatus(rawCwd), next);
1024 next = yield* Ref.modify(queuedRefreshesRef, (queued) => {
1025 const followUp = queued.get(rawCwd) ?? null;
1026 const nextQueued = new Map(queued);
1027 if (followUp === null) {
1028 nextQueued.delete(rawCwd);
1029 } else {
1030 nextQueued.set(rawCwd, null);
1032 return [followUp, nextQueued] as const;
1033 });
1035 });
1036​
1037 const shareQueuedRefreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
1038 "VcsStatusBroadcaster.shareQueuedRefreshStatus",
1039 )(function* (rawCwd, options) {
1040 if (options?.localOnly) return yield* refreshStatus(rawCwd, options);
1041 const requested = yield* Deferred.make<VcsRefreshStatusResult, GitManagerServiceError>();
1042 // Registering and forking together keeps an interrupt from leaving an entry with no worker.
1043 const shared = yield* Effect.uninterruptible(
1044 Effect.gen(function* () {
1045 const followUp = yield* Ref.modify(
1046 queuedRefreshesRef,
1047 (queued): readonly [SharedRefresh | undefined, Map<string, SharedRefresh | null>] => {
1048 if (!queued.has(rawCwd)) return [undefined, new Map(queued).set(rawCwd, null)];
1049 const followUp = queued.get(rawCwd) ?? requested;
1050 return [followUp, new Map(queued).set(rawCwd, followUp)];
1051 },
1052 );
1053 if (followUp !== undefined) return followUp;
1054 // The broadcaster scope owns the work, so one caller's interrupt does not cancel it for the rest.
1055 yield* runQueuedRefreshes(rawCwd, requested).pipe(Effect.forkIn(broadcasterScope));
1056 return requested;
1057 }),
1058 );
1059 return yield* Deferred.await(shared);
1060 });
1061​
1062 const readHeadBranch = Effect.fn("VcsStatusBroadcaster.readHeadBranch")(function* (cwd: string) {
1063 const observation = ++branchObservation;
1064 const refName = yield* workflow.currentBranch(cwd);
1065 // A null branch is a detached HEAD or a checkout that is gone, such as a removed worktree.
1066 const isRepo = refName !== null || (yield* workflow.repositoryRoot(cwd)) !== null;
1067 return { observation, refName, isRepo };
1068 });
1069​
1070 // Keep cache invalidation serialized with detailed reads and refreshes.
1071 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
1072 (cwd: string) =>
1073 localRefreshLocks.withLock(
1074 cwd,
1075 Effect.gen(function* () {
1076 if (detailedSubscribers.has(cwd)) {
1077 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
1078 return (
1079 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
1080 );
1082 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1083 // HEAD cannot certify working-tree totals, even when it has not moved.
1084 localRefreshResults.delete(cwd);
1085 yield* workflow.invalidateLocalStatus(cwd);
1086 yield* Ref.update(cacheRef, (cache) => {
1087 const previous = cache.get(cwd);
1088 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
1089 });
1090 if (detailedSubscribers.has(cwd)) {
1091 const local = yield* loadLocalStatus(cwd, { publish: true });
1092 return (
1093 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
1094 );
1096 yield* publishBranch(cwd, { refName, isRepo }, observation);
1097 return branches.get(cwd) ?? { refName, isRepo, revision: 0 };
1098 }),
1099 ),
1100 );
1101​
1102 // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
1103 // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
1104 const publishCheckedOutRef = Effect.fn("VcsStatusBroadcaster.publishCheckedOutRef")(function* (
1105 cwd: string,
1106 ) {
1107 if (!detailedSubscribers.has(cwd)) return yield* refreshBranchStatusCore(cwd);
1108 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1109 yield* publishBranch(cwd, { refName, isRepo }, observation);
1110 });
1111​
1112 const reconcileCheckedOutRef = Effect.fn("VcsStatusBroadcaster.reconcileCheckedOutRef")(
1113 function* (cwd: string) {
1114 if (!detailedSubscribers.has(cwd)) return;
1115 if ((yield* getCachedStatus(cwd))?.remote) {
1116 yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
1117 } else {
1118 yield* refreshLocalStatusCore(cwd);
1120 },
1121 );
1122​
1123 const retryCheckedOutRef = <E>(cwd: string, refresh: Effect.Effect<unknown, E>) =>
1124 refresh.pipe(
1125 Effect.retry(CHECKOUT_REFRESH_RETRY),
1126 Effect.catchCause((cause) =>
1127 Effect.logWarning("VCS checked-out ref refresh failed", {
1128 cwdLength: cwd.length,
1129 ...remoteRefreshFailureDiagnostics(cause),
1130 }),
1131 ),
1132 );
1133​
1134 // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
1135 const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
1136 const headPath = yield* workflow.headPath(cwd);
1137 if (headPath === null) return;
1138 const headDirectory = path.dirname(headPath);
1139 // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
1140 yield* fs
1141 .watch(headDirectory, {
1142 onReady: () => Deferred.doneUnsafe(ready, Exit.void),
1143 })
1144 .pipe(
1145 // On Windows a watch outlives its deleted directory and reports it ~150k times a second.
1146 Stream.takeUntilEffect((event) =>
1147 event._tag === "Remove"
1148 ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists))
1149 : Effect.succeed(false),
1150 ),
1151 // A terminal commit moves the branch ref but not HEAD; it always rewrites the index beside it.
1152 Stream.filter((event) => {
1153 const name = path.basename(event.path);
1154 return name === "HEAD" || name === "index";
1155 }),
1156 // On arrival: the cache keeps the old branch until reads below land, and they can retry.
1157 Stream.tap(() =>
1158 Effect.sync(() => {
1159 branchConfirmedUnder.delete(cwd);
1160 headGenerations.set(cwd, (headGenerations.get(cwd) ?? 0) + 1);
1161 }),
1162 ),
1163 // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
1164 Stream.buffer({ capacity: 1, strategy: "sliding" }),
1165 Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))),
1166 // Detailed status waits behind its own reads; the branch keeps up on the stage above.
1167 Stream.buffer({ capacity: 1, strategy: "sliding" }),
1168 Stream.runForEach(() => retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd))),
1169 );
1170 });
1171​
1172 const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
1173 cwd: string,
1174 ) {
1175 const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
1176 const existing = activeWatchers.get(cwd);
1177 if (existing && existing.fiber.pollUnsafe() === undefined) {
1178 const nextWatchers = new Map(activeWatchers).set(cwd, {
1179 ...existing,
1180 subscriberCount: existing.subscriberCount + 1,
1181 });
1182 return Effect.succeed([existing.ready, nextWatchers] as const);
1184 // A watch that ended, say before the repository existed, restarts for everyone holding it.
1185 return Effect.gen(function* () {
1186 const ready = yield* Deferred.make<void>();
1187 const fiber = yield* watchHead(cwd, ready).pipe(
1188 Effect.catchCause((cause) =>
1189 Effect.logWarning("VCS HEAD watch failed", {
1190 cwdLength: cwd.length,
1191 ...remoteRefreshFailureDiagnostics(cause),
1192 }),
1193 ),
1194 // Subscribers wait for the watch, so one that cannot start must not hold them.
1195 Effect.ensuring(Deferred.succeed(ready, undefined)),
1196 Effect.forkIn(broadcasterScope),
1197 );
1198 const nextWatchers = new Map(activeWatchers).set(cwd, {
1199 fiber,
1200 ready,
1201 subscriberCount: (existing?.subscriberCount ?? 0) + 1,
1202 });
1203 return [ready, nextWatchers] as const;
1204 });
1205 });
1206 yield* Deferred.await(ready);
1207 });
1208​
1209 const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
1210 cwd: string,
1211 ) {
1212 const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
1213 const existing = activeWatchers.get(cwd);
1214 if (!existing) return [null, activeWatchers] as const;
1215 const nextWatchers = new Map(activeWatchers);
1216 if (existing.subscriberCount > 1) {
1217 nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
1218 return [null, nextWatchers] as const;
1220 nextWatchers.delete(cwd);
1221 // In this step, so a watch that registers next for cwd cannot lose its generation.
1222 if (branchConfirmedUnder.get(cwd) === existing.fiber) branchConfirmedUnder.delete(cwd);
1223 headGenerations.delete(cwd);
1224 return [existing.fiber, nextWatchers] as const;
1225 });
1226 if (watcherToInterrupt) {
1227 yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
1229 });
1230​
1231 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
1232 Stream.unwrap(
1233 Effect.gen(function* () {
1234 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1235 yield* Effect.acquireRelease(
1236 Effect.sync(() => {
1237 const previous = detailedSubscribers.get(cwd) ?? 0;
1238 detailedSubscribers.set(cwd, previous + 1);
1239 }),
1240 () =>
1241 Effect.sync(() => {
1242 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
1243 if (remaining === 0) detailedSubscribers.delete(cwd);
1244 else detailedSubscribers.set(cwd, remaining);
1245 }).pipe(Effect.andThen(trimCachedStatuses)),
1246 );
1247 if (input.includeRemote !== false) yield* acquireBranchChangesDemand(cwd);
1248 const subscription = yield* PubSub.subscribe(changesPubSub);
1249 // Watch before reading so a checkout in between still publishes.
1250 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1251 const initialLocal = yield* getOrLoadLocalStatus(cwd);
1252 const cachedStatus = yield* getCachedStatus(cwd);
1253 const initialRemote = cachedStatus?.remote?.value ?? null;
1254 if (input.includeRemote !== false) {
1255 yield* retainRemotePoller(
1256 cwd,
1257 input.cwd,
1258 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
1259 );
1261 const release =
1262 input.includeRemote === false
1263 ? Effect.void
1264 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
1265​
1266 return Stream.concat(
1267 Stream.make({
1268 _tag: "snapshot" as const,
1269 local: initialLocal,
1270 remote: initialRemote,
1271 }),
1272 Stream.fromSubscription(subscription).pipe(
1273 Stream.filter((event) => event.cwd === cwd),
1274 Stream.map((event) => event.event),
1275 ),
1276 ).pipe(Stream.ensuring(release));
1277 }),
1278 );
1279​
1280 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
1281 "VcsStatusBroadcaster.refreshBranchStatus",
1282 )(function* (input) {
1283 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1284 if (!detailedSubscribers.has(cwd)) {
1285 const { refName, isRepo } = yield* refreshBranchStatusCore(cwd);
1286 return { refName, isRepo };
1288 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1289 yield* publishBranch(cwd, { refName, isRepo }, observation);
1290 yield* refreshBranchStatusCore(cwd).pipe(
1291 Effect.catchCause((cause) =>
1292 Effect.logWarning("VCS branch refresh failed", {
1293 cwdLength: cwd.length,
1294 ...remoteRefreshFailureDiagnostics(cause),
1295 }),
1296 ),
1297 Effect.forkIn(broadcasterScope),
1298 );
1299 return { refName, isRepo };
1300 });
1301​
1302 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
1303 Stream.unwrap(
1304 Effect.gen(function* () {
1305 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1306 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
1307 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1308 const branch = yield* refreshBranchStatusCore(cwd);
1309 return Stream.concat(
1310 Stream.make({ refName: branch.refName, isRepo: branch.isRepo }),
1311 Stream.fromSubscription(subscription).pipe(
1312 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
1313 Stream.map(({ refName, isRepo }) => ({ refName, isRepo })),
1314 ),
1315 ).pipe(
1316 Stream.changesWith(
1317 (left, right) => left.refName === right.refName && left.isRepo === right.isRepo,
1318 ),
1319 );
1320 }),
1321 );
1322​
1323 return VcsStatusBroadcaster.of({
1324 streamBranchStatus,
1325 refreshBranchStatus,
1326 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
1327 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
1328 ),
1329 getStatus,
1330 refreshLocalStatus,
1331 refreshAfterCheckout,
1332 refreshStatus: shareQueuedRefreshStatus,
1333 refreshPullRequestStatus,
1334 streamStatus,
1335 });
1336});
1337​
1338export const layer = Layer.effect(VcsStatusBroadcaster, make);