Open History to see the last commit
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);
51}
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 }
70}
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;
86}
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 }
96}
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 };
130}
131
132interface VcsStatusChange {
133 readonly cwd: string;
134 readonly event: VcsStatusStreamEvent;
135}
136
137interface CachedValue<T> {
138 readonly fingerprint: string;
139 readonly value: T;
140}
141
142interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
143 readonly branch: string | null;
144}
145
146interface CachedVcsStatus {
147 readonly local: CachedValue<VcsStatusLocalResult> | null;
148 readonly remote: CachedRemoteStatus | null;
149}
150
151interface ActiveHeadWatcher {
152 readonly fiber: Fiber.Fiber<void, never>;
153 readonly ready: Deferred.Deferred<void>;
154 readonly subscriberCount: number;
155}
156
157interface ActiveRemotePoller {
158 readonly fiber: Fiber.Fiber<void, never>;
159 readonly subscriberCount: number;
160 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
161}
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);
218}
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 readonly refreshStatus: (
240 cwd: string,
241 options?: { readonly localOnly?: boolean },
242 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
243 readonly refreshPullRequestStatus: (
244 cwd: string,
245 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
246 readonly streamStatus: (
247 input: VcsStatusSubscriptionInput,
248 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
249 }
250>()("t3/vcs/VcsStatusBroadcaster") {}
251
252function fingerprintStatusPart(status: unknown): string {
253 return JSON.stringify(status);
254}
255
256const normalizeCwd = (cwd: string) =>
257 Effect.service(FileSystem.FileSystem).pipe(
258 Effect.flatMap((fs) => fs.realPath(cwd)),
259 Effect.orElseSucceed(() => cwd),
260 );
261
262/** @public */
263export const make = Effect.gen(function* () {
264 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
265 const autoPullPolicy = yield* VcsAutoPullPolicy;
266 const workflow = yield* GitWorkflowService.GitWorkflowService;
267 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
268 const fs = yield* FileSystem.FileSystem;
269 const path = yield* Path.Path;
270 const changesPubSub = yield* Effect.acquireRelease(
271 PubSub.unbounded<VcsStatusChange>(),
272 (pubsub) => PubSub.shutdown(pubsub),
273 );
274 const branchChangesPubSub = yield* Effect.acquireRelease(
275 PubSub.unbounded<{
276 readonly cwd: string;
277 readonly refName: string | null;
278 readonly isRepo: boolean;
279 readonly revision: number;
280 }>(),
281 (pubsub) => PubSub.shutdown(pubsub),
282 );
283 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
284 Scope.close(scope, Exit.void),
285 );
286 const detailedSubscribers = new Map<string, number>();
287 const branches = new Map<
288 string,
289 { readonly refName: string | null; readonly isRepo: boolean; readonly revision: number }
290 >();
291 let branchRevision = 0;
292 const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
293 cwd: string,
294 { refName, isRepo }: { readonly refName: string | null; readonly isRepo: boolean },
295 ) {
296 const previous = branches.get(cwd);
297 if (previous?.refName === refName && previous.isRepo === isRepo) return;
298 const revision = ++branchRevision;
299 branches.set(cwd, { refName, isRepo, revision });
300 yield* PubSub.publish(branchChangesPubSub, { cwd, refName, isRepo, revision });
301 });
302 const localRefreshLocks = yield* KeyedLock.make<string>();
303 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
304 // One permit per cwd for remote reads that write the cache. Without it a
305 // periodic poll that started before an agent creates a PR can finish after the
306 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
307 const remoteWriteLocks = yield* KeyedLock.make<string>();
308 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
309 remoteWriteLocks.withLock(cwd, effect);
310 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
311 const headWatchersRef = yield* SynchronizedRef.make(new Map<string, ActiveHeadWatcher>());
312
313 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
314 cwd: string,
315 ) {
316 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
317 });
318
319 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
320 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
321 const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
322 const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
323 const previous = cache.get(cwd) ?? { local: null, remote: null };
324 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
325 return [
326 [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
327 new Map(cache).set(cwd, { local: nextLocal, remote }),
328 ] as const;
329 });
330 yield* publishBranch(cwd, local);
331 if (options?.publish && remoteCleared) {
332 yield* PubSub.publish(changesPubSub, {
333 cwd,
334 event: { _tag: "remoteUpdated", remote: null },
335 });
336 }
337 if (options?.publish && localChanged) {
338 yield* PubSub.publish(changesPubSub, {
339 cwd,
340 event: { _tag: "localUpdated", local },
341 });
342 }
343 return local;
344 },
345 );
346
347 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
348 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
349 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
350 const previous = cache.get(cwd) ?? { local: null, remote: null };
351 const next = remote?.branch === previous.local?.value.refName ? remote : null;
352 return [
353 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
354 new Map(cache).set(cwd, { ...previous, remote: next }),
355 ] as const;
356 });
357 if (options?.publish && changed) {
358 yield* PubSub.publish(changesPubSub, {
359 cwd,
360 event: { _tag: "remoteUpdated", remote: value },
361 });
362 }
363 return value;
364 },
365 );
366
367 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
368 cwd: string,
369 ) {
370 const local = yield* workflow.localStatus({ cwd });
371 return yield* updateCachedLocalStatus(cwd, local);
372 });
373
374 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
375 function* (cwd: string) {
376 const cached = yield* getCachedStatus(cwd);
377 if (cached?.local) {
378 const branch = yield* workflow.currentBranch(cwd);
379 if (branch === cached.local.value.refName) return cached.local.value;
380 yield* workflow.invalidateLocalStatus(cwd);
381 return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), {
382 publish: true,
383 });
384 }
385 return yield* loadLocalStatus(cwd);
386 },
387 );
388
389 const getOrLoadLocalStatus = (cwd: string) =>
390 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
391
392 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
393 const cached = yield* getCachedStatus(cwd);
394 if (cached?.local) {
395 return { local: cached.local.value, remote: cached.remote?.value ?? null };
396 }
397 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
398 });
399
400 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
401
402 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
403 "VcsStatusBroadcaster.getStatus",
404 )(function* (input) {
405 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
406 yield* getOrLoadLocalStatus(cwd);
407 const cached = yield* getCachedStatus(cwd);
408 if (cached?.local && cached.remote) {
409 return mergeGitStatusParts(cached.local.value, cached.remote.value);
410 }
411 return yield* withRemoteWriteLock(
412 cwd,
413 Effect.gen(function* () {
414 const latest = yield* getCachedStatus(cwd);
415 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
416 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
417 yield* updateCachedRemoteStatus(cwd, remote);
418 const parts = yield* getStatusParts(cwd);
419 return mergeGitStatusParts(parts.local, parts.remote);
420 }),
421 );
422 });
423
424 // A refresh that started after a request saw every change that request could mean, so queued
425 // callers share it instead of each running git status again.
426 const localRefreshRequests = new Map<string, number>();
427 const localRefreshResults = new Map<
428 string,
429 { readonly startedAt: number; readonly local: VcsStatusLocalResult }
430 >();
431 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
432 function* (cwd: string) {
433 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
434 localRefreshRequests.set(cwd, requestedAt);
435 return yield* localRefreshLocks.withLock(
436 cwd,
437 Effect.gen(function* () {
438 const shared = localRefreshResults.get(cwd);
439 if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;
440 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
441 yield* workflow.invalidateLocalStatus(cwd);
442 const local = yield* workflow.localStatus({ cwd });
443 localRefreshResults.set(cwd, { startedAt, local });
444 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
445 }),
446 );
447 },
448 );
449
450 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
451 "VcsStatusBroadcaster.refreshLocalStatus",
452 )(function* (rawCwd) {
453 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
454 return yield* refreshLocalStatusCore(cwd);
455 });
456
457 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
458 cwd: string,
459 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
460 ) {
461 const branch = yield* workflow.currentBranch(cwd);
462 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
463 yield* workflow.invalidateRemoteStatus(cwd);
464 const value = yield* workflow.remoteStatus({ cwd }, options);
465 const currentBranch = yield* workflow.currentBranch(cwd);
466 const cached = yield* getCachedStatus(cwd);
467 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
468 yield* refreshLocalStatusCore(cwd);
469 }
470 return branch === currentBranch
471 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
472 : null;
473 });
474
475 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
476 cwd: string,
477 remoteRead: CachedRemoteStatus | null,
478 policyCwds: ReadonlyArray<string>,
479 ) {
480 const remote = remoteRead?.value ?? null;
481 let pullAttempted = false;
482 return yield* Effect.gen(function* () {
483 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
484 concurrency: "unbounded",
485 })).some(Boolean);
486 if (
487 remote === null ||
488 !remote.hasUpstream ||
489 remote.aheadCount > 0 ||
490 remote.behindCount <= 0 ||
491 !autoPullEnabled
492 ) {
493 return null;
494 }
495
496 yield* workflow.invalidateLocalStatus(cwd);
497 const local = yield* workflow.localStatus({ cwd });
498 if (
499 !local.isRepo ||
500 !local.isDefaultRef ||
501 local.hasWorkingTreeChanges ||
502 local.refName !== remoteRead?.branch
503 )
504 return null;
505
506 pullAttempted = true;
507 yield* workflow.pullCurrentBranch(cwd);
508 yield* workflow.invalidateStatus(cwd);
509 yield* refreshLocalStatusCore(cwd);
510 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
511 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
512 return yield* getStatusParts(cwd);
513 }).pipe(
514 Effect.catch((error) =>
515 Effect.gen(function* () {
516 yield* Effect.logWarning("Automatic project pull failed", {
517 cwdLength: cwd.length,
518 errorTag: error._tag,
519 });
520 if (!pullAttempted) return null;
521 // A pull or its follow-up reads can fail after local state has changed.
522 // Let a failed reconciliation reach the caller instead of publishing old status.
523 yield* refreshLocalStatusCore(cwd);
524 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
525 return yield* getStatusParts(cwd);
526 }),
527 ),
528 );
529 });
530
531 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
532 cwd: string,
533 options?: {
534 readonly refreshUpstream?: boolean;
535 readonly policyCwds?: ReadonlyArray<string>;
536 },
537 ) {
538 return yield* withRemoteWriteLock(
539 cwd,
540 Effect.gen(function* () {
541 const remoteRead = yield* readRemoteStatus(cwd, options);
542 const pulled =
543 options?.refreshUpstream === false
544 ? null
545 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
546 if (pulled !== null) return pulled.remote;
547 // Base refs and merge bases can move without changing divergence counts.
548 yield* refreshLocalStatusCore(cwd);
549 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
550 }),
551 );
552 });
553
554 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
555 "VcsStatusBroadcaster.refreshStatus",
556 )(function* (rawCwd, options) {
557 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
558 yield* refreshLocalStatusCore(cwd);
559 if (options?.localOnly) {
560 // Never cache a remote here: readers take `value: null` as "read and found no PR".
561 const parts = yield* getStatusParts(cwd);
562 return mergeGitStatusParts(parts.local, parts.remote);
563 }
564 return yield* withRemoteWriteLock(
565 cwd,
566 Effect.gen(function* () {
567 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
568 // Bump the PR lookup epoch after earlier remote writers have finished.
569 yield* workflow.invalidateStatus(cwd);
570 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
571 // Fetch can move the base used for local Changes totals.
572 yield* refreshLocalStatusCore(cwd);
573 // Without a fetch, the cached behind count cannot justify an automatic pull.
574 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
575 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
576 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
577 const parts = yield* getStatusParts(cwd);
578 return mergeGitStatusParts(parts.local, parts.remote);
579 }),
580 );
581 });
582
583 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
584 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
585 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
586 return yield* withRemoteWriteLock(
587 cwd,
588 Effect.gen(function* () {
589 const cached = yield* getCachedStatus(cwd);
590 if (!cached || cached.remote?.value === null) return null;
591 // Turn completion must update divergence even when background polling is paused.
592 const remoteRead = yield* readRemoteStatus(cwd, {
593 refreshUpstream: false,
594 refreshMissingPullRequest: true,
595 });
596 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
597 }),
598 );
599 });
600
601 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
602 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
603 cwd: string,
604 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
605 refreshImmediately: boolean,
606 ) {
607 const consecutiveFailuresRef = yield* Ref.make(0);
608 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
609 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
610 const configuredInterval = yield* automaticFetchInterval;
611 const activeInterval = Duration.isZero(configuredInterval)
612 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
613 : configuredInterval;
614 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
615 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
616 return activeInterval;
617 }
618
619 const demandCwds = yield* Ref.get(demandCwdsRef);
620 const shouldRun =
621 needsInitialRefresh ||
622 (yield* Effect.forEach(
623 [...demandCwds.keys()],
624 (demandCwd) =>
625 backgroundPolicy.shouldRunScopeWork({
626 type: "vcs-status",
627 cwd: demandCwd,
628 }),
629 { concurrency: "unbounded" },
630 )).some(Boolean);
631 if (!shouldRun) {
632 return activeInterval;
633 }
634
635 const exit = yield* refreshRemoteStatus(cwd, {
636 refreshUpstream: !Duration.isZero(configuredInterval),
637 policyCwds: [...demandCwds.keys()],
638 }).pipe(Effect.exit);
639 if (Exit.isSuccess(exit)) {
640 yield* Ref.set(needsInitialRefreshRef, false);
641 yield* Ref.set(consecutiveFailuresRef, 0);
642 return activeInterval;
643 }
644
645 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
646 if (interruptionReasons.length > 0) {
647 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
648 }
649
650 const consecutiveFailures = yield* Ref.updateAndGet(
651 consecutiveFailuresRef,
652 (count) => count + 1,
653 );
654 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
655 yield* Effect.logWarning("VCS remote status refresh failed", {
656 cwdLength: cwd.length,
657 ...remoteRefreshFailureDiagnostics(exit.cause),
658 consecutiveFailures,
659 nextDelayMs: Duration.toMillis(nextDelay),
660 });
661 return nextDelay;
662 });
663
664 if (!refreshImmediately) {
665 const configuredInterval = yield* automaticFetchInterval;
666 yield* Effect.sleep(
667 Duration.isZero(configuredInterval)
668 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
669 : configuredInterval,
670 );
671 }
672
673 return yield* refreshRemoteStatusIfEnabled.pipe(
674 Effect.repeat(
675 Schedule.identity<Duration.Duration>().pipe(
676 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
677 ),
678 ),
679 Effect.asVoid,
680 );
681 });
682
683 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
684 cwd: string,
685 demandCwd: string,
686 refreshImmediately: boolean,
687 ) {
688 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
689 const existing = activePollers.get(cwd);
690 if (existing) {
691 return Ref.update(existing.demandCwds, (demandCwds) => {
692 const next = new Map(demandCwds);
693 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
694 return next;
695 }).pipe(
696 Effect.map(() => {
697 const nextPollers = new Map(activePollers);
698 nextPollers.set(cwd, {
699 ...existing,
700 subscriberCount: existing.subscriberCount + 1,
701 });
702 return [undefined, nextPollers] as const;
703 }),
704 );
705 }
706
707 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
708 Effect.flatMap((demandCwds) =>
709 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
710 Effect.forkIn(broadcasterScope),
711 Effect.map((fiber) => {
712 const nextPollers = new Map(activePollers);
713 nextPollers.set(cwd, {
714 fiber,
715 subscriberCount: 1,
716 demandCwds,
717 });
718 return [undefined, nextPollers] as const;
719 }),
720 ),
721 ),
722 );
723 });
724 });
725
726 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
727 cwd: string,
728 demandCwd: string,
729 ) {
730 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
731 const existing = activePollers.get(cwd);
732 if (!existing) {
733 return Effect.succeed([null, activePollers] as const);
734 }
735
736 if (existing.subscriberCount > 1) {
737 return Ref.update(existing.demandCwds, (demandCwds) => {
738 const nextDemandCwds = new Map(demandCwds);
739 const count = nextDemandCwds.get(demandCwd) ?? 0;
740 if (count <= 1) {
741 nextDemandCwds.delete(demandCwd);
742 } else {
743 nextDemandCwds.set(demandCwd, count - 1);
744 }
745 return nextDemandCwds;
746 }).pipe(
747 Effect.as([
748 null,
749 new Map(activePollers).set(cwd, {
750 ...existing,
751 subscriberCount: existing.subscriberCount - 1,
752 }),
753 ] as const),
754 );
755 }
756
757 return Effect.succeed([
758 existing.fiber,
759 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
760 ] as const);
761 });
762
763 if (pollerToInterrupt) {
764 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
765 }
766 });
767
768 // Serialize branch publication and cache invalidation with detailed reads and refreshes.
769 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
770 (cwd: string) =>
771 localRefreshLocks.withLock(
772 cwd,
773 Effect.gen(function* () {
774 if (detailedSubscribers.has(cwd)) {
775 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
776 return {
777 refName: local.refName,
778 isRepo: local.isRepo,
779 revision: branches.get(cwd)?.revision ?? 0,
780 };
781 }
782 const refName = yield* workflow.currentBranch(cwd);
783 // A null branch is a detached HEAD or a checkout that is gone, such as a removed worktree.
784 const isRepo = refName !== null || (yield* workflow.repositoryRoot(cwd)) !== null;
785 // HEAD cannot certify working-tree totals, even when it has not moved.
786 localRefreshResults.delete(cwd);
787 yield* workflow.invalidateLocalStatus(cwd);
788 yield* Ref.update(cacheRef, (cache) => {
789 const previous = cache.get(cwd);
790 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
791 });
792 if (detailedSubscribers.has(cwd)) {
793 const local = yield* workflow.localStatus({ cwd });
794 yield* updateCachedLocalStatus(cwd, local, { publish: true });
795 return {
796 refName: local.refName,
797 isRepo: local.isRepo,
798 revision: branches.get(cwd)?.revision ?? 0,
799 };
800 }
801 yield* publishBranch(cwd, { refName, isRepo });
802 return { refName, isRepo, revision: branches.get(cwd)?.revision ?? 0 };
803 }),
804 ),
805 );
806
807 // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
808 // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
809 const refreshCheckedOutRef = Effect.fn("VcsStatusBroadcaster.refreshCheckedOutRef")(function* (
810 cwd: string,
811 ) {
812 if (!detailedSubscribers.has(cwd)) {
813 yield* refreshBranchStatusCore(cwd);
814 } else if ((yield* getCachedStatus(cwd))?.remote) {
815 yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
816 } else {
817 yield* refreshLocalStatusCore(cwd);
818 }
819 });
820
821 // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
822 const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
823 const headPath = yield* workflow.headPath(cwd);
824 if (headPath === null) return;
825 const headDirectory = path.dirname(headPath);
826 // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
827 yield* fs
828 .watch(headDirectory, {
829 onReady: () => Deferred.doneUnsafe(ready, Exit.void),
830 })
831 .pipe(
832 // On Windows a watch outlives its deleted directory and reports it ~150k times a second.
833 Stream.takeUntilEffect((event) =>
834 event._tag === "Remove"
835 ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists))
836 : Effect.succeed(false),
837 ),
838 Stream.filter((event) => path.basename(event.path) === "HEAD"),
839 // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
840 Stream.buffer({ capacity: 1, strategy: "sliding" }),
841 Stream.runForEach(() =>
842 refreshCheckedOutRef(cwd).pipe(
843 Effect.retry(CHECKOUT_REFRESH_RETRY),
844 Effect.catchCause((cause) =>
845 Effect.logWarning("VCS checked-out ref refresh failed", {
846 cwdLength: cwd.length,
847 ...remoteRefreshFailureDiagnostics(cause),
848 }),
849 ),
850 ),
851 ),
852 );
853 });
854
855 const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
856 cwd: string,
857 ) {
858 const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
859 const existing = activeWatchers.get(cwd);
860 if (existing && existing.fiber.pollUnsafe() === undefined) {
861 const nextWatchers = new Map(activeWatchers).set(cwd, {
862 ...existing,
863 subscriberCount: existing.subscriberCount + 1,
864 });
865 return Effect.succeed([existing.ready, nextWatchers] as const);
866 }
867 // A watch that ended, say before the repository existed, restarts for everyone holding it.
868 return Effect.gen(function* () {
869 const ready = yield* Deferred.make<void>();
870 const fiber = yield* watchHead(cwd, ready).pipe(
871 Effect.catchCause((cause) =>
872 Effect.logWarning("VCS HEAD watch failed", {
873 cwdLength: cwd.length,
874 ...remoteRefreshFailureDiagnostics(cause),
875 }),
876 ),
877 // Subscribers wait for the watch, so one that cannot start must not hold them.
878 Effect.ensuring(Deferred.succeed(ready, undefined)),
879 Effect.forkIn(broadcasterScope),
880 );
881 const nextWatchers = new Map(activeWatchers).set(cwd, {
882 fiber,
883 ready,
884 subscriberCount: (existing?.subscriberCount ?? 0) + 1,
885 });
886 return [ready, nextWatchers] as const;
887 });
888 });
889 yield* Deferred.await(ready);
890 });
891
892 const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
893 cwd: string,
894 ) {
895 const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
896 const existing = activeWatchers.get(cwd);
897 if (!existing) return [null, activeWatchers] as const;
898 const nextWatchers = new Map(activeWatchers);
899 if (existing.subscriberCount > 1) {
900 nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
901 return [null, nextWatchers] as const;
902 }
903 nextWatchers.delete(cwd);
904 return [existing.fiber, nextWatchers] as const;
905 });
906 if (watcherToInterrupt) {
907 yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
908 }
909 });
910
911 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
912 Stream.unwrap(
913 Effect.gen(function* () {
914 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
915 yield* Effect.acquireRelease(
916 Effect.sync(() => {
917 const previous = detailedSubscribers.get(cwd) ?? 0;
918 detailedSubscribers.set(cwd, previous + 1);
919 }),
920 () =>
921 Effect.sync(() => {
922 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
923 if (remaining === 0) detailedSubscribers.delete(cwd);
924 else detailedSubscribers.set(cwd, remaining);
925 }),
926 );
927 const subscription = yield* PubSub.subscribe(changesPubSub);
928 // Watch before reading so a checkout in between still publishes.
929 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
930 const initialLocal = yield* getOrLoadLocalStatus(cwd);
931 const cachedStatus = yield* getCachedStatus(cwd);
932 const initialRemote = cachedStatus?.remote?.value ?? null;
933 if (input.includeRemote !== false) {
934 yield* retainRemotePoller(
935 cwd,
936 input.cwd,
937 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
938 );
939 }
940 const release =
941 input.includeRemote === false
942 ? Effect.void
943 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
944
945 return Stream.concat(
946 Stream.make({
947 _tag: "snapshot" as const,
948 local: initialLocal,
949 remote: initialRemote,
950 }),
951 Stream.fromSubscription(subscription).pipe(
952 Stream.filter((event) => event.cwd === cwd),
953 Stream.map((event) => event.event),
954 ),
955 ).pipe(Stream.ensuring(release));
956 }),
957 );
958
959 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
960 "VcsStatusBroadcaster.refreshBranchStatus",
961 )(function* (input) {
962 const { refName, isRepo } = yield* refreshBranchStatusCore(
963 yield* withFileSystem(normalizeCwd(input.cwd)),
964 );
965 return { refName, isRepo };
966 });
967
968 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
969 Stream.unwrap(
970 Effect.gen(function* () {
971 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
972 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
973 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
974 const branch = yield* refreshBranchStatusCore(cwd);
975 return Stream.concat(
976 Stream.make({ refName: branch.refName, isRepo: branch.isRepo }),
977 Stream.fromSubscription(subscription).pipe(
978 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
979 Stream.map(({ refName, isRepo }) => ({ refName, isRepo })),
980 ),
981 ).pipe(
982 Stream.changesWith(
983 (left, right) => left.refName === right.refName && left.isRepo === right.isRepo,
984 ),
985 );
986 }),
987 );
988
989 return VcsStatusBroadcaster.of({
990 streamBranchStatus,
991 refreshBranchStatus,
992 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
993 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
994 ),
995 getStatus,
996 refreshLocalStatus,
997 refreshStatus,
998 refreshPullRequestStatus,
999 streamStatus,
1000 });
1001});
1002
1003export const layer = Layer.effect(VcsStatusBroadcaster, make);