Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import { assert, it, describe } from "@effect/vitest";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Deferred from "effect/Deferred";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as Scheduler from "effect/Scheduler";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import * as Tracer from "effect/Tracer";
19import type {
20 BackgroundScope,
21 VcsStatusLocalResult,
22 VcsStatusRemoteResult,
23 VcsStatusStreamEvent,
24} from "@t3tools/contracts";
25import { GitCommandError, GitManagerError } from "@t3tools/contracts";
26
27import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
28import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
29import * as GitWorkflowService from "../git/GitWorkflowService.ts";
30import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
31
32const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
33
34const baseLocalStatus: VcsStatusLocalResult = {
35 isRepo: true,
36 sourceControlProvider: {
37 kind: SourceControlProviderKind.make("github"),
38 name: "GitHub",
39 baseUrl: "https://github.com",
40 },
41 hasPrimaryRemote: true,
42 isDefaultRef: false,
43 refName: "feature/status-broadcast",
44 hasWorkingTreeChanges: false,
45 workingTree: { files: [], insertions: 0, deletions: 0 },
46};
47
48const baseRemoteStatus: VcsStatusRemoteResult = {
49 hasUpstream: true,
50 aheadCount: 0,
51 behindCount: 0,
52 pr: null,
53};
54
55const remoteStatusWithPr: VcsStatusRemoteResult = {
56 ...baseRemoteStatus,
57 pr: {
58 number: 2978,
59 title: "[codex] Rewrite client connection architecture",
60 url: "https://github.com/pingdotgg/t3code/pull/2978",
61 baseRef: "main",
62 headRef: "upstream-topic",
63 state: "open",
64 },
65};
66
67function layerTestFor(state: {
68 currentLocalStatus: VcsStatusLocalResult;
69 currentRemoteStatus: VcsStatusRemoteResult | null;
70 localStatusCalls: number;
71 remoteStatusCalls: number;
72 localInvalidationCalls: number;
73 remoteInvalidationCalls: number;
74 remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;
75 remoteStatusError?: GitManagerError;
76 backgroundWorkEnabled?: boolean;
77 automaticFetchInterval?: Effect.Effect<Duration.Duration>;
78 beforeRemoteStatus?: Effect.Effect<void>;
79 beforeLocalStatus?: Effect.Effect<void>;
80 fileSystem?: FileSystem.FileSystem;
81 pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];
82}) {
83 return VcsStatusBroadcaster.layer.pipe(
84 Layer.provideMerge(
85 state.fileSystem
86 ? Layer.succeed(FileSystem.FileSystem, state.fileSystem)
87 : NodeServices.layer,
88 ),
89 Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
90 Layer.provide(
91 Layer.succeed(
92 VcsStatusBroadcaster.VcsAutomaticFetchInterval,
93 state.automaticFetchInterval ?? Effect.succeed(Duration.seconds(30)),
94 ),
95 ),
96 Layer.provide(
97 Layer.mock(GitWorkflowService.GitWorkflowService)({
98 localStatus: () =>
99 Effect.suspend(() => {
100 state.localStatusCalls += 1;
101 return (state.beforeLocalStatus ?? Effect.void).pipe(
102 Effect.as(state.currentLocalStatus),
103 );
104 }),
105 currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName),
106 remoteStatus: (_input, options) =>
107 Effect.suspend(() => {
108 return (state.beforeRemoteStatus ?? Effect.void).pipe(
109 Effect.andThen(
110 Effect.sync(() => {
111 state.remoteStatusCalls += 1;
112 state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
113 return state.currentRemoteStatus;
114 }),
115 ),
116 Effect.tap(() =>
117 state.remoteStatusError ? Effect.fail(state.remoteStatusError) : Effect.void,
118 ),
119 );
120 }),
121 invalidateLocalStatus: () =>
122 Effect.sync(() => {
123 state.localInvalidationCalls += 1;
124 }),
125 invalidateRemoteStatus: () =>
126 Effect.sync(() => {
127 state.remoteInvalidationCalls += 1;
128 }),
129 invalidateStatus: () =>
130 Effect.sync(() => {
131 state.localInvalidationCalls += 1;
132 state.remoteInvalidationCalls += 1;
133 }),
134 ...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}),
135 }),
136 ),
137 );
138}
139
140function layerBackgroundPolicy(shouldRunScopeWork: (scope: BackgroundScope) => boolean) {
141 return Layer.mock(BackgroundPolicy.BackgroundPolicy)({
142 reportClientActivity: () => Effect.void,
143 removeRpcClient: () => Effect.void,
144 snapshot: Effect.succeed({
145 hostPower: {
146 source: "unknown",
147 idle: "unknown",
148 idleSeconds: null,
149 locked: "unknown",
150 suspended: false,
151 onBattery: "unknown",
152 lowPowerMode: "unknown",
153 thermalState: "unknown",
154 stale: true,
155 updatedAt: TEST_EPOCH,
156 },
157 leases: [],
158 activeForegroundLeaseCount: 0,
159 activeScopeKeys: [],
160 shouldRunOpportunisticWork: false,
161 updatedAt: TEST_EPOCH,
162 }),
163 shouldRunScopeWork: (scope) => Effect.sync(() => shouldRunScopeWork(scope)),
164 shouldRunOpportunisticWork: Effect.succeed(true),
165 });
166}
167
168describe("VcsStatusBroadcaster", () => {
169 it.effect("refreshes queued behind a running one share the next git status read", () => {
170 const state: Parameters<typeof layerTestFor>[0] = {
171 currentLocalStatus: baseLocalStatus,
172 currentRemoteStatus: baseRemoteStatus,
173 localStatusCalls: 0,
174 remoteStatusCalls: 0,
175 localInvalidationCalls: 0,
176 remoteInvalidationCalls: 0,
177 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
178 };
179
180 return Effect.gen(function* () {
181 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
182 const started = yield* Deferred.make<void>();
183 const release = yield* Deferred.make<void>();
184 state.beforeLocalStatus = Deferred.succeed(started, undefined).pipe(
185 Effect.andThen(Deferred.await(release)),
186 );
187 const running = yield* broadcaster
188 .refreshLocalStatus("/repo")
189 .pipe(Effect.forkScoped({ startImmediately: true }));
190 yield* Deferred.await(started);
191 // Requested while the first read runs, so that read may predate their change.
192 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
193 const queued = yield* Effect.all(
194 [broadcaster.refreshLocalStatus("/repo"), broadcaster.refreshLocalStatus("/repo")],
195 { concurrency: "unbounded" },
196 ).pipe(Effect.forkScoped({ startImmediately: true }));
197 yield* Deferred.succeed(release, undefined);
198
199 assert.isFalse((yield* Fiber.join(running)).hasWorkingTreeChanges);
200 const [second, third] = yield* Fiber.join(queued);
201 assert.isTrue(second.hasWorkingTreeChanges);
202 assert.isTrue(third.hasWorkingTreeChanges);
203 assert.strictEqual(state.localStatusCalls, 2);
204
205 yield* broadcaster.refreshLocalStatus("/repo");
206 assert.strictEqual(state.localStatusCalls, 3);
207 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
208 });
209
210 it.effect("publishes a terminal branch switch without reading remote status", () => {
211 const state = {
212 currentLocalStatus: baseLocalStatus,
213 currentRemoteStatus: remoteStatusWithPr,
214 localStatusCalls: 0,
215 remoteStatusCalls: 0,
216 localInvalidationCalls: 0,
217 remoteInvalidationCalls: 0,
218 };
219
220 return Effect.gen(function* () {
221 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
222 yield* broadcaster.getStatus({ cwd: "/repo" });
223 const subscribed = yield* Deferred.make<void>();
224 const events = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
225 Stream.tap((event) =>
226 event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,
227 ),
228 Stream.take(3),
229 Stream.runCollect,
230 Effect.forkScoped,
231 );
232 yield* Deferred.await(subscribed);
233
234 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
235 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
236 assert.equal(refreshed.refName, "main");
237 assert.isNull(refreshed.pr);
238 assert.equal(state.localInvalidationCalls, 1);
239 assert.equal(state.remoteStatusCalls, 1);
240 assert.equal(state.remoteInvalidationCalls, 2);
241 assert.deepStrictEqual((yield* Fiber.join(events)).slice(1), [
242 { _tag: "remoteUpdated", remote: null },
243 { _tag: "localUpdated", local: state.currentLocalStatus },
244 ]);
245 assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
246 const snapshot = yield* broadcaster
247 .streamStatus({ cwd: "/repo", includeRemote: false })
248 .pipe(Stream.take(1), Stream.runCollect);
249 assert.deepStrictEqual(snapshot[0], {
250 _tag: "snapshot",
251 local: state.currentLocalStatus,
252 remote: null,
253 });
254 }).pipe(Effect.provide(layerTestFor(state)));
255 });
256
257 it.effect(
258 "preserves cached remote status when a local-only refresh stays on the same branch",
259 () => {
260 const state = {
261 currentLocalStatus: baseLocalStatus,
262 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 2, behindCount: 3 },
263 localStatusCalls: 0,
264 remoteStatusCalls: 0,
265 localInvalidationCalls: 0,
266 remoteInvalidationCalls: 0,
267 };
268
269 return Effect.gen(function* () {
270 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
271 const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
272 const refreshed = yield* broadcaster.refreshStatus("/repo", { localOnly: true });
273 assert.deepStrictEqual(refreshed, initial);
274 assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);
275 assert.equal(state.localInvalidationCalls, 1);
276 assert.equal(state.remoteInvalidationCalls, 1);
277 assert.equal(state.remoteStatusCalls, 1);
278 }).pipe(Effect.provide(layerTestFor(state)));
279 },
280 );
281
282 it.effect("clears the previous branch's remote status after an in-flight PR refresh", () => {
283 const remoteReadStarted = Deferred.makeUnsafe<void>();
284 const releaseRemoteRead = Deferred.makeUnsafe<void>();
285 const state = {
286 currentLocalStatus: baseLocalStatus,
287 currentRemoteStatus: remoteStatusWithPr,
288 localStatusCalls: 0,
289 remoteStatusCalls: 0,
290 localInvalidationCalls: 0,
291 remoteInvalidationCalls: 0,
292 beforeRemoteStatus: Effect.void,
293 };
294
295 return Effect.gen(function* () {
296 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
297 yield* broadcaster.getStatus({ cwd: "/repo" });
298 state.beforeRemoteStatus = Deferred.succeed(remoteReadStarted, undefined).pipe(
299 Effect.andThen(Deferred.await(releaseRemoteRead)),
300 );
301 const remoteRefresh = yield* broadcaster
302 .refreshPullRequestStatus("/repo")
303 .pipe(Effect.forkScoped);
304 yield* Deferred.await(remoteReadStarted);
305 state.currentLocalStatus = { ...baseLocalStatus, refName: "main" };
306 const localRefresh = yield* broadcaster
307 .refreshStatus("/repo", { localOnly: true })
308 .pipe(Effect.forkScoped);
309 yield* Deferred.succeed(releaseRemoteRead, undefined);
310 yield* Fiber.join(remoteRefresh);
311 yield* Fiber.join(localRefresh);
312
313 const status = yield* broadcaster.getStatus({ cwd: "/repo" });
314 assert.equal(status.refName, "main");
315 assert.isNull(status.pr);
316 assert.equal(status.aheadCount, 0);
317 assert.equal(status.behindCount, 0);
318 assert.equal(state.remoteStatusCalls, 2);
319 }).pipe(Effect.provide(layerTestFor(state)));
320 });
321
322 it.effect.skipIf(!symlinksSupported)(
323 "automatically pulls an enabled clean default branch when status detects it is behind",
324 () => {
325 let remoteStatus: VcsStatusRemoteResult = { ...baseRemoteStatus, behindCount: 2 };
326 let pullCalls = 0;
327 let configuredWorkspaceRoot = "";
328 const localStatus: VcsStatusLocalResult = {
329 ...baseLocalStatus,
330 isDefaultRef: true,
331 refName: "main",
332 };
333 const layerTest = VcsStatusBroadcaster.layer.pipe(
334 Layer.provideMerge(NodeServices.layer),
335 Layer.provide(layerBackgroundPolicy(() => true)),
336 Layer.provide(
337 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
338 isEnabled: (cwd) => Effect.succeed(cwd === configuredWorkspaceRoot),
339 }),
340 ),
341 Layer.provide(
342 Layer.mock(GitWorkflowService.GitWorkflowService)({
343 localStatus: () => Effect.succeed(localStatus),
344 currentBranch: () => Effect.succeed(localStatus.refName),
345 remoteStatus: () => Effect.succeed(remoteStatus),
346 invalidateLocalStatus: () => Effect.void,
347 invalidateRemoteStatus: () => Effect.void,
348 invalidateStatus: () => Effect.void,
349 pullCurrentBranch: () =>
350 Effect.sync(() => {
351 pullCalls += 1;
352 remoteStatus = { ...remoteStatus, behindCount: 0 };
353 return {
354 status: "pulled" as const,
355 refName: "main",
356 upstreamRef: "origin/main",
357 };
358 }),
359 }),
360 ),
361 );
362
363 return Effect.gen(function* () {
364 const fileSystem = yield* FileSystem.FileSystem;
365 const path = yield* Path.Path;
366 const realDir = yield* fileSystem.makeTempDirectoryScoped({
367 prefix: "t3-vcs-auto-pull-real-",
368 });
369 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
370 prefix: "t3-vcs-auto-pull-link-",
371 });
372 configuredWorkspaceRoot = path.join(linkParent, "repo-link");
373 yield* fileSystem.symlink(realDir, configuredWorkspaceRoot);
374
375 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
376 const status = yield* broadcaster.refreshStatus(configuredWorkspaceRoot);
377
378 assert.equal(pullCalls, 1);
379 assert.equal(status.behindCount, 0);
380 }).pipe(Effect.provide(layerTest));
381 },
382 );
383
384 it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => {
385 const state = {
386 currentLocalStatus: baseLocalStatus,
387 currentRemoteStatus: baseRemoteStatus,
388 localStatusCalls: 0,
389 remoteStatusCalls: 0,
390 localInvalidationCalls: 0,
391 remoteInvalidationCalls: 0,
392 };
393
394 return Effect.gen(function* () {
395 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
396
397 assert.isNull(yield* broadcaster.refreshPullRequestStatus("/repo"));
398 assert.equal(state.remoteStatusCalls, 0);
399
400 yield* broadcaster.getStatus({ cwd: "/repo" });
401 assert.equal(state.remoteStatusCalls, 1);
402
403 state.currentRemoteStatus = remoteStatusWithPr;
404 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
405 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
406 assert.equal(state.remoteStatusCalls, 2);
407 assert.equal(state.remoteInvalidationCalls, 2);
408
409 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
410 state.currentRemoteStatus = baseRemoteStatus;
411 yield* broadcaster.refreshLocalStatus("/repo");
412 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
413 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
414 assert.equal(state.remoteStatusCalls, 3);
415 const refreshedStatus = yield* broadcaster.getStatus({ cwd: "/repo" });
416 assert.equal(refreshedStatus.refName, "feature/next");
417 assert.isNull(refreshedStatus.pr);
418 assert.equal(state.remoteStatusCalls, 3);
419 assert.equal(state.remoteInvalidationCalls, 3);
420 }).pipe(Effect.provide(layerTestFor(state)));
421 });
422
423 it.effect("a poll that started before the turn-end refresh cannot overwrite its PR", () => {
424 const releaseFirstPoll = Deferred.makeUnsafe<void>();
425 const firstPollStarted = Deferred.makeUnsafe<void>();
426 let remoteReads = 0;
427 const layer = VcsStatusBroadcaster.layer.pipe(
428 Layer.provideMerge(NodeServices.layer),
429 Layer.provide(layerBackgroundPolicy(() => true)),
430 Layer.provide(
431 Layer.mock(GitWorkflowService.GitWorkflowService)({
432 localStatus: () => Effect.succeed(baseLocalStatus),
433 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
434 remoteStatus: () =>
435 Effect.gen(function* () {
436 remoteReads += 1;
437 if (remoteReads === 2) {
438 yield* Deferred.succeed(firstPollStarted, undefined);
439 yield* Deferred.await(releaseFirstPoll);
440 return baseRemoteStatus;
441 }
442 return remoteReads === 1 ? baseRemoteStatus : remoteStatusWithPr;
443 }),
444 invalidateLocalStatus: () => Effect.void,
445 invalidateRemoteStatus: () => Effect.void,
446 invalidateStatus: () => Effect.void,
447 }),
448 ),
449 );
450
451 return Effect.gen(function* () {
452 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
453 yield* broadcaster.getStatus({ cwd: "/repo" });
454
455 const poll = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
456 yield* Deferred.await(firstPollStarted);
457 const refresh = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
458 yield* Deferred.succeed(releaseFirstPoll, undefined);
459 yield* Fiber.join(poll);
460 const refreshed = yield* Fiber.join(refresh);
461
462 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
463 const final = yield* broadcaster.getStatus({ cwd: "/repo" });
464 assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
465 }).pipe(Effect.provide(layer), Effect.scoped);
466 });
467
468 it.effect("an initial status read cannot overwrite an explicit refresh", () => {
469 const firstReadStarted = Deferred.makeUnsafe<void>();
470 const releaseFirstRead = Deferred.makeUnsafe<void>();
471 let remoteReads = 0;
472 const layer = VcsStatusBroadcaster.layer.pipe(
473 Layer.provide(FileSystem.layerNoop({ realPath: (path) => Effect.succeed(path) })),
474 Layer.provideMerge(NodeServices.layer),
475 Layer.provide(layerBackgroundPolicy(() => true)),
476 Layer.provide(
477 Layer.mock(GitWorkflowService.GitWorkflowService)({
478 localStatus: () => Effect.succeed(baseLocalStatus),
479 currentBranch: () => Effect.succeed(baseLocalStatus.refName),
480 remoteStatus: () =>
481 Effect.gen(function* () {
482 remoteReads += 1;
483 if (remoteReads === 1) {
484 yield* Deferred.succeed(firstReadStarted, undefined);
485 yield* Deferred.await(releaseFirstRead);
486 return baseRemoteStatus;
487 }
488 return remoteStatusWithPr;
489 }),
490 invalidateLocalStatus: () => Effect.void,
491 invalidateRemoteStatus: () => Effect.void,
492 invalidateStatus: () => Effect.void,
493 }),
494 ),
495 );
496 return Effect.gen(function* () {
497 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
498 const initial = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
499 yield* Deferred.await(firstReadStarted);
500 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
501 yield* TestClock.adjust(Duration.zero);
502 yield* Deferred.succeed(releaseFirstRead, undefined);
503 yield* Fiber.join(initial);
504 yield* Fiber.join(refresh);
505 assert.deepStrictEqual(
506 (yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
507 remoteStatusWithPr.pr,
508 );
509 }).pipe(Effect.provide(layer), Effect.scoped);
510 });
511
512 it.effect("keeps the published local snapshot when a refresh remote read fails", () => {
513 const state = {
514 currentLocalStatus: baseLocalStatus,
515 currentRemoteStatus: baseRemoteStatus,
516 localStatusCalls: 0,
517 remoteStatusCalls: 0,
518 localInvalidationCalls: 0,
519 remoteInvalidationCalls: 0,
520 failRemoteStatus: false,
521 };
522 const layerTest = VcsStatusBroadcaster.layer.pipe(
523 Layer.provideMerge(NodeServices.layer),
524 Layer.provide(layerBackgroundPolicy(() => true)),
525 Layer.provide(
526 Layer.mock(GitWorkflowService.GitWorkflowService)({
527 localStatus: () =>
528 Effect.sync(() => {
529 state.localStatusCalls += 1;
530 return state.currentLocalStatus;
531 }),
532 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
533 remoteStatus: () =>
534 Effect.suspend(() => {
535 state.remoteStatusCalls += 1;
536 return state.failRemoteStatus
537 ? Effect.fail(
538 new GitManagerError({
539 operation: "VcsStatusBroadcaster.test",
540 cwd: "/repo",
541 detail: "remote status failed",
542 }),
543 )
544 : Effect.succeed(state.currentRemoteStatus);
545 }),
546 invalidateLocalStatus: () =>
547 Effect.sync(() => {
548 state.localInvalidationCalls += 1;
549 }),
550 invalidateRemoteStatus: () =>
551 Effect.sync(() => {
552 state.remoteInvalidationCalls += 1;
553 }),
554 invalidateStatus: () =>
555 Effect.sync(() => {
556 state.localInvalidationCalls += 1;
557 state.remoteInvalidationCalls += 1;
558 }),
559 }),
560 ),
561 );
562
563 return Effect.gen(function* () {
564 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
565 yield* broadcaster.getStatus({ cwd: "/repo" });
566
567 state.currentLocalStatus = {
568 ...baseLocalStatus,
569 refName: "feature/partial-refresh",
570 };
571 state.currentRemoteStatus = {
572 ...baseRemoteStatus,
573 aheadCount: 3,
574 };
575 state.failRemoteStatus = true;
576
577 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
578 const snapshot = yield* Stream.runHead(
579 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
580 );
581
582 assert.isTrue(Exit.isFailure(refreshExit));
583 assert.isTrue(Option.isSome(snapshot));
584 const event = Option.getOrThrow(snapshot);
585 assert.equal(event._tag, "snapshot");
586 if (event._tag === "snapshot") {
587 assert.equal(event.local.refName, "feature/partial-refresh");
588 assert.isNull(event.remote);
589 }
590 }).pipe(Effect.provide(layerTest));
591 });
592
593 it.effect.skipIf(!symlinksSupported)(
594 "normalizes symlinked CWDs before cache lookup and workflow calls",
595 () => {
596 const seenCwds: string[] = [];
597 const state = {
598 currentLocalStatus: baseLocalStatus,
599 currentRemoteStatus: baseRemoteStatus,
600 localStatusCalls: 0,
601 remoteStatusCalls: 0,
602 localInvalidationCalls: 0,
603 remoteInvalidationCalls: 0,
604 };
605 const layerTest = VcsStatusBroadcaster.layer.pipe(
606 Layer.provideMerge(NodeServices.layer),
607 Layer.provide(layerBackgroundPolicy(() => true)),
608 Layer.provide(
609 Layer.mock(GitWorkflowService.GitWorkflowService)({
610 localStatus: (input) =>
611 Effect.sync(() => {
612 seenCwds.push(input.cwd);
613 state.localStatusCalls += 1;
614 return state.currentLocalStatus;
615 }),
616 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
617 remoteStatus: (input) =>
618 Effect.sync(() => {
619 seenCwds.push(input.cwd);
620 state.remoteStatusCalls += 1;
621 return state.currentRemoteStatus;
622 }),
623 invalidateLocalStatus: () =>
624 Effect.sync(() => {
625 state.localInvalidationCalls += 1;
626 }),
627 invalidateRemoteStatus: () =>
628 Effect.sync(() => {
629 state.remoteInvalidationCalls += 1;
630 }),
631 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
632 ),
633 );
634
635 return Effect.gen(function* () {
636 const fileSystem = yield* FileSystem.FileSystem;
637 const path = yield* Path.Path;
638 const realDir = yield* fileSystem.makeTempDirectoryScoped({
639 prefix: "t3-vcs-status-real-",
640 });
641 const linkParent = yield* fileSystem.makeTempDirectoryScoped({
642 prefix: "t3-vcs-status-link-",
643 });
644 const linkDir = path.join(linkParent, "repo-link");
645 yield* fileSystem.symlink(realDir, linkDir);
646 const realPath = yield* fileSystem.realPath(realDir);
647
648 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
649 yield* broadcaster.getStatus({ cwd: linkDir });
650 yield* broadcaster.getStatus({ cwd: realDir });
651
652 assert.deepStrictEqual(seenCwds, [realPath, realPath]);
653 assert.equal(state.localStatusCalls, 1);
654 assert.equal(state.remoteStatusCalls, 1);
655 }).pipe(Effect.provide(layerTest));
656 },
657 );
658
659 it.effect("an explicit refresh reads local totals after the fetch", () => {
660 const state: Parameters<typeof layerTestFor>[0] = {
661 currentLocalStatus: baseLocalStatus,
662 currentRemoteStatus: baseRemoteStatus,
663 localStatusCalls: 0,
664 remoteStatusCalls: 0,
665 localInvalidationCalls: 0,
666 remoteInvalidationCalls: 0,
667 };
668
669 return Effect.gen(function* () {
670 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
671 const fetchStarted = yield* Deferred.make<void>();
672 const finishFetch = yield* Deferred.make<void>();
673 state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe(
674 Effect.andThen(Deferred.await(finishFetch)),
675 );
676 const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped);
677 yield* Deferred.await(fetchStarted);
678
679 const fetchedLocal: VcsStatusLocalResult = {
680 ...baseLocalStatus,
681 branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 },
682 };
683 state.currentLocalStatus = fetchedLocal;
684 yield* Deferred.succeed(finishFetch, undefined);
685
686 const status = yield* Fiber.join(refresh);
687 assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges);
688 }).pipe(Effect.provide(layerTestFor(state)));
689 });
690
691 it.effect("publishes local status while an earlier lookup holds the remote lock", () => {
692 const state: Parameters<typeof layerTestFor>[0] = {
693 currentLocalStatus: baseLocalStatus,
694 currentRemoteStatus: baseRemoteStatus,
695 localStatusCalls: 0,
696 remoteStatusCalls: 0,
697 localInvalidationCalls: 0,
698 remoteInvalidationCalls: 0,
699 };
700
701 return Effect.gen(function* () {
702 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
703 yield* broadcaster.getStatus({ cwd: "/repo" });
704 const subscribed = yield* Deferred.make<void>();
705 const published = yield* Deferred.make<VcsStatusLocalResult>();
706 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
707 Stream.runForEach((event) => {
708 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
709 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
710 return Effect.void;
711 }),
712 Effect.forkScoped,
713 );
714 yield* Deferred.await(subscribed);
715 const started = yield* Deferred.make<void>();
716 const release = yield* Deferred.make<void>();
717 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
718 Effect.andThen(Deferred.await(release)),
719 );
720 const earlier = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
721 yield* Deferred.await(started);
722 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
723 const completed = yield* Deferred.make<void>();
724 const refresh = yield* broadcaster
725 .refreshStatus("/repo")
726 .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
727
728 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
729 assert.isFalse(yield* Deferred.isDone(completed));
730 assert.isFalse(yield* Deferred.isDone(release));
731 state.currentRemoteStatus = remoteStatusWithPr;
732 yield* Deferred.succeed(release, undefined);
733 yield* Fiber.join(earlier);
734 const status = yield* Fiber.join(refresh);
735 assert.isTrue(status.hasWorkingTreeChanges);
736 assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
737 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
738 });
739
740 it.effect("publishes local changes before a remote error and propagates that error", () => {
741 const remoteError = new GitManagerError({
742 operation: "VcsStatusBroadcaster.remoteStatus",
743 cwd: "/repo",
744 detail: "The controlled remote lookup failed.",
745 });
746 const state: Parameters<typeof layerTestFor>[0] = {
747 currentLocalStatus: baseLocalStatus,
748 currentRemoteStatus: remoteStatusWithPr,
749 localStatusCalls: 0,
750 remoteStatusCalls: 0,
751 localInvalidationCalls: 0,
752 remoteInvalidationCalls: 0,
753 };
754
755 return Effect.gen(function* () {
756 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
757 yield* broadcaster.getStatus({ cwd: "/repo" });
758 const subscribed = yield* Deferred.make<void>();
759 const published = yield* Deferred.make<VcsStatusLocalResult>();
760 yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
761 Stream.runForEach((event) => {
762 if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
763 if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
764 return Effect.void;
765 }),
766 Effect.forkScoped,
767 );
768 yield* Deferred.await(subscribed);
769 const started = yield* Deferred.make<void>();
770 const release = yield* Deferred.make<void>();
771 const completed = yield* Deferred.make<void>();
772 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
773 Effect.andThen(Deferred.await(release)),
774 );
775 state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
776 state.remoteStatusError = remoteError;
777 const refresh = yield* broadcaster
778 .refreshStatus("/repo")
779 .pipe(
780 Effect.result,
781 Effect.ensuring(Deferred.succeed(completed, undefined)),
782 Effect.forkScoped,
783 );
784 yield* Deferred.await(started);
785 assert.isFalse(yield* Deferred.isDone(completed));
786 const pending = Option.getOrThrow(
787 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
788 );
789 assert.equal(pending._tag, "snapshot");
790 if (pending._tag === "snapshot") assert.isTrue(pending.local.hasWorkingTreeChanges);
791 yield* Deferred.succeed(release, undefined);
792 const result = yield* Fiber.join(refresh);
793 assert.equal(result._tag, "Failure");
794 if (result._tag === "Failure") assert.strictEqual(result.failure, remoteError);
795 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
796 assert.isTrue(cached.hasWorkingTreeChanges);
797 assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);
798 assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
799 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
800 });
801
802 it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(
803 "%s keeps response parts consistent when local state changes after the remote cache write",
804 (operation) => {
805 const state: Parameters<typeof layerTestFor>[0] = {
806 currentLocalStatus: baseLocalStatus,
807 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
808 localStatusCalls: 0,
809 remoteStatusCalls: 0,
810 localInvalidationCalls: 0,
811 remoteInvalidationCalls: 0,
812 fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
813 };
814 const autoPull = operation === "autoPull" || operation === "autoPullFailure";
815 if (autoPull) {
816 state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: true };
817 state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 0, behindCount: 5 };
818 state.pullCurrentBranch = () =>
819 operation === "autoPullFailure"
820 ? Effect.fail(
821 new GitCommandError({
822 operation: "test.pull",
823 command: "pull",
824 cwd: "/repo",
825 detail: "Pull failed.",
826 }),
827 )
828 : Effect.succeed({
829 status: "pulled",
830 refName: "feature/status-broadcast",
831 upstreamRef: "origin/main",
832 });
833 }
834 const layerTest = layerTestFor(state).pipe(
835 Layer.provide(
836 Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
837 isEnabled: () => Effect.succeed(autoPull),
838 }),
839 ),
840 );
841 return Effect.gen(function* () {
842 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
843 let switched = false;
844 let remoteWritten = false;
845 const writeCompleted = yield* Deferred.make<void>();
846 const localRefresh = yield* Effect.gen(function* () {
847 yield* Deferred.await(writeCompleted);
848 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
849 yield* broadcaster.refreshLocalStatus("/repo");
850 switched = true;
851 }).pipe(Effect.forkScoped);
852 const scheduler = new Scheduler.MixedScheduler();
853 const shouldYield = scheduler.shouldYield.bind(scheduler);
854 scheduler.shouldYield = (fiber) => (remoteWritten && !switched) || shouldYield(fiber);
855 const tracer = Tracer.make({
856 span: (options) => {
857 const span = new Tracer.NativeSpan(options);
858 const end = span.end.bind(span);
859 span.end = (time, exit) => {
860 end(time, exit);
861 if (
862 options.name !== "VcsStatusBroadcaster.updateCachedRemoteStatus" ||
863 remoteWritten
864 ) {
865 return;
866 }
867 // Yield this reader after its write until the local refresh finishes.
868 remoteWritten = true;
869 Deferred.doneUnsafe(writeCompleted, Effect.void);
870 };
871 return span;
872 },
873 });
874 const status = yield* (
875 operation === "getStatus"
876 ? broadcaster.getStatus({ cwd: "/repo" })
877 : broadcaster.refreshStatus("/repo")
878 ).pipe(Effect.withTracer(tracer), Effect.provideService(Scheduler.Scheduler, scheduler));
879 yield* Fiber.join(localRefresh);
880 assert.isTrue(switched);
881 assert.equal(status.refName, "feature/next-status");
882 assert.isNull(status.pr);
883 assert.equal(status.aheadCount, 0);
884 assert.equal(status.behindCount, 0);
885 }).pipe(Effect.provide(layerTest), Effect.scoped);
886 },
887 );
888
889 it.effect("recovers a discarded branch lookup on the next permitted turn-end refresh", () => {
890 const state: Parameters<typeof layerTestFor>[0] = {
891 currentLocalStatus: baseLocalStatus,
892 currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
893 localStatusCalls: 0,
894 remoteStatusCalls: 0,
895 localInvalidationCalls: 0,
896 remoteInvalidationCalls: 0,
897 };
898
899 return Effect.gen(function* () {
900 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
901 const started = yield* Deferred.make<void>();
902 const release = yield* Deferred.make<void>();
903 state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
904 Effect.andThen(Deferred.await(release)),
905 );
906 const lookup = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
907 yield* Deferred.await(started);
908 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
909 yield* Deferred.succeed(release, undefined);
910 const discarded = yield* Fiber.join(lookup);
911 assert.equal(discarded.refName, state.currentLocalStatus.refName);
912 assert.isNull(discarded.pr);
913 assert.equal(discarded.aheadCount, 0);
914 assert.equal(discarded.behindCount, 0);
915 const snapshot = Option.getOrThrow(
916 yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
917 );
918 assert.equal(snapshot._tag, "snapshot");
919 if (snapshot._tag === "snapshot") assert.isNull(snapshot.remote);
920
921 state.beforeRemoteStatus = Effect.void;
922 state.currentRemoteStatus = {
923 ...baseRemoteStatus,
924 aheadCount: 2,
925 pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" },
926 };
927 state.backgroundWorkEnabled = false;
928 yield* broadcaster.refreshPullRequestStatus("/repo");
929 assert.equal(state.remoteStatusCalls, 1);
930 state.backgroundWorkEnabled = true;
931 const recovered = yield* broadcaster.refreshPullRequestStatus("/repo");
932 assert.deepStrictEqual(recovered, state.currentRemoteStatus);
933 const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
934 assert.equal(cached.refName, state.currentLocalStatus.refName);
935 assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);
936 assert.equal(cached.aheadCount, 2);
937 assert.equal(state.remoteStatusCalls, 2);
938 }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
939 });
940
941 it.effect("releases remote demand while passive observers remain", () => {
942 const state = {
943 currentLocalStatus: baseLocalStatus,
944 currentRemoteStatus: baseRemoteStatus,
945 localStatusCalls: 0,
946 remoteStatusCalls: 0,
947 localInvalidationCalls: 0,
948 remoteInvalidationCalls: 0,
949 };
950 let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
951 let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
952 const layerTest = VcsStatusBroadcaster.layer.pipe(
953 Layer.provideMerge(NodeServices.layer),
954 Layer.provide(layerBackgroundPolicy(() => true)),
955 Layer.provide(
956 Layer.mock(GitWorkflowService.GitWorkflowService)({
957 localStatus: () =>
958 Effect.sync(() => {
959 state.localStatusCalls += 1;
960 return state.currentLocalStatus;
961 }),
962 currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
963 remoteStatus: () =>
964 Effect.sync(() => {
965 state.remoteStatusCalls += 1;
966 }).pipe(
967 Effect.andThen(
968 remoteStartedDeferred
969 ? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
970 : Effect.void,
971 ),
972 Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
973 Effect.onInterrupt(() =>
974 remoteInterruptedDeferred
975 ? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
976 : Effect.void,
977 ),
978 ),
979 invalidateLocalStatus: () =>
980 Effect.sync(() => {
981 state.localInvalidationCalls += 1;
982 }),
983 invalidateRemoteStatus: () =>
984 Effect.sync(() => {
985 state.remoteInvalidationCalls += 1;
986 }),
987 } satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
988 ),
989 );
990
991 return Effect.gen(function* () {
992 const remoteInterrupted = yield* Deferred.make<void>();
993 const remoteStarted = yield* Deferred.make<void>();
994 remoteInterruptedDeferred = remoteInterrupted;
995 remoteStartedDeferred = remoteStarted;
996
997 const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
998 const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
999 const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1000 const firstScope = yield* Scope.make();
1001 const secondScope = yield* Scope.make();
1002 const passiveSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
1003 yield* Stream.runForEach(
1004 broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
1005 (event) =>
1006 event._tag === "snapshot"
1007 ? Deferred.succeed(passiveSnapshot, event).pipe(Effect.ignore)
1008 : Effect.void,
1009 ).pipe(Effect.forkScoped);
1010 yield* Deferred.await(passiveSnapshot);
1011 assert.equal(state.remoteStatusCalls, 0);
1012 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1013 event._tag === "snapshot"
1014 ? Deferred.succeed(firstSnapshot, event).pipe(Effect.ignore)
1015 : Effect.void,
1016 ).pipe(Effect.forkIn(firstScope));
1017 yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
1018 event._tag === "snapshot"
1019 ? Deferred.succeed(secondSnapshot, event).pipe(Effect.ignore)
1020 : Effect.void,
1021 ).pipe(Effect.forkIn(secondScope));
1022
1023 yield* Deferred.await(firstSnapshot);
1024 yield* Deferred.await(secondSnapshot);
1025 yield* Deferred.await(remoteStarted);
1026
1027 assert.equal(state.remoteStatusCalls, 1);
1028
1029 yield* Scope.close(firstScope, Exit.void);
1030 assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
1031
1032 yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
1033 yield* Deferred.await(remoteInterrupted);
1034 assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
1035 }).pipe(Effect.provide(layerTest));
1036 });
1037});