TypeScript
fix(server): publish local git status before remote lookup (#21046)
Yannic Charlone677e9799df4
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.tsindex 8e6a42c2271..7f374a79934 100644--- a/apps/server/src/git/GitManager.test.ts+++ b/apps/server/src/git/GitManager.test.ts@@ -1,3 +1,5 @@+import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";+import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";import { SourceControlProviderKind } from "@t3tools/contracts";// @effect-diagnostics nodeBuiltinImport:offimport * as NodeFS from "node:fs";@@ -69,6 +71,10 @@ type FakeChangeRequest = Omit<ChangeRequest, "provider" | "state" | "updatedAt">};interface FakeProviderScenario {+ prListGate?: {+ readonly started: Deferred.Deferred<void>;+ readonly release: Deferred.Deferred<void>;+ };/** The kind the fake host reports itself as. */kind?: string;/** Answers to successive change request listings, whatever their head selector. */@@ -452,6 +458,13 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): {[]).map(toChangeRequest),),+ Effect.tap(() =>+ scenario.prListGate+ ? Deferred.succeed(scenario.prListGate.started, undefined).pipe(+ Effect.andThen(Deferred.await(scenario.prListGate.release)),+ )+ : Effect.void,+ ),),createChangeRequest: (input) =>record(input.cwd, {@@ -723,6 +736,108 @@ const layerGitManagerTest = GitVcsDriver.layer.pipe();it.layer(layerGitManagerTest)("GitManager", (it) => {+ it.effect(+ "publishes local Git changes during a held PR lookup without caching its old branch",+ () =>+ Effect.gen(function* () {+ const repoDir = yield* makeTempDir("t3code-refresh-status-gh-gate-");+ yield* initRepo(repoDir);+ yield* runGit(repoDir, ["checkout", "-b", "release"]);+ const remoteDir = yield* createBareRemote();+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);+ yield* runGit(repoDir, ["push", "-u", "origin", "release"]);+ yield* runGit(repoDir, ["tag", "release"]);+ const oldPr = {+ number: 613,+ title: "Release PR",+ url: "https://github.com/pingdotgg/codething-mvp/pull/613",+ baseRefName: "main",+ headRefName: "release",+ };+ const newPr = { ...oldPr, number: 614, headRefName: "heads/release" };+ const providerScenario: FakeProviderScenario = {+ prListSequence: [oldPr, oldPr, newPr].map((pr) => [pr]),+ };+ const { manager } = yield* makeManager({ providerScenario });+ const context = yield* Layer.build(+ VcsStatusBroadcaster.layer.pipe(+ Layer.provide(+ GitWorkflowService.layer.pipe(+ Layer.provide(Layer.succeed(GitManager.GitManager, manager)),+ Layer.provide(+ VcsDriverRegistry.layer.pipe(+ Layer.provide(VcsProjectConfig.layer),+ Layer.provide(VcsProcess.layer),+ ),+ ),+ ),+ ),+ Layer.provide(+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({+ shouldRunScopeWork: () => Effect.succeed(true),+ }),+ ),+ ),+ );+ const broadcaster = Context.get(context, VcsStatusBroadcaster.VcsStatusBroadcaster);+ const initial = yield* broadcaster.getStatus({ cwd: repoDir });+ expect(initial.refName).toBe("release");+ expect(initial.pr?.number).toBe(613);++ const subscribed = yield* Deferred.make<void>();+ const published = yield* Deferred.make<void>();+ yield* broadcaster.streamStatus({ cwd: repoDir, includeRemote: false }).pipe(+ Stream.runForEach((event) => {+ if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);+ if (event._tag === "localUpdated" && event.local.hasWorkingTreeChanges) {+ return Deferred.succeed(published, undefined);+ }+ return Effect.void;+ }),+ Effect.forkScoped,+ );+ yield* Deferred.await(subscribed);+ const gate = {+ started: yield* Deferred.make<void>(),+ release: yield* Deferred.make<void>(),+ };+ providerScenario.prListGate = gate;+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(NodePath.join(repoDir, "README.md"), "changed before refresh\n");+ const completed = yield* Deferred.make<void>();+ const refresh = yield* broadcaster+ .refreshStatus(repoDir)+ .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);+ yield* Deferred.await(gate.started);+ const pending = Option.getOrThrow(+ yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),+ );+ expect(pending._tag).toBe("snapshot");+ if (pending._tag === "snapshot") expect(pending.local.hasWorkingTreeChanges).toBe(true);+ yield* Deferred.await(published);+ expect(yield* Deferred.isDone(completed)).toBe(false);++ yield* runGit(repoDir, ["checkout", "-b", "heads/release"]);+ yield* runGit(repoDir, ["push", "-u", "origin", "refs/heads/heads/release"]);+ yield* Deferred.succeed(gate.release, undefined);+ const refreshed = yield* Fiber.join(refresh);+ expect(refreshed.refName).toBe("heads/release");+ expect(refreshed.hasWorkingTreeChanges).toBe(true);+ expect(refreshed.pr).toBeNull();+ const snapshot = Option.getOrThrow(+ yield* Stream.runHead(broadcaster.streamStatus({ cwd: repoDir, includeRemote: false })),+ );+ expect(snapshot._tag).toBe("snapshot");+ if (snapshot._tag === "snapshot") expect(snapshot.remote).toBeNull();++ delete providerScenario.prListGate;+ const recovered = yield* broadcaster.getStatus({ cwd: repoDir });+ expect(recovered.refName).toBe("heads/release");+ expect(recovered.pr?.number).toBe(614);+ expect((yield* broadcaster.getStatus({ cwd: repoDir })).pr?.number).toBe(614);+ }),+ );+it.effect("status reports the listed PR whose head is the branch", () =>Effect.gen(function* () {const repoDir = yield* makeTempDir("t3code-git-manager-");diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.tsindex 832dc6c4ef6..7bb098da878 100644--- a/apps/server/src/git/GitWorkflowService.ts+++ b/apps/server/src/git/GitWorkflowService.ts@@ -52,6 +52,7 @@ export class GitWorkflowService extends Context.Service<readonly localStatus: (input: VcsStatusInput,) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;+ readonly currentBranch: (cwd: string) => Effect.Effect<string | null, GitManagerServiceError>;readonly remoteStatus: (input: VcsStatusInput,options?: GitManager.GitRemoteStatusOptions,@@ -332,6 +333,32 @@ export const make = Effect.gen(function* () {),);}),+ currentBranch: Effect.fn("GitWorkflowService.currentBranch")(function* (cwd) {+ if (!(yield* detectGitRepositoryForStatus("GitWorkflowService.currentBranch", cwd))) {+ return null;+ }+ const result = yield* git.execute({+ operation: "GitWorkflowService.currentBranch",+ cwd,+ args: ["symbolic-ref", "--quiet", "HEAD"],+ allowNonZeroExit: true,+ timeoutMs: 5_000,+ });+ if (result.exitCode === 0) {+ return result.stdout.trim().replace(/^refs\/heads\//, "") || null;+ }+ if (result.exitCode === 1) return null;+ return yield* new GitCommandError({+ operation: "GitWorkflowService.currentBranch",+ command: "git symbolic-ref",+ cwd,+ argumentCount: 3,+ ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),+ stdoutLength: result.stdout.length,+ stderrLength: result.stderr.length,+ detail: "Failed to read the checked-out branch.",+ });+ }),remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) {return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(Effect.flatMap((isGitRepository) =>diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.tsindex bdf5dfff6c4..cc1b6d24e38 100644--- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts+++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts@@ -12,16 +12,17 @@ import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Scope from "effect/Scope";+import * as Scheduler from "effect/Scheduler";import * as Stream from "effect/Stream";import * as TestClock from "effect/testing/TestClock";+import * as Tracer from "effect/Tracer";import type {BackgroundScope,VcsStatusLocalResult,VcsStatusRemoteResult,- VcsStatusResult,VcsStatusStreamEvent,} from "@t3tools/contracts";-import { GitManagerError } from "@t3tools/contracts";+import { GitCommandError, GitManagerError } from "@t3tools/contracts";import * as VcsStatusBroadcaster from "./VcsStatusBroadcaster.ts";import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";@@ -58,16 +59,11 @@ const remoteStatusWithPr: VcsStatusRemoteResult = {title: "[codex] Rewrite client connection architecture",url: "https://github.com/pingdotgg/t3code/pull/2978",baseRef: "main",- headRef: "codex/connection-state-audit",+ headRef: "upstream-topic",state: "open",},};-const baseStatus: VcsStatusResult = {- ...baseLocalStatus,- ...baseRemoteStatus,-};-function layerTestFor(state: {currentLocalStatus: VcsStatusLocalResult;currentRemoteStatus: VcsStatusRemoteResult | null;@@ -76,12 +72,19 @@ function layerTestFor(state: {localInvalidationCalls: number;remoteInvalidationCalls: number;remoteStatusRefreshUpstreamValues?: Array<boolean | undefined>;+ remoteStatusError?: GitManagerError;backgroundWorkEnabled?: boolean;automaticFetchInterval?: Effect.Effect<Duration.Duration>;beforeRemoteStatus?: Effect.Effect<void>;+ fileSystem?: FileSystem.FileSystem;+ pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"];}) {return VcsStatusBroadcaster.layer.pipe(- Layer.provideMerge(NodeServices.layer),+ Layer.provideMerge(+ state.fileSystem+ ? Layer.succeed(FileSystem.FileSystem, state.fileSystem)+ : NodeServices.layer,+ ),Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)),Layer.provide(Layer.succeed(@@ -96,16 +99,22 @@ function layerTestFor(state: {state.localStatusCalls += 1;return state.currentLocalStatus;}),+ currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName),remoteStatus: (_input, options) =>- Effect.suspend(() => state.beforeRemoteStatus ?? Effect.void).pipe(- Effect.andThen(- Effect.sync(() => {- state.remoteStatusCalls += 1;- state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);- return state.currentRemoteStatus;- }),- ),- ),+ Effect.suspend(() => {+ return (state.beforeRemoteStatus ?? Effect.void).pipe(+ Effect.andThen(+ Effect.sync(() => {+ state.remoteStatusCalls += 1;+ state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream);+ return state.currentRemoteStatus;+ }),+ ),+ Effect.tap(() =>+ state.remoteStatusError ? Effect.fail(state.remoteStatusError) : Effect.void,+ ),+ );+ }),invalidateLocalStatus: () =>Effect.sync(() => {state.localInvalidationCalls += 1;@@ -119,6 +128,7 @@ function layerTestFor(state: {state.localInvalidationCalls += 1;state.remoteInvalidationCalls += 1;}),+ ...(state.pullCurrentBranch ? { pullCurrentBranch: state.pullCurrentBranch } : {}),}),),);@@ -171,7 +181,7 @@ describe("VcsStatusBroadcaster", () => {Stream.tap((event) =>event._tag === "snapshot" ? Deferred.succeed(subscribed, undefined) : Effect.void,),- Stream.take(2),+ Stream.take(3),Stream.runCollect,Effect.forkScoped,);@@ -183,12 +193,11 @@ describe("VcsStatusBroadcaster", () => {assert.isNull(refreshed.pr);assert.equal(state.localInvalidationCalls, 1);assert.equal(state.remoteStatusCalls, 1);- assert.equal(state.remoteInvalidationCalls, 1);- assert.deepStrictEqual((yield* Fiber.join(events))[1], {- _tag: "snapshot",- local: state.currentLocalStatus,- remote: null,- });+ assert.equal(state.remoteInvalidationCalls, 2);+ assert.deepStrictEqual((yield* Fiber.join(events)).slice(1), [+ { _tag: "remoteUpdated", remote: null },+ { _tag: "localUpdated", local: state.currentLocalStatus },+ ]);assert.isNull((yield* broadcaster.getStatus({ cwd: "/repo" })).pr);const snapshot = yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })@@ -220,7 +229,7 @@ describe("VcsStatusBroadcaster", () => {assert.deepStrictEqual(refreshed, initial);assert.deepStrictEqual(yield* broadcaster.getStatus({ cwd: "/repo" }), refreshed);assert.equal(state.localInvalidationCalls, 1);- assert.equal(state.remoteInvalidationCalls, 0);+ assert.equal(state.remoteInvalidationCalls, 1);assert.equal(state.remoteStatusCalls, 1);}).pipe(Effect.provide(layerTestFor(state)));},@@ -288,6 +297,7 @@ describe("VcsStatusBroadcaster", () => {Layer.provide(Layer.mock(GitWorkflowService.GitWorkflowService)({localStatus: () => Effect.succeed(localStatus),+ currentBranch: () => Effect.succeed(localStatus.refName),remoteStatus: () => Effect.succeed(remoteStatus),invalidateLocalStatus: () => Effect.void,invalidateRemoteStatus: () => Effect.void,@@ -350,7 +360,7 @@ describe("VcsStatusBroadcaster", () => {const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo");assert.deepStrictEqual(refreshed, remoteStatusWithPr);assert.equal(state.remoteStatusCalls, 2);- assert.equal(state.remoteInvalidationCalls, 0);+ assert.equal(state.remoteInvalidationCalls, 2);state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next" };state.currentRemoteStatus = baseRemoteStatus;@@ -358,6 +368,11 @@ describe("VcsStatusBroadcaster", () => {const refreshedBranch = yield* broadcaster.refreshPullRequestStatus("/repo");assert.deepStrictEqual(refreshedBranch, baseRemoteStatus);assert.equal(state.remoteStatusCalls, 3);+ const refreshedStatus = yield* broadcaster.getStatus({ cwd: "/repo" });+ assert.equal(refreshedStatus.refName, "feature/next");+ assert.isNull(refreshedStatus.pr);+ assert.equal(state.remoteStatusCalls, 3);+ assert.equal(state.remoteInvalidationCalls, 3);}).pipe(Effect.provide(layerTestFor(state)));});@@ -371,6 +386,7 @@ describe("VcsStatusBroadcaster", () => {Layer.provide(Layer.mock(GitWorkflowService.GitWorkflowService)({localStatus: () => Effect.succeed(baseLocalStatus),+ currentBranch: () => Effect.succeed(baseLocalStatus.refName),remoteStatus: () =>Effect.gen(function* () {remoteReads += 1;@@ -416,6 +432,7 @@ describe("VcsStatusBroadcaster", () => {Layer.provide(Layer.mock(GitWorkflowService.GitWorkflowService)({localStatus: () => Effect.succeed(baseLocalStatus),+ currentBranch: () => Effect.succeed(baseLocalStatus.refName),remoteStatus: () =>Effect.gen(function* () {remoteReads += 1;@@ -426,6 +443,8 @@ describe("VcsStatusBroadcaster", () => {}return remoteStatusWithPr;}),+ invalidateLocalStatus: () => Effect.void,+ invalidateRemoteStatus: () => Effect.void,invalidateStatus: () => Effect.void,}),),@@ -446,7 +465,7 @@ describe("VcsStatusBroadcaster", () => {}).pipe(Effect.provide(layer), Effect.scoped);});- it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => {+ it.effect("keeps the published local snapshot when a refresh remote read fails", () => {const state = {currentLocalStatus: baseLocalStatus,currentRemoteStatus: baseRemoteStatus,@@ -466,6 +485,7 @@ describe("VcsStatusBroadcaster", () => {state.localStatusCalls += 1;return state.currentLocalStatus;}),+ currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),remoteStatus: () =>Effect.suspend(() => {state.remoteStatusCalls += 1;@@ -511,10 +531,18 @@ describe("VcsStatusBroadcaster", () => {state.failRemoteStatus = true;const refreshExit = yield* broadcaster.refreshStatus("/repo").pipe(Effect.exit);- const cached = yield* broadcaster.getStatus({ cwd: "/repo" });+ const snapshot = yield* Stream.runHead(+ broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }),+ );assert.isTrue(Exit.isFailure(refreshExit));- assert.deepStrictEqual(cached, baseStatus);+ assert.isTrue(Option.isSome(snapshot));+ const event = Option.getOrThrow(snapshot);+ assert.equal(event._tag, "snapshot");+ if (event._tag === "snapshot") {+ assert.equal(event.local.refName, "feature/partial-refresh");+ assert.isNull(event.remote);+ }}).pipe(Effect.provide(layerTest));});@@ -541,6 +569,7 @@ describe("VcsStatusBroadcaster", () => {state.localStatusCalls += 1;return state.currentLocalStatus;}),+ currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),remoteStatus: (input) =>Effect.sync(() => {seenCwds.push(input.cwd);@@ -615,6 +644,256 @@ describe("VcsStatusBroadcaster", () => {}).pipe(Effect.provide(layerTestFor(state)));});+ it.effect("publishes local status while an earlier lookup holds the remote lock", () => {+ const state: Parameters<typeof layerTestFor>[0] = {+ currentLocalStatus: baseLocalStatus,+ currentRemoteStatus: baseRemoteStatus,+ localStatusCalls: 0,+ remoteStatusCalls: 0,+ localInvalidationCalls: 0,+ remoteInvalidationCalls: 0,+ };++ return Effect.gen(function* () {+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;+ yield* broadcaster.getStatus({ cwd: "/repo" });+ const subscribed = yield* Deferred.make<void>();+ const published = yield* Deferred.make<VcsStatusLocalResult>();+ yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(+ Stream.runForEach((event) => {+ if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);+ if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);+ return Effect.void;+ }),+ Effect.forkScoped,+ );+ yield* Deferred.await(subscribed);+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(+ Effect.andThen(Deferred.await(release)),+ );+ const earlier = yield* broadcaster.refreshPullRequestStatus("/repo").pipe(Effect.forkScoped);+ yield* Deferred.await(started);+ state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };+ const completed = yield* Deferred.make<void>();+ const refresh = yield* broadcaster+ .refreshStatus("/repo")+ .pipe(Effect.ensuring(Deferred.succeed(completed, undefined)), Effect.forkScoped);++ assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);+ assert.isFalse(yield* Deferred.isDone(completed));+ assert.isFalse(yield* Deferred.isDone(release));+ state.currentRemoteStatus = remoteStatusWithPr;+ yield* Deferred.succeed(release, undefined);+ yield* Fiber.join(earlier);+ const status = yield* Fiber.join(refresh);+ assert.isTrue(status.hasWorkingTreeChanges);+ assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);+ });++ it.effect("publishes local changes before a remote error and propagates that error", () => {+ const remoteError = new GitManagerError({+ operation: "VcsStatusBroadcaster.remoteStatus",+ cwd: "/repo",+ detail: "The controlled remote lookup failed.",+ });+ const state: Parameters<typeof layerTestFor>[0] = {+ currentLocalStatus: baseLocalStatus,+ currentRemoteStatus: remoteStatusWithPr,+ localStatusCalls: 0,+ remoteStatusCalls: 0,+ localInvalidationCalls: 0,+ remoteInvalidationCalls: 0,+ };++ return Effect.gen(function* () {+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;+ yield* broadcaster.getStatus({ cwd: "/repo" });+ const subscribed = yield* Deferred.make<void>();+ const published = yield* Deferred.make<VcsStatusLocalResult>();+ yield* broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }).pipe(+ Stream.runForEach((event) => {+ if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined);+ if (event._tag === "localUpdated") return Deferred.succeed(published, event.local);+ return Effect.void;+ }),+ Effect.forkScoped,+ );+ yield* Deferred.await(subscribed);+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ const completed = yield* Deferred.make<void>();+ state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(+ Effect.andThen(Deferred.await(release)),+ );+ state.currentLocalStatus = { ...baseLocalStatus, hasWorkingTreeChanges: true };+ state.remoteStatusError = remoteError;+ const refresh = yield* broadcaster+ .refreshStatus("/repo")+ .pipe(+ Effect.result,+ Effect.ensuring(Deferred.succeed(completed, undefined)),+ Effect.forkScoped,+ );+ yield* Deferred.await(started);+ assert.isFalse(yield* Deferred.isDone(completed));+ const pending = Option.getOrThrow(+ yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),+ );+ assert.equal(pending._tag, "snapshot");+ if (pending._tag === "snapshot") assert.isTrue(pending.local.hasWorkingTreeChanges);+ yield* Deferred.succeed(release, undefined);+ const result = yield* Fiber.join(refresh);+ assert.equal(result._tag, "Failure");+ if (result._tag === "Failure") assert.strictEqual(result.failure, remoteError);+ const cached = yield* broadcaster.getStatus({ cwd: "/repo" });+ assert.isTrue(cached.hasWorkingTreeChanges);+ assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);+ assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);+ });++ it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(+ "%s keeps response parts consistent when local state changes after the remote cache write",+ (operation) => {+ const state: Parameters<typeof layerTestFor>[0] = {+ currentLocalStatus: baseLocalStatus,+ currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },+ localStatusCalls: 0,+ remoteStatusCalls: 0,+ localInvalidationCalls: 0,+ remoteInvalidationCalls: 0,+ fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }),+ };+ const autoPull = operation === "autoPull" || operation === "autoPullFailure";+ if (autoPull) {+ state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: true };+ state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 0, behindCount: 5 };+ state.pullCurrentBranch = () =>+ operation === "autoPullFailure"+ ? Effect.fail(+ new GitCommandError({+ operation: "test.pull",+ command: "pull",+ cwd: "/repo",+ detail: "Pull failed.",+ }),+ )+ : Effect.succeed({+ status: "pulled",+ refName: "feature/status-broadcast",+ upstreamRef: "origin/main",+ });+ }+ const layerTest = layerTestFor(state).pipe(+ Layer.provide(+ Layer.succeed(VcsStatusBroadcaster.VcsAutoPullPolicy, {+ isEnabled: () => Effect.succeed(autoPull),+ }),+ ),+ );+ return Effect.gen(function* () {+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;+ let switched = false;+ let remoteWritten = false;+ const writeCompleted = yield* Deferred.make<void>();+ const localRefresh = yield* Effect.gen(function* () {+ yield* Deferred.await(writeCompleted);+ state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };+ yield* broadcaster.refreshLocalStatus("/repo");+ switched = true;+ }).pipe(Effect.forkScoped);+ const scheduler = new Scheduler.MixedScheduler();+ const shouldYield = scheduler.shouldYield.bind(scheduler);+ scheduler.shouldYield = (fiber) => (remoteWritten && !switched) || shouldYield(fiber);+ const tracer = Tracer.make({+ span: (options) => {+ const span = new Tracer.NativeSpan(options);+ const end = span.end.bind(span);+ span.end = (time, exit) => {+ end(time, exit);+ if (+ options.name !== "VcsStatusBroadcaster.updateCachedRemoteStatus" ||+ remoteWritten+ ) {+ return;+ }+ // Yield this reader after its write until the local refresh finishes.+ remoteWritten = true;+ Deferred.doneUnsafe(writeCompleted, Effect.void);+ };+ return span;+ },+ });+ const status = yield* (+ operation === "getStatus"+ ? broadcaster.getStatus({ cwd: "/repo" })+ : broadcaster.refreshStatus("/repo")+ ).pipe(Effect.withTracer(tracer), Effect.provideService(Scheduler.Scheduler, scheduler));+ yield* Fiber.join(localRefresh);+ assert.isTrue(switched);+ assert.equal(status.refName, "feature/next-status");+ assert.isNull(status.pr);+ assert.equal(status.aheadCount, 0);+ assert.equal(status.behindCount, 0);+ }).pipe(Effect.provide(layerTest), Effect.scoped);+ },+ );++ it.effect("recovers a discarded branch lookup on the next permitted turn-end refresh", () => {+ const state: Parameters<typeof layerTestFor>[0] = {+ currentLocalStatus: baseLocalStatus,+ currentRemoteStatus: { ...remoteStatusWithPr, aheadCount: 3, behindCount: 5 },+ localStatusCalls: 0,+ remoteStatusCalls: 0,+ localInvalidationCalls: 0,+ remoteInvalidationCalls: 0,+ };++ return Effect.gen(function* () {+ const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;+ const started = yield* Deferred.make<void>();+ const release = yield* Deferred.make<void>();+ state.beforeRemoteStatus = Deferred.succeed(started, undefined).pipe(+ Effect.andThen(Deferred.await(release)),+ );+ const lookup = yield* broadcaster.getStatus({ cwd: "/repo" }).pipe(Effect.forkScoped);+ yield* Deferred.await(started);+ state.currentLocalStatus = { ...baseLocalStatus, refName: "feature/next-status" };+ yield* Deferred.succeed(release, undefined);+ const discarded = yield* Fiber.join(lookup);+ assert.equal(discarded.refName, state.currentLocalStatus.refName);+ assert.isNull(discarded.pr);+ assert.equal(discarded.aheadCount, 0);+ assert.equal(discarded.behindCount, 0);+ const snapshot = Option.getOrThrow(+ yield* Stream.runHead(broadcaster.streamStatus({ cwd: "/repo", includeRemote: false })),+ );+ assert.equal(snapshot._tag, "snapshot");+ if (snapshot._tag === "snapshot") assert.isNull(snapshot.remote);++ state.beforeRemoteStatus = Effect.void;+ state.currentRemoteStatus = {+ ...baseRemoteStatus,+ aheadCount: 2,+ pr: { ...remoteStatusWithPr.pr!, number: 2979, headRef: "feature/next-status" },+ };+ state.backgroundWorkEnabled = false;+ yield* broadcaster.refreshPullRequestStatus("/repo");+ assert.equal(state.remoteStatusCalls, 1);+ state.backgroundWorkEnabled = true;+ const recovered = yield* broadcaster.refreshPullRequestStatus("/repo");+ assert.deepStrictEqual(recovered, state.currentRemoteStatus);+ const cached = yield* broadcaster.getStatus({ cwd: "/repo" });+ assert.equal(cached.refName, state.currentLocalStatus.refName);+ assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);+ assert.equal(cached.aheadCount, 2);+ assert.equal(state.remoteStatusCalls, 2);+ }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);+ });+it.effect("releases remote demand while passive observers remain", () => {const state = {currentLocalStatus: baseLocalStatus,@@ -636,6 +915,7 @@ describe("VcsStatusBroadcaster", () => {state.localStatusCalls += 1;return state.currentLocalStatus;}),+ currentBranch: () => Effect.succeed(state.currentLocalStatus.refName),remoteStatus: () =>Effect.sync(() => {state.remoteStatusCalls += 1;diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.tsindex 3cbcb3546e9..8ce1b225d12 100644--- a/apps/server/src/vcs/VcsStatusBroadcaster.ts+++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts@@ -130,9 +130,13 @@ interface CachedValue<T> {readonly value: T;}+interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {+ readonly branch: string | null;+}+interface CachedVcsStatus {readonly local: CachedValue<VcsStatusLocalResult> | null;- readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;+ readonly remote: CachedRemoteStatus | null;}interface ActiveRemotePoller {@@ -261,106 +265,51 @@ export const make = Effect.gen(function* () {const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {- const nextLocal = {- fingerprint: fingerprintStatusPart(local),- value: local,- } satisfies CachedValue<VcsStatusLocalResult>;- const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {+ const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };+ const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {const previous = cache.get(cwd) ?? { local: null, remote: null };- const nextCache = new Map(cache);- nextCache.set(cwd, {- ...previous,- local: nextLocal,- });- return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;+ const remote = previous.remote?.branch === local.refName ? previous.remote : null;+ return [+ [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],+ new Map(cache).set(cwd, { local: nextLocal, remote }),+ ] as const;});-- if (options?.publish && shouldPublish) {+ if (options?.publish && remoteCleared) {yield* PubSub.publish(changesPubSub, {cwd,- event: {- _tag: "localUpdated",- local,- },+ event: { _tag: "remoteUpdated", remote: null },+ });+ }+ if (options?.publish && localChanged) {+ yield* PubSub.publish(changesPubSub, {+ cwd,+ event: { _tag: "localUpdated", local },});}-return local;},);const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(- function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {- const nextRemote = {- fingerprint: fingerprintStatusPart(remote),- value: remote,- } satisfies CachedValue<VcsStatusRemoteResult | null>;- const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {+ function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {+ const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {const previous = cache.get(cwd) ?? { local: null, remote: null };- const nextCache = new Map(cache);- nextCache.set(cwd, {- ...previous,- remote: nextRemote,- });- return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;+ const next = remote?.branch === previous.local?.value.refName ? remote : null;+ return [+ [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],+ new Map(cache).set(cwd, { ...previous, remote: next }),+ ] as const;});-- if (options?.publish && shouldPublish) {+ if (options?.publish && changed) {yield* PubSub.publish(changesPubSub, {cwd,- event: {- _tag: "remoteUpdated",- remote,- },+ event: { _tag: "remoteUpdated", remote: value },});}-- return remote;+ return value;},);- const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (- cwd: string,- local: VcsStatusLocalResult,- remote: VcsStatusRemoteResult | null,- options?: { publish?: boolean },- ) {- const nextLocal = {- fingerprint: fingerprintStatusPart(local),- value: local,- } satisfies CachedValue<VcsStatusLocalResult>;- const nextRemote = {- fingerprint: fingerprintStatusPart(remote),- value: remote,- } satisfies CachedValue<VcsStatusRemoteResult | null>;- const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {- const previous = cache.get(cwd) ?? { local: null, remote: null };- const nextCache = new Map(cache);- nextCache.set(cwd, {- local: nextLocal,- remote: nextRemote,- });- return [- previous.local?.fingerprint !== nextLocal.fingerprint ||- previous.remote?.fingerprint !== nextRemote.fingerprint,- nextCache,- ] as const;- });-- if (options?.publish && shouldPublish) {- yield* PubSub.publish(changesPubSub, {- cwd,- event: {- _tag: "snapshot",- local,- remote,- },- });- }-- return mergeGitStatusParts(local, remote);- });-const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (cwd: string,) {@@ -378,6 +327,14 @@ export const make = Effect.gen(function* () {return yield* loadLocalStatus(cwd);});+ const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {+ const cached = yield* getCachedStatus(cwd);+ if (cached?.local) {+ return { local: cached.local.value, remote: cached.remote?.value ?? null };+ }+ return { local: yield* loadLocalStatus(cwd), remote: null };+ });+const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(@@ -388,21 +345,16 @@ export const make = Effect.gen(function* () {if (cached?.local && cached.remote) {return mergeGitStatusParts(cached.local.value, cached.remote.value);}+ yield* getOrLoadLocalStatus(cwd);return yield* withRemoteWriteLock(cwd,Effect.gen(function* () {const latest = yield* getCachedStatus(cwd);const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);- const [local, remote] = yield* Effect.all(- [- latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),- latest?.remote- ? Effect.succeed(latest.remote.value)- : workflow.remoteStatus({ cwd }, { refreshUpstream }),- ],- { concurrency: "unbounded" },- );- return yield* updateCachedStatus(cwd, local, remote);+ const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));+ yield* updateCachedRemoteStatus(cwd, remote);+ const parts = yield* getStatusParts(cwd);+ return mergeGitStatusParts(parts.local, parts.remote);}),);});@@ -422,11 +374,30 @@ export const make = Effect.gen(function* () {return yield* refreshLocalStatusCore(cwd);});+ const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (+ cwd: string,+ options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],+ ) {+ const branch = yield* workflow.currentBranch(cwd);+ // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.+ yield* workflow.invalidateRemoteStatus(cwd);+ const value = yield* workflow.remoteStatus({ cwd }, options);+ const currentBranch = yield* workflow.currentBranch(cwd);+ const cached = yield* getCachedStatus(cwd);+ if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {+ yield* refreshLocalStatusCore(cwd);+ }+ return branch === currentBranch+ ? { branch, value, fingerprint: fingerprintStatusPart(value) }+ : null;+ });+const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (cwd: string,- remote: VcsStatusRemoteResult | null,+ remoteRead: CachedRemoteStatus | null,policyCwds: ReadonlyArray<string>,) {+ const remote = remoteRead?.value ?? null;let pullAttempted = false;return yield* Effect.gen(function* () {const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {@@ -444,17 +415,21 @@ export const make = Effect.gen(function* () {yield* workflow.invalidateLocalStatus(cwd);const local = yield* workflow.localStatus({ cwd });- if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;+ if (+ !local.isRepo ||+ !local.isDefaultRef ||+ local.hasWorkingTreeChanges ||+ local.refName !== remoteRead?.branch+ )+ return null;pullAttempted = true;yield* workflow.pullCurrentBranch(cwd);yield* workflow.invalidateStatus(cwd);- const [refreshedLocal, refreshedRemote] = yield* Effect.all(- [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],- { concurrency: "unbounded" },- );- yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });- return { local: refreshedLocal, remote: refreshedRemote };+ yield* refreshLocalStatusCore(cwd);+ const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });+ yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });+ return yield* getStatusParts(cwd);}).pipe(Effect.catch((error) =>Effect.gen(function* () {@@ -463,11 +438,11 @@ export const make = Effect.gen(function* () {errorTag: error._tag,});if (!pullAttempted) return null;- // Pull can change local state before failing; propagate reconciliation failures instead of publishing stale status.- yield* workflow.invalidateLocalStatus(cwd);- const local = yield* workflow.localStatus({ cwd });- yield* updateCachedStatus(cwd, local, remote, { publish: true });- return { local, remote };+ // A pull or its follow-up reads can fail after local state has changed.+ // Let a failed reconciliation reach the caller instead of publishing old status.+ yield* refreshLocalStatusCore(cwd);+ yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });+ return yield* getStatusParts(cwd);}),),);@@ -483,15 +458,13 @@ export const make = Effect.gen(function* () {return yield* withRemoteWriteLock(cwd,Effect.gen(function* () {- if (options?.refreshUpstream !== false) {- yield* workflow.invalidateRemoteStatus(cwd);- }const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;- const remote = yield* workflow.remoteStatus({ cwd }, options);+ const remoteRead = yield* readRemoteStatus(cwd, options);+ const remote = remoteRead?.value;const pulled =options?.refreshUpstream === false? null- : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);+ : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);if (pulled !== null) return pulled.remote;if (remote &&@@ -502,7 +475,7 @@ export const make = Effect.gen(function* () {) {yield* refreshLocalStatusCore(cwd);}- return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });+ return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });}),);});@@ -511,35 +484,41 @@ export const make = Effect.gen(function* () {"VcsStatusBroadcaster.refreshStatus",)(function* (rawCwd, options) {const cwd = yield* withFileSystem(normalizeCwd(rawCwd));+ const previous = options?.localOnly ? yield* getCachedStatus(cwd) : null;+ const local = yield* refreshLocalStatusCore(cwd);if (options?.localOnly) {return yield* withRemoteWriteLock(cwd,Effect.gen(function* () {- yield* workflow.invalidateLocalStatus(cwd);- const local = yield* workflow.localStatus({ cwd });- const previous = yield* getCachedStatus(cwd);- if (previous?.local?.value.refName !== local.refName) {+ if (previous?.local?.value.refName !== local.refName || !previous?.remote) {yield* workflow.invalidateRemoteStatus(cwd);- return yield* updateCachedStatus(cwd, local, null, { publish: true });+ yield* updateCachedRemoteStatus(+ cwd,+ { branch: local.refName, fingerprint: fingerprintStatusPart(null), value: null },+ { publish: true },+ );}- yield* updateCachedLocalStatus(cwd, local, { publish: true });- return mergeGitStatusParts(local, previous?.remote?.value ?? null);+ const parts = yield* getStatusParts(cwd);+ return mergeGitStatusParts(parts.local, parts.remote);}),);}- // Full invalidation also bypasses GitManager's slow PR cache.return yield* withRemoteWriteLock(cwd,Effect.gen(function* () {const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);+ // Bump the PR lookup epoch after earlier remote writers have finished.yield* workflow.invalidateStatus(cwd);- // Local after remote: the fetch can move the base that the Changes totals compare with.- const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream });+ const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });+ // Fetch can move the base used for local Changes totals.const local = yield* workflow.localStatus({ cwd });+ yield* updateCachedLocalStatus(cwd, local, { publish: true });// Without a fetch, the cached behind count cannot justify an automatic pull.- const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null;+ const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);- return yield* updateCachedStatus(cwd, local, remote, { publish: true });+ yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });+ const parts = yield* getStatusParts(cwd);+ return mergeGitStatusParts(parts.local, parts.remote);}),);});@@ -551,7 +530,7 @@ export const make = Effect.gen(function* () {cwd,Effect.gen(function* () {const cached = yield* getCachedStatus(cwd);- if (cached?.remote?.value == null) return null;+ if (!cached?.local || cached.remote?.value === null) return null;const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];const shouldRefresh = (yield* Effect.forEach(@@ -561,12 +540,11 @@ export const make = Effect.gen(function* () {{ concurrency: "unbounded" },)).some(Boolean);if (!shouldRefresh) return null;- // Re-resolve the branch; cached PRs may belong to a checkout's previous branch.- const remote = yield* workflow.remoteStatus(- { cwd },- { refreshUpstream: false, refreshMissingPullRequest: true },- );- return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });+ const remoteRead = yield* readRemoteStatus(cwd, {+ refreshUpstream: false,+ refreshMissingPullRequest: true,+ });+ return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });}),);});