The best way to control Claude Code, Codex and more from any computer or phone

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