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

VcsStatusBroadcaster.ts

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