diff --git a/apps/mobile/src/state/use-thread-pr.ts b/apps/mobile/src/state/use-thread-pr.ts index a3440cd484..85af767469 100644 --- a/apps/mobile/src/state/use-thread-pr.ts +++ b/apps/mobile/src/state/use-thread-pr.ts @@ -15,6 +15,10 @@ export { * (environmentId, cwd) by the atom family, so many rows on the same worktree * or project root share one stream — and virtualization means only visible * rows subscribe at all. + * + * Keyed by the thread's recorded branch, not the current checkout: the + * streamed status is the fast path while the checkout matches, and a + * branch-keyed lookup keeps the badge alive once the checkout moves away. */ export function useThreadPr( thread: EnvironmentThreadShell, @@ -29,13 +33,25 @@ export function useThreadPr( }) : null, ); + const branchPr = useEnvironmentQuery( + thread.branch !== null && cwd !== null + ? vcsEnvironment.branchPr({ + environmentId: thread.environmentId, + input: { cwd, branch: thread.branch }, + }) + : null, + ); const status = gitStatus.data; - if (status === null || thread.branch === null || status.refName !== thread.branch) { + // When the status describes the thread's own branch it is authoritative + // about that branch's PR — including when it reports none, so this must not + // fall through to a warm branch lookup that would resurrect a stale badge. + if (status !== null && thread.branch !== null && status.refName === thread.branch) { + return status.pr ? presentThreadPr(status.pr, status.sourceControlProvider) : null; + } + const pr = branchPr.data?.pr; + if (!pr) { return null; } - if (!status.pr) { - return null; - } - return presentThreadPr(status.pr, status.sourceControlProvider); + return presentThreadPr(pr, status?.sourceControlProvider); } diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 20c3e126b8..3d8f04ff33 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; @@ -288,6 +289,88 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(testLayer)); }); + it.effect("returns the new checkout when one lands mid-refresh", () => { + const state = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const remoteEntered = yield* Deferred.make(); + const releaseRemote = yield* Deferred.make(); + // Armed only around the refresh under test, so neither the priming read + // nor the follow-up refresh that the checkout change kicks off blocks. + const gate = { armed: false }; + const testLayer = VcsStatusBroadcaster.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(makeBackgroundPolicyLayer(() => true)), + Layer.provide( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + localStatus: () => + Effect.sync(() => { + state.localStatusCalls += 1; + return state.currentLocalStatus; + }), + remoteStatus: () => + Effect.suspend(() => { + state.remoteStatusCalls += 1; + if (!gate.armed) { + return Effect.succeed(state.currentRemoteStatus); + } + gate.armed = false; + return Deferred.succeed(remoteEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseRemote)), + Effect.as(state.currentRemoteStatus), + ); + }), + invalidateLocalStatus: () => + Effect.sync(() => { + state.localInvalidationCalls += 1; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + state.remoteInvalidationCalls += 1; + }), + invalidateStatus: () => + Effect.sync(() => { + state.localInvalidationCalls += 1; + state.remoteInvalidationCalls += 1; + }), + }), + ), + ); + + return yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + + gate.armed = true; + const refreshFiber = yield* Effect.forkChild(broadcaster.refreshStatus("/repo"), { + startImmediately: true, + }); + yield* Deferred.await(remoteEntered); + + // A checkout lands while the slow remote read is still in flight. + state.currentLocalStatus = { + ...baseLocalStatus, + refName: "feature/checked-out-mid-refresh", + }; + yield* broadcaster.refreshLocalStatus("/repo"); + + yield* Deferred.succeed(releaseRemote, undefined); + const refreshed = yield* Fiber.join(refreshFiber); + + // The refresh must not hand back the branch that was checked out when + // it started; its own remote result was discarded as superseded. + assert.equal(refreshed.refName, "feature/checked-out-mid-refresh"); + }).pipe(Effect.provide(testLayer)); + }); + }); + it.effect("refreshes only the cached local snapshot when the checkout is unchanged", () => { const state = { currentLocalStatus: baseLocalStatus, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 9fb4f28b25..c26f05c603 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -482,7 +482,16 @@ export const make = Effect.gen(function* () { }), ); const remote = yield* refreshRemoteStatus(cwd, { invalidate: false }); - return mergeGitStatusParts(local, remote); + // A checkout can land between the two reads. refreshRemoteStatus discards + // a superseded remote result, which would leave `local` describing the old + // branch — returning that pair would hand the caller a status the cache + // itself no longer agrees with. Prefer the cache's halves, which the + // concurrent refresh has already reconciled for the new branch. + const cached = yield* getCachedStatus(cwd); + return mergeGitStatusParts( + cached?.local?.value ?? local, + cached?.remote ? cached.remote.value : remote, + ); }); const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn( diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 76336f1ef1..86ced8deaf 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -10,7 +10,6 @@ import { resolveEffectiveEnvMode, resolveEnvModeLabel, resolveBranchTriggerLabel, - resolveBranchToolbarPrBranch, resolveBranchToolbarValue, resolveLockedWorkspaceLabel, resolveLocalCheckoutBranchMismatch, @@ -270,35 +269,6 @@ describe("resolveBranchTriggerLabel", () => { }); }); -describe("resolveBranchToolbarPrBranch", () => { - it("uses the explicit thread branch when it matches the displayed branch", () => { - expect( - resolveBranchToolbarPrBranch({ - activeThreadBranch: "feature/current", - resolvedActiveBranch: "feature/current", - }), - ).toBe("feature/current"); - }); - - it("hides PR state while an optimistic branch switch is in flight", () => { - expect( - resolveBranchToolbarPrBranch({ - activeThreadBranch: "feature/current", - resolvedActiveBranch: "feature/next", - }), - ).toBeNull(); - }); - - it("does not infer PR state without an explicit thread branch", () => { - expect( - resolveBranchToolbarPrBranch({ - activeThreadBranch: null, - resolvedActiveBranch: "feature/current", - }), - ).toBeNull(); - }); -}); - describe("resolveLocalCheckoutBranchMismatch", () => { it("detects when a local thread is associated with a different branch than the checkout", () => { expect( diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index d9737f17a3..dd3300c0cb 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -183,13 +183,6 @@ export function resolveBranchTriggerLabel(input: { return resolvedActiveBranch; } -export function resolveBranchToolbarPrBranch(input: { - activeThreadBranch: string | null; - resolvedActiveBranch: string | null; -}): string | null { - return input.activeThreadBranch === input.resolvedActiveBranch ? input.activeThreadBranch : null; -} - export function resolveLocalCheckoutBranchMismatch(input: { effectiveEnvMode: EnvMode; activeWorktreePath: string | null; diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 3b49e6f6bf..8c3eb8669f 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -37,7 +37,6 @@ import { getSourceControlPresentation } from "../sourceControlPresentation"; import { deriveLocalBranchNameFromRemoteRef, resolveBranchTriggerLabel, - resolveBranchToolbarPrBranch, resolveBranchSelectionTarget, resolveBranchToolbarValue, resolveDraftEnvModeAfterBranchChange, @@ -47,7 +46,7 @@ import { import { ChangeRequestStatusIcon, prStatusIndicator, - resolveThreadPr, + selectBranchPr, } from "./ThreadStatusIndicators"; import { Button } from "./ui/button"; import { Switch } from "./ui/switch"; @@ -619,16 +618,11 @@ export function BranchToolbarBranchSelector({ }) : null, ); - const branchPr = - resolveThreadPr({ - threadBranch: resolveBranchToolbarPrBranch({ - activeThreadBranch, - resolvedActiveBranch, - }), - gitStatus: branchStatusQuery.data ?? null, - }) ?? - branchPrQuery.data?.pr ?? - null; + const branchPr = selectBranchPr({ + branch: branchPrLookupBranch, + gitStatus: branchStatusQuery.data ?? null, + branchPr: branchPrQuery.data?.pr, + }); const branchPrStatus = prStatusIndicator(branchPr, branchStatusQuery.data?.sourceControlProvider); // Action-oriented tooltip (the pill opens the PR), distinct from the sidebar's // state-description tooltip. diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 5d4b7dd116..3451b841d0 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -49,7 +49,6 @@ import { resolveQuickAction, resolveThreadBranchUpdate, } from "./GitActionsControl.logic"; -import { useThreadPr } from "./ThreadStatusIndicators"; import { AnimatedHeight } from "./AnimatedHeight"; import { Button } from "~/components/ui/button"; import { Checkbox } from "~/components/ui/checkbox"; @@ -1100,22 +1099,13 @@ export default function GitActionsControl({ // Default to true while loading so we don't flash init controls. const isRepo = gitStatus?.isRepo ?? true; const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false; - const activeThreadBranchPr = useThreadPr({ - environmentId: activeEnvironmentId, - cwd: gitCwd, - threadBranch: activeServerThread?.branch ?? null, - gitStatus, - }); - // Scope PR-driven actions to the thread's recorded branch: when the - // checkout has moved under a thread, "View PR" must open the thread's PR, - // not whatever the current checkout has. Non-thread contexts (project view, - // new composer) keep the checkout's PR. - const gitStatusForActions = useMemo(() => { - if (!gitStatus || activeServerThread?.branch == null) { - return gitStatus; - } - return { ...gitStatus, pr: activeThreadBranchPr }; - }, [activeServerThread?.branch, activeThreadBranchPr, gitStatus]); + // Deliberately the checkout's status, not the active thread's branch: every + // action here (commit, push, create) runs against whatever is checked out at + // `gitCwd`, so gating them on another branch's PR would offer "Create PR" + // for a branch that already has one — or hide it for one that doesn't. + // Thread-scoped PR state lives on the sidebar badge and the composer pill, + // which are branch-keyed; the branch-mismatch banner explains the split. + const gitStatusForActions = gitStatus; const allFiles = gitStatusForActions?.workingTree.files ?? []; const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path)); diff --git a/apps/web/src/components/ThreadStatusIndicators.test.ts b/apps/web/src/components/ThreadStatusIndicators.test.ts index 3eb8e4f710..e5b3577141 100644 --- a/apps/web/src/components/ThreadStatusIndicators.test.ts +++ b/apps/web/src/components/ThreadStatusIndicators.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { prStatusIndicator, - resolveThreadPr, + selectBranchPr, settledPrHoverColorClass, } from "./ThreadStatusIndicators"; @@ -30,43 +30,54 @@ function status(overrides: Partial = {}): VcsStatusResult { }; } -describe("resolveThreadPr", () => { - it("keeps local-checkout PR indicators scoped to the stored thread branch", () => { - expect( - resolveThreadPr({ - threadBranch: "feature/other", - gitStatus: status(), - }), - ).toBeNull(); - }); +const otherBranchPr = { + number: 7, + title: "Branch-keyed PR", + url: "https://github.com/pingdotgg/t3code/pull/7", + baseRef: "main", + headRef: "feature/other", + state: "open", +} as const; - it("hides PR indicators when a dedicated worktree has switched away from the thread branch", () => { - expect( - resolveThreadPr({ - threadBranch: "stack/base", - gitStatus: status(), - }), - ).toBeNull(); - }); - - it("hides PR indicators when thread branch metadata is missing", () => { - expect( - resolveThreadPr({ - threadBranch: null, - gitStatus: status(), - }), - ).toBeNull(); - }); - - it("shows the PR when the live checkout matches the stored thread branch", () => { +describe("selectBranchPr", () => { + it("shows the PR when the live checkout matches the requested branch", () => { const gitStatus = status(); + expect(selectBranchPr({ branch: "feature/current", gitStatus, branchPr: undefined })).toBe( + gitStatus.pr, + ); + }); + + it("falls back to the branch-keyed lookup when the checkout moved elsewhere", () => { expect( - resolveThreadPr({ - threadBranch: "feature/current", - gitStatus, + selectBranchPr({ + branch: "feature/other", + gitStatus: status(), + branchPr: otherBranchPr, }), - ).toBe(gitStatus.pr); + ).toBe(otherBranchPr); + }); + + it("treats an empty PR on the matching checkout as authoritative", () => { + // Regression: a warm branch-keyed result must not resurrect a badge the + // status stream just cleared (e.g. immediately after a merge). + expect( + selectBranchPr({ + branch: "feature/current", + gitStatus: status({ pr: null }), + branchPr: otherBranchPr, + }), + ).toBeNull(); + }); + + it("returns nothing when the branch is unknown and no lookup resolved", () => { + expect(selectBranchPr({ branch: null, gitStatus: status(), branchPr: undefined })).toBeNull(); + }); + + it("returns nothing while the branch-keyed lookup is unresolved", () => { + expect( + selectBranchPr({ branch: "feature/other", gitStatus: status(), branchPr: undefined }), + ).toBeNull(); }); }); diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 4ee8edf292..b468d7b5b5 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -110,20 +110,33 @@ export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator } ); } -export function resolveThreadPr(input: { - threadBranch: string | null; +/** + * True when the streamed status describes the thread's own branch, and so is + * authoritative about that branch's PR — including when it reports none. + */ +function statusCoversBranch( + gitStatus: VcsStatusResult | null, + threadBranch: string | null, +): gitStatus is VcsStatusResult { + return gitStatus !== null && threadBranch !== null && gitStatus.refName === threadBranch; +} + +/** + * Pick the PR for `branch` from the two available sources. The streamed + * status wins whenever it describes that branch — including when it reports + * no PR, which is why this short-circuits instead of falling through with + * `??`: a warm branch-keyed result must never resurrect a badge the + * authoritative status just cleared (e.g. right after a merge). + */ +export function selectBranchPr(input: { + branch: string | null; gitStatus: VcsStatusResult | null; + branchPr: ThreadPr | null | undefined; }): ThreadPr | null { - const { threadBranch, gitStatus } = input; - if (gitStatus === null) { - return null; + if (statusCoversBranch(input.gitStatus, input.branch)) { + return input.gitStatus.pr ?? null; } - - if (threadBranch === null || gitStatus.refName !== threadBranch) { - return null; - } - - return gitStatus.pr ?? null; + return input.branchPr ?? null; } /** @@ -146,11 +159,11 @@ export function useThreadPr(input: { }) : null, ); - return ( - resolveThreadPr({ threadBranch: input.threadBranch, gitStatus: input.gitStatus }) ?? - branchPr.data?.pr ?? - null - ); + return selectBranchPr({ + branch: input.threadBranch, + gitStatus: input.gitStatus, + branchPr: branchPr.data?.pr, + }); } export function terminalStatusFromRunningIds(