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

VcsStatusBroadcaster.ts

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