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

VcsStatusBroadcaster.ts

1,160 lines43.8 KB

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