@devries-cameron20 / t3code Mirror · read-only / commits / e677e9799d
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 13:15 UTC

fix(server): publish local git status before remote lookup (#21046)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Yannic Charlon committed Oct 29, 2026 at 08:02 UTC e677e9799df44fd33d96890cb80dc0ee64d1221d
4 files changed +559 -159
apps/server/src/git/GitManager.test.ts
+115
@@ -1,3 +1,5 @@
1 +import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
2 +import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
3 import { SourceControlProviderKind } from "@t3tools/contracts";
4 // @effect-diagnostics nodeBuiltinImport:off
5 import * as NodeFS from "node:fs";
@@ -69,6 +71,10 @@ type FakeChangeRequest = Omit<ChangeRequest, "provider" | "state" | "updatedAt">
71 };
72
73 interface FakeProviderScenario {
74 + prListGate?: {
75 + readonly started: Deferred.Deferred<void>;
76 + readonly release: Deferred.Deferred<void>;
77 + };
78 /** The kind the fake host reports itself as. */
79 kind?: string;
80 /** Answers to successive change request listings, whatever their head selector. */
@@ -452,6 +458,13 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): {
458 []
459 ).map(toChangeRequest),
460 ),
461 + Effect.tap(() =>
462 + scenario.prListGate
463 + ? Deferred.succeed(scenario.prListGate.started, undefined).pipe(
464 + Effect.andThen(Deferred.await(scenario.prListGate.release)),
465 + )
466 + : Effect.void,
467 + ),
468 ),
469 createChangeRequest: (input) =>
470 record(input.cwd, {
@@ -723,6 +736,108 @@ const layerGitManagerTest = GitVcsDriver.layer.pipe(
736 );
737
738 it.layer(layerGitManagerTest)("GitManager", (it) => {
739 + it.effect(
740 + "publishes local Git changes during a held PR lookup without caching its old branch",
741 + () =>
742 + Effect.gen(function* () {
743 + const repoDir = yield* makeTempDir("t3code-refresh-status-gh-gate-");
744 + yield* initRepo(repoDir);
745 + yield* runGit(repoDir, ["checkout", "-b", "release"]);
746 + const remoteDir = yield* createBareRemote();
747 + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
748 + yield* runGit(repoDir, ["push", "-u", "origin", "release"]);
749 + yield* runGit(repoDir, ["tag", "release"]);
750 + const oldPr = {
751 + number: 613,
752 + title: "Release PR",
753 + url: "https://github.com/pingdotgg/codething-mvp/pull/613",
754 + baseRefName: "main",
755 + headRefName: "release",
756 + };
757 + const newPr = { ...oldPr, number: 614, headRefName: "heads/release" };
758 + const providerScenario: FakeProviderScenario = {
759 + prListSequence: [oldPr, oldPr, newPr].map((pr) => [pr]),
760 + };
761 + const { manager } = yield* makeManager({ providerScenario });
762 + const context = yield* Layer.build(
763 + VcsStatusBroadcaster.layer.pipe(
764 + Layer.provide(
765 + GitWorkflowService.layer.pipe(
766 + Layer.provide(Layer.succeed(GitManager.GitManager, manager)),
767 + Layer.provide(
768 + VcsDriverRegistry.layer.pipe(
769 + Layer.provide(VcsProjectConfig.layer),
770 + Layer.provide(VcsProcess.layer),
771 + ),
772 + ),
773 + ),
774 + ),
775 + Layer.provide(
776 + Layer.mock(BackgroundPolicy.BackgroundPolicy)({
777 + shouldRunScopeWork: () => Effect.succeed(true),
778 + }),
779 + ),
780 + ),
781 + );
782 + const broadcaster = Context.get(context, VcsStatusBroadcaster.VcsStatusBroadcaster);
783 + const initial = yield* broadcaster.getStatus({ cwd: repoDir });
784 + expect(initial.refName).toBe("release");
785 + expect(initial.pr?.number).toBe(613);
786 +
787 + const subscribed = yield* Deferred.make<void>();
788 + const published = yield* Deferred.make<void>();
789 + yield* broadcaster.streamStatus({ cwd: repoDir, includeRemote: false }).pipe(
790 + Stream.runForEach((event) => {
791 + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
792 + if (event._tag === "localUpdated" && event.local.hasWorkingTreeChanges) {
793 + return Deferred.succeed(published, undefined);
794 + }
795 + return Effect.void;
796 + }),
797 + Effect.forkScoped,
798 + );
799 + yield* Deferred.await(subscribed);
800 + const gate = {
801 + started: yield* Deferred.make<void>(),
802 + release: yield* Deferred.make<void>(),
803 + };
804 + providerScenario.prListGate = gate;
805 + const fs = yield* FileSystem.FileSystem;
806 + yield* fs.writeFileString(NodePath.join(repoDir, "README.md"), "changed before refresh\n");
807 + const completed = yield* Deferred.make<void>();
808 + const refresh = yield* broadcaster
809 + .refreshStatus(repoDir)
810 + .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
811 + yield* Deferred.await(gate.started);
812 + const pending = Option.getOrThrow(
813 + yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),
814 + );
815 + expect(pending._tag).toBe("snapshot");
816 + if (pending._tag === "snapshot") expect(pending.local.hasWorkingTreeChanges).toBe(true);
817 + yield* Deferred.await(published);
818 + expect(yield* Deferred.isDone(completed)).toBe(false);
819 +
820 + yield* runGit(repoDir, ["checkout", "-b", "heads/release"]);
821 + yield* runGit(repoDir, ["push", "-u", "origin", "refs/heads/heads/release"]);
822 + yield* Deferred.succeed(gate.release, undefined);
823 + const refreshed = yield* Fiber.join(refresh);
824 + expect(refreshed.refName).toBe("heads/release");
825 + expect(refreshed.hasWorkingTreeChanges).toBe(true);
826 + expect(refreshed.pr).toBeNull();
827 + const snapshot = Option.getOrThrow(
828 + yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),
829 + );
830 + expect(snapshot._tag).toBe("snapshot");
831 + if (snapshot._tag === "snapshot") expect(snapshot.remote).toBeNull();
832 +
833 + delete providerScenario.prListGate;
834 + const recovered = yield* broadcaster.getStatus({ cwd: repoDir });
835 + expect(recovered.refName).toBe("heads/release");
836 + expect(recovered.pr?.number).toBe(614);
837 + expect((yield* broadcaster.getStatus({ cwd: repoDir })).pr?.number).toBe(614);
838 + }),
839 + );
840 +
841 it.effect("status reports the listed PR whose head is the branch", () =>
842 Effect.gen(function* () {
843 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/GitWorkflowService.ts
+27
@@ -52,6 +52,7 @@ export class GitWorkflowService extends Context.Service<
52 readonly localStatus: (
53 input: VcsStatusInput,
54 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
55 + readonly currentBranch: (cwd: string) => Effect.Effect<string | null, GitManagerServiceError>;
56 readonly remoteStatus: (
57 input: VcsStatusInput,
58 options?: GitManager.GitRemoteStatusOptions,
@@ -332,6 +333,32 @@ export const make = Effect.gen(function* () {
333 ),
334 );
335 }),
336 + currentBranch: Effect.fn("GitWorkflowService.currentBranch")(function* (cwd) {
337 + if (!(yield* detectGitRepositoryForStatus("GitWorkflowService.currentBranch", cwd))) {
338 + return null;
339 + }
340 + const result = yield* git.execute({
341 + operation: "GitWorkflowService.currentBranch",
342 + cwd,
343 + args: ["symbolic-ref", "--quiet", "HEAD"],
344 + allowNonZeroExit: true,
345 + timeoutMs: 5_000,
346 + });
347 + if (result.exitCode === 0) {
348 + return result.stdout.trim().replace(/^refs\/heads\//, "") || null;
349 + }
350 + if (result.exitCode === 1) return null;
351 + return yield* new GitCommandError({
352 + operation: "GitWorkflowService.currentBranch",
353 + command: "git symbolic-ref",
354 + cwd,
355 + argumentCount: 3,
356 + ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
357 + stdoutLength: result.stdout.length,
358 + stderrLength: result.stderr.length,
359 + detail: "Failed to read the checked-out branch.",
360 + });
361 + }),
362 remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {
363 return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
364 Effect.flatMap((isGitRepository) =>
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+310 -30
@@ -12,16 +12,17 @@ import * as Layer from "effect/Layer";
12 import * as Option from "effect/Option";
13 import * as Path from "effect/Path";
14 import * as Scope from "effect/Scope";
15 +import * as Scheduler from "effect/Scheduler";
16 import * as Stream from "effect/Stream";
17 import * as TestClock from "effect/testing/TestClock";
18 +import * as Tracer from "effect/Tracer";
19 import type {
20 BackgroundScope,
21 VcsStatusLocalResult,
22 VcsStatusRemoteResult,
21 - VcsStatusResult,
23 VcsStatusStreamEvent,
24 } from "@t3tools/contracts";
24 -import { GitManagerError } from "@t3tools/contracts";
25 +import { GitCommandError, GitManagerError } from "@t3tools/contracts";
26
27 import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";
28 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
@@ -58,16 +59,11 @@ const remoteStatusWithPr: VcsStatusRemoteResult = {
59 title: "[codex] Rewrite client connection architecture",
60 url: "https://github.com/pingdotgg/t3code/pull/2978",
61 baseRef: "main",
61 - headRef: "codex/connection-state-audit",
62 + headRef: "upstream-topic",
63 state: "open",
64 },
65 };
66
66 -const baseStatus: VcsStatusResult = {
67 - ...baseLocalStatus,
68 - ...baseRemoteStatus,
69 -};
70 -
67 function layerTestFor(state: {
68 currentLocalStatus: VcsStatusLocalResult;
69 currentRemoteStatus: VcsStatusRemoteResult | null;
@@ -76,12 +72,19 @@ function layerTestFor(state: {
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 + fileSystem?: FileSystem.FileSystem;
80 + pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];
81 }) {
82 return VcsStatusBroadcaster.layer.pipe(
84 - Layer.provideMerge(NodeServices.layer),
83 + Layer.provideMerge(
84 + state.fileSystem
85 + ? Layer.succeed(FileSystem.FileSystem, state.fileSystem)
86 + : NodeServices.layer,
87 + ),
88 Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),
89 Layer.provide(
90 Layer.succeed(
@@ -96,16 +99,22 @@ function layerTestFor(state: {
99 state.localStatusCalls += 1;
100 return state.currentLocalStatus;
101 }),
102 + currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName),
103 remoteStatus: (_input, options) =>
100 - Effect.suspend(() => state.beforeRemoteStatus ?? Effect.void).pipe(
101 - Effect.andThen(
102 - Effect.sync(() => {
103 - state.remoteStatusCalls += 1;
104 - state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
105 - return state.currentRemoteStatus;
106 - }),
107 - ),
108 - ),
104 + Effect.suspend(() => {
105 + return (state.beforeRemoteStatus ?? Effect.void).pipe(
106 + Effect.andThen(
107 + Effect.sync(() => {
108 + state.remoteStatusCalls += 1;
109 + state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);
110 + return state.currentRemoteStatus;
111 + }),
112 + ),
113 + Effect.tap(() =>
114 + state.remoteStatusError ? Effect.fail(state.remoteStatusError) : Effect.void,
115 + ),
116 + );
117 + }),
118 invalidateLocalStatus: () =>
119 Effect.sync(() => {
120 state.localInvalidationCalls += 1;
@@ -119,6 +128,7 @@ function layerTestFor(state: {
128 state.localInvalidationCalls += 1;
129 state.remoteInvalidationCalls += 1;
130 }),
131 + ...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}),
132 }),
133 ),
134 );
@@ -171,7 +181,7 @@ describe("VcsStatusBroadcaster", () => {
181 Stream.tap((event) =>
182 event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,
183 ),
174 - Stream.take(2),
184 + Stream.take(3),
185 Stream.runCollect,
186 Effect.forkScoped,
187 );
@@ -183,12 +193,11 @@ describe("VcsStatusBroadcaster", () => {
193 assert.isNull(refreshed.pr);
194 assert.equal(state.localInvalidationCalls, 1);
195 assert.equal(state.remoteStatusCalls, 1);
186 - assert.equal(state.remoteInvalidationCalls, 1);
187 - assert.deepStrictEqual((yield* Fiber.join(events))[1], {
188 - _tag: "snapshot",
189 - local: state.currentLocalStatus,
190 - remote: null,
191 - });
196 + assert.equal(state.remoteInvalidationCalls, 2);
197 + assert.deepStrictEqual((yield* Fiber.join(events)).slice(1), [
198 + { _tag: "remoteUpdated", remote: null },
199 + { _tag: "localUpdated", local: state.currentLocalStatus },
200 + ]);
201 assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);
202 const snapshot = yield* broadcaster
203 .streamStatus({ cwd: "/repo", includeRemote: false })
@@ -220,7 +229,7 @@ describe("VcsStatusBroadcaster", () => {
229 assert.deepStrictEqual(refreshed, initial);
230 assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);
231 assert.equal(state.localInvalidationCalls, 1);
223 - assert.equal(state.remoteInvalidationCalls, 0);
232 + assert.equal(state.remoteInvalidationCalls, 1);
233 assert.equal(state.remoteStatusCalls, 1);
234 }).pipe(Effect.provide(layerTestFor(state)));
235 },
@@ -288,6 +297,7 @@ describe("VcsStatusBroadcaster", () => {
297 Layer.provide(
298 Layer.mock(GitWorkflowService.GitWorkflowService)({
299 localStatus: () => Effect.succeed(localStatus),
300 + currentBranch: () => Effect.succeed(localStatus.refName),
301 remoteStatus: () => Effect.succeed(remoteStatus),
302 invalidateLocalStatus: () => Effect.void,
303 invalidateRemoteStatus: () => Effect.void,
@@ -350,7 +360,7 @@ describe("VcsStatusBroadcaster", () => {
360 const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");
361 assert.deepStrictEqual(refreshed, remoteStatusWithPr);
362 assert.equal(state.remoteStatusCalls, 2);
353 - assert.equal(state.remoteInvalidationCalls, 0);
363 + assert.equal(state.remoteInvalidationCalls, 2);
364
365 state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };
366 state.currentRemoteStatus = baseRemoteStatus;
@@ -358,6 +368,11 @@ describe("VcsStatusBroadcaster", () => {
368 const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");
369 assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);
370 assert.equal(state.remoteStatusCalls, 3);
371 + const refreshedStatus = yield* broadcaster.getStatus({ cwd: "/repo" });
372 + assert.equal(refreshedStatus.refName, "feature/next");
373 + assert.isNull(refreshedStatus.pr);
374 + assert.equal(state.remoteStatusCalls, 3);
375 + assert.equal(state.remoteInvalidationCalls, 3);
376 }).pipe(Effect.provide(layerTestFor(state)));
377 });
378
@@ -371,6 +386,7 @@ describe("VcsStatusBroadcaster", () => {
386 Layer.provide(
387 Layer.mock(GitWorkflowService.GitWorkflowService)({
388 localStatus: () => Effect.succeed(baseLocalStatus),
389 + currentBranch: () => Effect.succeed(baseLocalStatus.refName),
390 remoteStatus: () =>
391 Effect.gen(function* () {
392 remoteReads += 1;
@@ -416,6 +432,7 @@ describe("VcsStatusBroadcaster", () => {
432 Layer.provide(
433 Layer.mock(GitWorkflowService.GitWorkflowService)({
434 localStatus: () => Effect.succeed(baseLocalStatus),
435 + currentBranch: () => Effect.succeed(baseLocalStatus.refName),
436 remoteStatus: () =>
437 Effect.gen(function* () {
438 remoteReads += 1;
@@ -426,6 +443,8 @@ describe("VcsStatusBroadcaster", () => {
443 }
444 return remoteStatusWithPr;
445 }),
446 + invalidateLocalStatus: () => Effect.void,
447 + invalidateRemoteStatus: () => Effect.void,
448 invalidateStatus: () => Effect.void,
449 }),
450 ),
@@ -446,7 +465,7 @@ describe("VcsStatusBroadcaster", () => {
465 }).pipe(Effect.provide(layer), Effect.scoped);
466 });
467
449 - it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {
468 + it.effect("keeps the published local snapshot when a refresh remote read fails", () => {
469 const state = {
470 currentLocalStatus: baseLocalStatus,
471 currentRemoteStatus: baseRemoteStatus,
@@ -466,6 +485,7 @@ describe("VcsStatusBroadcaster", () => {
485 state.localStatusCalls += 1;
486 return state.currentLocalStatus;
487 }),
488 + currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
489 remoteStatus: () =>
490 Effect.suspend(() => {
491 state.remoteStatusCalls += 1;
@@ -511,10 +531,18 @@ describe("VcsStatusBroadcaster", () => {
531 state.failRemoteStatus = true;
532
533 const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);
514 - const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
534 + const snapshot = yield* Stream.runHead(
535 + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),
536 + );
537
538 assert.isTrue(Exit.isFailure(refreshExit));
517 - assert.deepStrictEqual(cached, baseStatus);
539 + assert.isTrue(Option.isSome(snapshot));
540 + const event = Option.getOrThrow(snapshot);
541 + assert.equal(event._tag, "snapshot");
542 + if (event._tag === "snapshot") {
543 + assert.equal(event.local.refName, "feature/partial-refresh");
544 + assert.isNull(event.remote);
545 + }
546 }).pipe(Effect.provide(layerTest));
547 });
548
@@ -541,6 +569,7 @@ describe("VcsStatusBroadcaster", () => {
569 state.localStatusCalls += 1;
570 return state.currentLocalStatus;
571 }),
572 + currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
573 remoteStatus: (input) =>
574 Effect.sync(() => {
575 seenCwds.push(input.cwd);
@@ -615,6 +644,256 @@ describe("VcsStatusBroadcaster", () => {
644 }).pipe(Effect.provide(layerTestFor(state)));
645 });
646
647 + it.effect("publishes local status while an earlier lookup holds the remote lock", () => {
648 + const state: Parameters<typeof layerTestFor>[0] = {
649 + currentLocalStatus: baseLocalStatus,
650 + currentRemoteStatus: baseRemoteStatus,
651 + localStatusCalls: 0,
652 + remoteStatusCalls: 0,
653 + localInvalidationCalls: 0,
654 + remoteInvalidationCalls: 0,
655 + };
656 +
657 + return Effect.gen(function* () {
658 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
659 + yield* broadcaster.getStatus({ cwd: "/repo" });
660 + const subscribed = yield* Deferred.make<void>();
661 + const published = yield* Deferred.make<VcsStatusLocalResult>();
662 + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
663 + Stream.runForEach((event) => {
664 + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
665 + if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
666 + return Effect.void;
667 + }),
668 + Effect.forkScoped,
669 + );
670 + yield* Deferred.await(subscribed);
671 + const started = yield* Deferred.make<void>();
672 + const release = yield* Deferred.make<void>();
673 + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
674 + Effect.andThen(Deferred.await(release)),
675 + );
676 + const earlier = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);
677 + yield* Deferred.await(started);
678 + state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
679 + const completed = yield* Deferred.make<void>();
680 + const refresh = yield* broadcaster
681 + .refreshStatus("/repo")
682 + .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);
683 +
684 + assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
685 + assert.isFalse(yield* Deferred.isDone(completed));
686 + assert.isFalse(yield* Deferred.isDone(release));
687 + state.currentRemoteStatus = remoteStatusWithPr;
688 + yield* Deferred.succeed(release, undefined);
689 + yield* Fiber.join(earlier);
690 + const status = yield* Fiber.join(refresh);
691 + assert.isTrue(status.hasWorkingTreeChanges);
692 + assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
693 + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
694 + });
695 +
696 + it.effect("publishes local changes before a remote error and propagates that error", () => {
697 + const remoteError = new GitManagerError({
698 + operation: "VcsStatusBroadcaster.remoteStatus",
699 + cwd: "/repo",
700 + detail: "The controlled remote lookup failed.",
701 + });
702 + const state: Parameters<typeof layerTestFor>[0] = {
703 + currentLocalStatus: baseLocalStatus,
704 + currentRemoteStatus: remoteStatusWithPr,
705 + localStatusCalls: 0,
706 + remoteStatusCalls: 0,
707 + localInvalidationCalls: 0,
708 + remoteInvalidationCalls: 0,
709 + };
710 +
711 + return Effect.gen(function* () {
712 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
713 + yield* broadcaster.getStatus({ cwd: "/repo" });
714 + const subscribed = yield* Deferred.make<void>();
715 + const published = yield* Deferred.make<VcsStatusLocalResult>();
716 + yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(
717 + Stream.runForEach((event) => {
718 + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);
719 + if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);
720 + return Effect.void;
721 + }),
722 + Effect.forkScoped,
723 + );
724 + yield* Deferred.await(subscribed);
725 + const started = yield* Deferred.make<void>();
726 + const release = yield* Deferred.make<void>();
727 + const completed = yield* Deferred.make<void>();
728 + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
729 + Effect.andThen(Deferred.await(release)),
730 + );
731 + state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };
732 + state.remoteStatusError = remoteError;
733 + const refresh = yield* broadcaster
734 + .refreshStatus("/repo")
735 + .pipe(
736 + Effect.result,
737 + Effect.ensuring(Deferred.succeed(completed, undefined)),
738 + Effect.forkScoped,
739 + );
740 + yield* Deferred.await(started);
741 + assert.isFalse(yield* Deferred.isDone(completed));
742 + const pending = Option.getOrThrow(
743 + yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
744 + );
745 + assert.equal(pending._tag, "snapshot");
746 + if (pending._tag === "snapshot") assert.isTrue(pending.local.hasWorkingTreeChanges);
747 + yield* Deferred.succeed(release, undefined);
748 + const result = yield* Fiber.join(refresh);
749 + assert.equal(result._tag, "Failure");
750 + if (result._tag === "Failure") assert.strictEqual(result.failure, remoteError);
751 + const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
752 + assert.isTrue(cached.hasWorkingTreeChanges);
753 + assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);
754 + assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
755 + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
756 + });
757 +
758 + it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(
759 + "%s keeps response parts consistent when local state changes after the remote cache write",
760 + (operation) => {
761 + const state: Parameters<typeof layerTestFor>[0] = {
762 + currentLocalStatus: baseLocalStatus,
763 + currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
764 + localStatusCalls: 0,
765 + remoteStatusCalls: 0,
766 + localInvalidationCalls: 0,
767 + remoteInvalidationCalls: 0,
768 + fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),
769 + };
770 + const autoPull = operation === "autoPull" || operation === "autoPullFailure";
771 + if (autoPull) {
772 + state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: true };
773 + state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 0, behindCount: 5 };
774 + state.pullCurrentBranch = () =>
775 + operation === "autoPullFailure"
776 + ? Effect.fail(
777 + new GitCommandError({
778 + operation: "test.pull",
779 + command: "pull",
780 + cwd: "/repo",
781 + detail: "Pull failed.",
782 + }),
783 + )
784 + : Effect.succeed({
785 + status: "pulled",
786 + refName: "feature/status-broadcast",
787 + upstreamRef: "origin/main",
788 + });
789 + }
790 + const layerTest = layerTestFor(state).pipe(
791 + Layer.provide(
792 + Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {
793 + isEnabled: () => Effect.succeed(autoPull),
794 + }),
795 + ),
796 + );
797 + return Effect.gen(function* () {
798 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
799 + let switched = false;
800 + let remoteWritten = false;
801 + const writeCompleted = yield* Deferred.make<void>();
802 + const localRefresh = yield* Effect.gen(function* () {
803 + yield* Deferred.await(writeCompleted);
804 + state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
805 + yield* broadcaster.refreshLocalStatus("/repo");
806 + switched = true;
807 + }).pipe(Effect.forkScoped);
808 + const scheduler = new Scheduler.MixedScheduler();
809 + const shouldYield = scheduler.shouldYield.bind(scheduler);
810 + scheduler.shouldYield = (fiber) => (remoteWritten && !switched) || shouldYield(fiber);
811 + const tracer = Tracer.make({
812 + span: (options) => {
813 + const span = new Tracer.NativeSpan(options);
814 + const end = span.end.bind(span);
815 + span.end = (time, exit) => {
816 + end(time, exit);
817 + if (
818 + options.name !== "VcsStatusBroadcaster.updateCachedRemoteStatus" ||
819 + remoteWritten
820 + ) {
821 + return;
822 + }
823 + // Yield this reader after its write until the local refresh finishes.
824 + remoteWritten = true;
825 + Deferred.doneUnsafe(writeCompleted, Effect.void);
826 + };
827 + return span;
828 + },
829 + });
830 + const status = yield* (
831 + operation === "getStatus"
832 + ? broadcaster.getStatus({ cwd: "/repo" })
833 + : broadcaster.refreshStatus("/repo")
834 + ).pipe(Effect.withTracer(tracer), Effect.provideService(Scheduler.Scheduler, scheduler));
835 + yield* Fiber.join(localRefresh);
836 + assert.isTrue(switched);
837 + assert.equal(status.refName, "feature/next-status");
838 + assert.isNull(status.pr);
839 + assert.equal(status.aheadCount, 0);
840 + assert.equal(status.behindCount, 0);
841 + }).pipe(Effect.provide(layerTest), Effect.scoped);
842 + },
843 + );
844 +
845 + it.effect("recovers a discarded branch lookup on the next permitted turn-end refresh", () => {
846 + const state: Parameters<typeof layerTestFor>[0] = {
847 + currentLocalStatus: baseLocalStatus,
848 + currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },
849 + localStatusCalls: 0,
850 + remoteStatusCalls: 0,
851 + localInvalidationCalls: 0,
852 + remoteInvalidationCalls: 0,
853 + };
854 +
855 + return Effect.gen(function* () {
856 + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
857 + const started = yield* Deferred.make<void>();
858 + const release = yield* Deferred.make<void>();
859 + state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(
860 + Effect.andThen(Deferred.await(release)),
861 + );
862 + const lookup = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);
863 + yield* Deferred.await(started);
864 + state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };
865 + yield* Deferred.succeed(release, undefined);
866 + const discarded = yield* Fiber.join(lookup);
867 + assert.equal(discarded.refName, state.currentLocalStatus.refName);
868 + assert.isNull(discarded.pr);
869 + assert.equal(discarded.aheadCount, 0);
870 + assert.equal(discarded.behindCount, 0);
871 + const snapshot = Option.getOrThrow(
872 + yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),
873 + );
874 + assert.equal(snapshot._tag, "snapshot");
875 + if (snapshot._tag === "snapshot") assert.isNull(snapshot.remote);
876 +
877 + state.beforeRemoteStatus = Effect.void;
878 + state.currentRemoteStatus = {
879 + ...baseRemoteStatus,
880 + aheadCount: 2,
881 + pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" },
882 + };
883 + state.backgroundWorkEnabled = false;
884 + yield* broadcaster.refreshPullRequestStatus("/repo");
885 + assert.equal(state.remoteStatusCalls, 1);
886 + state.backgroundWorkEnabled = true;
887 + const recovered = yield* broadcaster.refreshPullRequestStatus("/repo");
888 + assert.deepStrictEqual(recovered, state.currentRemoteStatus);
889 + const cached = yield* broadcaster.getStatus({ cwd: "/repo" });
890 + assert.equal(cached.refName, state.currentLocalStatus.refName);
891 + assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);
892 + assert.equal(cached.aheadCount, 2);
893 + assert.equal(state.remoteStatusCalls, 2);
894 + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
895 + });
896 +
897 it.effect("releases remote demand while passive observers remain", () => {
898 const state = {
899 currentLocalStatus: baseLocalStatus,
@@ -636,6 +915,7 @@ describe("VcsStatusBroadcaster", () => {
915 state.localStatusCalls += 1;
916 return state.currentLocalStatus;
917 }),
918 + currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),
919 remoteStatus: () =>
920 Effect.sync(() => {
921 state.remoteStatusCalls += 1;
apps/server/src/vcs/VcsStatusBroadcaster.ts
+107 -129
@@ -130,9 +130,13 @@ interface CachedValue<T> {
130 readonly value: T;
131 }
132
133 +interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
134 + readonly branch: string | null;
135 +}
136 +
137 interface CachedVcsStatus {
138 readonly local: CachedValue<VcsStatusLocalResult> | null;
135 - readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
139 + readonly remote: CachedRemoteStatus | null;
140 }
141
142 interface ActiveRemotePoller {
@@ -261,106 +265,51 @@ export const make = Effect.gen(function* () {
265
266 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
267 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
264 - const nextLocal = {
265 - fingerprint: fingerprintStatusPart(local),
266 - value: local,
267 - } satisfies CachedValue<VcsStatusLocalResult>;
268 - const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
268 + const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
269 + const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
270 const previous = cache.get(cwd) ?? { local: null, remote: null };
270 - const nextCache = new Map(cache);
271 - nextCache.set(cwd, {
272 - ...previous,
273 - local: nextLocal,
274 - });
275 - return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
271 + const remote = previous.remote?.branch === local.refName ? previous.remote : null;
272 + return [
273 + [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
274 + new Map(cache).set(cwd, { local: nextLocal, remote }),
275 + ] as const;
276 });
277 -
278 - if (options?.publish && shouldPublish) {
277 + if (options?.publish && remoteCleared) {
278 yield* PubSub.publish(changesPubSub, {
279 cwd,
281 - event: {
282 - _tag: "localUpdated",
283 - local,
284 - },
280 + event: { _tag: "remoteUpdated", remote: null },
281 + });
282 + }
283 + if (options?.publish && localChanged) {
284 + yield* PubSub.publish(changesPubSub, {
285 + cwd,
286 + event: { _tag: "localUpdated", local },
287 });
288 }
287 -
289 return local;
290 },
291 );
292
293 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
293 - function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
294 - const nextRemote = {
295 - fingerprint: fingerprintStatusPart(remote),
296 - value: remote,
297 - } satisfies CachedValue<VcsStatusRemoteResult | null>;
298 - const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
294 + function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
295 + const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
296 const previous = cache.get(cwd) ?? { local: null, remote: null };
300 - const nextCache = new Map(cache);
301 - nextCache.set(cwd, {
302 - ...previous,
303 - remote: nextRemote,
304 - });
305 - return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
297 + const next = remote?.branch === previous.local?.value.refName ? remote : null;
298 + return [
299 + [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
300 + new Map(cache).set(cwd, { ...previous, remote: next }),
301 + ] as const;
302 });
307 -
308 - if (options?.publish && shouldPublish) {
303 + if (options?.publish && changed) {
304 yield* PubSub.publish(changesPubSub, {
305 cwd,
311 - event: {
312 - _tag: "remoteUpdated",
313 - remote,
314 - },
306 + event: { _tag: "remoteUpdated", remote: value },
307 });
308 }
317 -
318 - return remote;
309 + return value;
310 },
311 );
312
322 - const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
323 - cwd: string,
324 - local: VcsStatusLocalResult,
325 - remote: VcsStatusRemoteResult | null,
326 - options?: { publish?: boolean },
327 - ) {
328 - const nextLocal = {
329 - fingerprint: fingerprintStatusPart(local),
330 - value: local,
331 - } satisfies CachedValue<VcsStatusLocalResult>;
332 - const nextRemote = {
333 - fingerprint: fingerprintStatusPart(remote),
334 - value: remote,
335 - } satisfies CachedValue<VcsStatusRemoteResult | null>;
336 - const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
337 - const previous = cache.get(cwd) ?? { local: null, remote: null };
338 - const nextCache = new Map(cache);
339 - nextCache.set(cwd, {
340 - local: nextLocal,
341 - remote: nextRemote,
342 - });
343 - return [
344 - previous.local?.fingerprint !== nextLocal.fingerprint ||
345 - previous.remote?.fingerprint !== nextRemote.fingerprint,
346 - nextCache,
347 - ] as const;
348 - });
349 -
350 - if (options?.publish && shouldPublish) {
351 - yield* PubSub.publish(changesPubSub, {
352 - cwd,
353 - event: {
354 - _tag: "snapshot",
355 - local,
356 - remote,
357 - },
358 - });
359 - }
360 -
361 - return mergeGitStatusParts(local, remote);
362 - });
363 -
313 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
314 cwd: string,
315 ) {
@@ -378,6 +327,14 @@ export const make = Effect.gen(function* () {
327 return yield* loadLocalStatus(cwd);
328 });
329
330 + const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
331 + const cached = yield* getCachedStatus(cwd);
332 + if (cached?.local) {
333 + return { local: cached.local.value, remote: cached.remote?.value ?? null };
334 + }
335 + return { local: yield* loadLocalStatus(cwd), remote: null };
336 + });
337 +
338 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
339
340 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
@@ -388,21 +345,16 @@ export const make = Effect.gen(function* () {
345 if (cached?.local && cached.remote) {
346 return mergeGitStatusParts(cached.local.value, cached.remote.value);
347 }
348 + yield* getOrLoadLocalStatus(cwd);
349 return yield* withRemoteWriteLock(
350 cwd,
351 Effect.gen(function* () {
352 const latest = yield* getCachedStatus(cwd);
353 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
396 - const [local, remote] = yield* Effect.all(
397 - [
398 - latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
399 - latest?.remote
400 - ? Effect.succeed(latest.remote.value)
401 - : workflow.remoteStatus({ cwd }, { refreshUpstream }),
402 - ],
403 - { concurrency: "unbounded" },
404 - );
405 - return yield* updateCachedStatus(cwd, local, remote);
354 + const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
355 + yield* updateCachedRemoteStatus(cwd, remote);
356 + const parts = yield* getStatusParts(cwd);
357 + return mergeGitStatusParts(parts.local, parts.remote);
358 }),
359 );
360 });
@@ -422,11 +374,30 @@ export const make = Effect.gen(function* () {
374 return yield* refreshLocalStatusCore(cwd);
375 });
376
377 + const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
378 + cwd: string,
379 + options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
380 + ) {
381 + const branch = yield* workflow.currentBranch(cwd);
382 + // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
383 + yield* workflow.invalidateRemoteStatus(cwd);
384 + const value = yield* workflow.remoteStatus({ cwd }, options);
385 + const currentBranch = yield* workflow.currentBranch(cwd);
386 + const cached = yield* getCachedStatus(cwd);
387 + if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
388 + yield* refreshLocalStatusCore(cwd);
389 + }
390 + return branch === currentBranch
391 + ? { branch, value, fingerprint: fingerprintStatusPart(value) }
392 + : null;
393 + });
394 +
395 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
396 cwd: string,
427 - remote: VcsStatusRemoteResult | null,
397 + remoteRead: CachedRemoteStatus | null,
398 policyCwds: ReadonlyArray<string>,
399 ) {
400 + const remote = remoteRead?.value ?? null;
401 let pullAttempted = false;
402 return yield* Effect.gen(function* () {
403 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
@@ -444,17 +415,21 @@ export const make = Effect.gen(function* () {
415
416 yield* workflow.invalidateLocalStatus(cwd);
417 const local = yield* workflow.localStatus({ cwd });
447 - if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
418 + if (
419 + !local.isRepo ||
420 + !local.isDefaultRef ||
421 + local.hasWorkingTreeChanges ||
422 + local.refName !== remoteRead?.branch
423 + )
424 + return null;
425
426 pullAttempted = true;
427 yield* workflow.pullCurrentBranch(cwd);
428 yield* workflow.invalidateStatus(cwd);
452 - const [refreshedLocal, refreshedRemote] = yield* Effect.all(
453 - [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
454 - { concurrency: "unbounded" },
455 - );
456 - yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
457 - return { local: refreshedLocal, remote: refreshedRemote };
429 + yield* refreshLocalStatusCore(cwd);
430 + const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
431 + yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
432 + return yield* getStatusParts(cwd);
433 }).pipe(
434 Effect.catch((error) =>
435 Effect.gen(function* () {
@@ -463,11 +438,11 @@ export const make = Effect.gen(function* () {
438 errorTag: error._tag,
439 });
440 if (!pullAttempted) return null;
466 - // Pull can change local state before failing; propagate reconciliation failures instead of publishing stale status.
467 - yield* workflow.invalidateLocalStatus(cwd);
468 - const local = yield* workflow.localStatus({ cwd });
469 - yield* updateCachedStatus(cwd, local, remote, { publish: true });
470 - return { local, remote };
441 + // A pull or its follow-up reads can fail after local state has changed.
442 + // Let a failed reconciliation reach the caller instead of publishing old status.
443 + yield* refreshLocalStatusCore(cwd);
444 + yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
445 + return yield* getStatusParts(cwd);
446 }),
447 ),
448 );
@@ -483,15 +458,13 @@ export const make = Effect.gen(function* () {
458 return yield* withRemoteWriteLock(
459 cwd,
460 Effect.gen(function* () {
486 - if (options?.refreshUpstream !== false) {
487 - yield* workflow.invalidateRemoteStatus(cwd);
488 - }
461 const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;
490 - const remote = yield* workflow.remoteStatus({ cwd }, options);
462 + const remoteRead = yield* readRemoteStatus(cwd, options);
463 + const remote = remoteRead?.value;
464 const pulled =
465 options?.refreshUpstream === false
466 ? null
494 - : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
467 + : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
468 if (pulled !== null) return pulled.remote;
469 if (
470 remote &&
@@ -502,7 +475,7 @@ export const make = Effect.gen(function* () {
475 ) {
476 yield* refreshLocalStatusCore(cwd);
477 }
505 - return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
478 + return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
479 }),
480 );
481 });
@@ -511,35 +484,41 @@ export const make = Effect.gen(function* () {
484 "VcsStatusBroadcaster.refreshStatus",
485 )(function* (rawCwd, options) {
486 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
487 + const previous = options?.localOnly ? yield* getCachedStatus(cwd) : null;
488 + const local = yield* refreshLocalStatusCore(cwd);
489 if (options?.localOnly) {
490 return yield* withRemoteWriteLock(
491 cwd,
492 Effect.gen(function* () {
518 - yield* workflow.invalidateLocalStatus(cwd);
519 - const local = yield* workflow.localStatus({ cwd });
520 - const previous = yield* getCachedStatus(cwd);
521 - if (previous?.local?.value.refName !== local.refName) {
493 + if (previous?.local?.value.refName !== local.refName || !previous?.remote) {
494 yield* workflow.invalidateRemoteStatus(cwd);
523 - return yield* updateCachedStatus(cwd, local, null, { publish: true });
495 + yield* updateCachedRemoteStatus(
496 + cwd,
497 + { branch: local.refName, fingerprint: fingerprintStatusPart(null), value: null },
498 + { publish: true },
499 + );
500 }
525 - yield* updateCachedLocalStatus(cwd, local, { publish: true });
526 - return mergeGitStatusParts(local, previous?.remote?.value ?? null);
501 + const parts = yield* getStatusParts(cwd);
502 + return mergeGitStatusParts(parts.local, parts.remote);
503 }),
504 );
505 }
530 - // Full invalidation also bypasses GitManager's slow PR cache.
506 return yield* withRemoteWriteLock(
507 cwd,
508 Effect.gen(function* () {
509 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
510 + // Bump the PR lookup epoch after earlier remote writers have finished.
511 yield* workflow.invalidateStatus(cwd);
536 - // Local after remote: the fetch can move the base that the Changes totals compare with.
537 - const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream });
512 + const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
513 + // Fetch can move the base used for local Changes totals.
514 const local = yield* workflow.localStatus({ cwd });
515 + yield* updateCachedLocalStatus(cwd, local, { publish: true });
516 // Without a fetch, the cached behind count cannot justify an automatic pull.
540 - const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null;
517 + const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
518 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
542 - return yield* updateCachedStatus(cwd, local, remote, { publish: true });
519 + yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
520 + const parts = yield* getStatusParts(cwd);
521 + return mergeGitStatusParts(parts.local, parts.remote);
522 }),
523 );
524 });
@@ -551,7 +530,7 @@ export const make = Effect.gen(function* () {
530 cwd,
531 Effect.gen(function* () {
532 const cached = yield* getCachedStatus(cwd);
554 - if (cached?.remote?.value == null) return null;
533 + if (!cached?.local || cached.remote?.value === null) return null;
534 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
535 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
536 const shouldRefresh = (yield* Effect.forEach(
@@ -561,12 +540,11 @@ export const make = Effect.gen(function* () {
540 { concurrency: "unbounded" },
541 )).some(Boolean);
542 if (!shouldRefresh) return null;
564 - // Re-resolve the branch; cached PRs may belong to a checkout's previous branch.
565 - const remote = yield* workflow.remoteStatus(
566 - { cwd },
567 - { refreshUpstream: false, refreshMissingPullRequest: true },
568 - );
569 - return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
543 + const remoteRead = yield* readRemoteStatus(cwd, {
544 + refreshUpstream: false,
545 + refreshMissingPullRequest: true,
546 + });
547 + return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
548 }),
549 );
550 });