Skip to content

Commit c0b9cee

Browse files
Address review: don't reuse a sticky PR fallback across a retargeted upstream
The last-known-PR fallback (added to avoid blanking the badge on a transient gh failure) is keyed by branch only, so a retarget to a different upstream/fork mid-failure could surface a PR that no longer matches the current head. Track the upstream the fallback was resolved against and withhold it when both the cached and current upstreamRef are known and differ, while still tolerating an upstream merely appearing or disappearing. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 0cb345d commit c0b9cee

2 files changed

Lines changed: 217 additions & 16 deletions

File tree

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1379,6 +1379,141 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
13791379
}),
13801380
);
13811381

1382+
it.effect(
1383+
"status does not reuse a stale PR after the branch is retargeted to a different upstream",
1384+
() =>
1385+
Effect.gen(function* () {
1386+
const repoDir = yield* makeTempDir("t3code-git-manager-");
1387+
yield* initRepo(repoDir);
1388+
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-retarget"]);
1389+
1390+
const originRemote = yield* createBareRemote();
1391+
yield* runGit(repoDir, ["remote", "add", "origin", originRemote]);
1392+
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-retarget"]);
1393+
1394+
const existingPr = {
1395+
number: 214,
1396+
title: "Sticky PR",
1397+
url: "https://github.com/pingdotgg/codething-mvp/pull/214",
1398+
baseRefName: "main",
1399+
headRefName: "feature/pr-retarget",
1400+
};
1401+
const { manager } = yield* makeManager({
1402+
ghScenario: {
1403+
// @effect-diagnostics-next-line preferSchemaOverJson:off
1404+
prListSequence: [JSON.stringify([existingPr])],
1405+
failWith: new GitHubCli.GitHubCliUnavailableError({
1406+
command: "gh",
1407+
cwd: repoDir,
1408+
cause: new Error("rate limited"),
1409+
}),
1410+
failAfterCalls: 1,
1411+
},
1412+
});
1413+
1414+
const first = yield* manager.status({ cwd: repoDir });
1415+
expect(first.pr?.number).toBe(214);
1416+
1417+
// Retarget the branch to a different remote/upstream (e.g. the PR was
1418+
// reopened against a fork). The previously cached PR belonged to the
1419+
// old upstream and must not be shown against the new one.
1420+
const forkRemote = yield* createBareRemote();
1421+
yield* runGit(repoDir, ["remote", "add", "fork", forkRemote]);
1422+
yield* runGit(repoDir, ["push", "fork", "feature/pr-retarget"]);
1423+
yield* runGit(repoDir, [
1424+
"branch",
1425+
"--set-upstream-to=fork/feature/pr-retarget",
1426+
"feature/pr-retarget",
1427+
]);
1428+
1429+
yield* manager.invalidateStatus(repoDir);
1430+
const second = yield* manager.status({ cwd: repoDir });
1431+
expect(second.pr).toBeNull();
1432+
}),
1433+
);
1434+
1435+
it.effect("status keeps the last known PR when the branch gains its first upstream", () =>
1436+
Effect.gen(function* () {
1437+
const repoDir = yield* makeTempDir("t3code-git-manager-");
1438+
yield* initRepo(repoDir);
1439+
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-sticky-first-push"]);
1440+
const remoteDir = yield* createBareRemote();
1441+
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
1442+
1443+
const existingPr = {
1444+
number: 215,
1445+
title: "Sticky first-push PR",
1446+
url: "https://github.com/pingdotgg/codething-mvp/pull/215",
1447+
baseRefName: "main",
1448+
headRefName: "feature/pr-sticky-first-push",
1449+
};
1450+
const { manager } = yield* makeManager({
1451+
ghScenario: {
1452+
// @effect-diagnostics-next-line preferSchemaOverJson:off
1453+
prListSequence: [JSON.stringify([existingPr])],
1454+
failWith: new GitHubCli.GitHubCliUnavailableError({
1455+
command: "gh",
1456+
cwd: repoDir,
1457+
cause: new Error("rate limited"),
1458+
}),
1459+
failAfterCalls: 1,
1460+
},
1461+
});
1462+
1463+
const first = yield* manager.status({ cwd: repoDir });
1464+
expect(first.pr?.number).toBe(215);
1465+
1466+
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-sticky-first-push"]);
1467+
yield* manager.invalidateStatus(repoDir);
1468+
1469+
const second = yield* manager.status({ cwd: repoDir });
1470+
expect(second.pr?.number).toBe(215);
1471+
}),
1472+
);
1473+
1474+
it.effect("status drops the last known PR when the tracked remote is repointed", () =>
1475+
Effect.gen(function* () {
1476+
const repoDir = yield* makeTempDir("t3code-git-manager-");
1477+
yield* initRepo(repoDir);
1478+
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-repointed"]);
1479+
const originalRemoteDir = yield* createBareRemote();
1480+
yield* runGit(repoDir, ["remote", "add", "origin", originalRemoteDir]);
1481+
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-repointed"]);
1482+
1483+
const existingPr = {
1484+
number: 216,
1485+
title: "Old remote PR",
1486+
url: "https://github.com/pingdotgg/codething-mvp/pull/216",
1487+
baseRefName: "main",
1488+
headRefName: "feature/pr-repointed",
1489+
};
1490+
const { manager } = yield* makeManager({
1491+
ghScenario: {
1492+
// @effect-diagnostics-next-line preferSchemaOverJson:off
1493+
prListSequence: [JSON.stringify([existingPr])],
1494+
failWith: new GitHubCli.GitHubCliUnavailableError({
1495+
command: "gh",
1496+
cwd: repoDir,
1497+
cause: new Error("rate limited"),
1498+
}),
1499+
failAfterCalls: 1,
1500+
},
1501+
});
1502+
1503+
const first = yield* manager.status({ cwd: repoDir });
1504+
expect(first.pr?.number).toBe(216);
1505+
1506+
const replacementRemoteDir = yield* createBareRemote();
1507+
yield* runGit(repoDir, ["remote", "add", "replacement", replacementRemoteDir]);
1508+
yield* runGit(repoDir, ["push", "replacement", "feature/pr-repointed"]);
1509+
yield* runGit(repoDir, ["remote", "set-url", "origin", replacementRemoteDir]);
1510+
yield* manager.invalidateStatus(repoDir);
1511+
1512+
const second = yield* manager.status({ cwd: repoDir });
1513+
expect(second.pr).toBeNull();
1514+
}),
1515+
);
1516+
13821517
it.effect("creates a commit when working tree is dirty", () =>
13831518
Effect.gen(function* () {
13841519
const repoDir = yield* makeTempDir("t3code-git-manager-");

‎apps/server/src/git/GitManager.ts‎

Lines changed: 82 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
import {
3333
detectSourceControlProviderFromGitRemoteUrl,
3434
mergeGitStatusParts,
35+
normalizeGitRemoteUrl,
3536
resolveAutoFeatureBranchName,
3637
sanitizeBranchFragment,
3738
sanitizeFeatureBranchName,
@@ -145,6 +146,7 @@ interface BranchHeadContext {
145146
headSelectors: ReadonlyArray<string>;
146147
preferredHeadSelector: string;
147148
remoteName: string | null;
149+
headRemoteUrlKey: string | null;
148150
headRepositoryNameWithOwner: string | null;
149151
headRepositoryOwnerLogin: string | null;
150152
isCrossRepository: boolean;
@@ -792,10 +794,17 @@ export const make = Effect.gen(function* () {
792794
const prLookupCache = yield* Cache.makeWith(
793795
(key: string) => {
794796
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
795-
return findLatestPr(cwd, {
797+
const details = {
796798
branch,
797799
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
798-
});
800+
};
801+
return resolveBranchHeadContext(cwd, details).pipe(
802+
Effect.flatMap((headContext) =>
803+
findLatestPrForHeadContext(cwd, headContext).pipe(
804+
Effect.map((latest) => ({ latest, headContext })),
805+
),
806+
),
807+
);
799808
},
800809
{
801810
capacity: PR_LOOKUP_CACHE_CAPACITY,
@@ -804,9 +813,17 @@ export const make = Effect.gen(function* () {
804813
);
805814
// A transient lookup failure (rate limit, network blip) must not clear an
806815
// already-known PR badge, so the last successful answer per branch sticks
807-
// around as the fallback.
808-
const lastKnownPrByBranchKey = new Map<string, ReturnType<typeof toStatusPr> | null>();
809-
const rememberLastKnownPr = (branchKey: string, pr: ReturnType<typeof toStatusPr> | null) => {
816+
// around as the fallback. Keep the resolved head context with it so a
817+
// branch retargeted to another remote/fork cannot inherit the old badge.
818+
interface LastKnownPr {
819+
readonly pr: ReturnType<typeof toStatusPr> | null;
820+
readonly upstreamRef: string | null;
821+
readonly headBranch: string;
822+
readonly remoteName: string | null;
823+
readonly headRemoteUrlKey: string | null;
824+
}
825+
const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();
826+
const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {
810827
if (
811828
!lastKnownPrByBranchKey.has(branchKey) &&
812829
lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY
@@ -816,7 +833,32 @@ export const make = Effect.gen(function* () {
816833
lastKnownPrByBranchKey.delete(oldestKey);
817834
}
818835
}
819-
lastKnownPrByBranchKey.set(branchKey, pr);
836+
lastKnownPrByBranchKey.set(branchKey, entry);
837+
};
838+
const resolveLastKnownPr = (
839+
branchKey: string,
840+
current: Pick<LastKnownPr, "upstreamRef" | "headBranch" | "remoteName" | "headRemoteUrlKey">,
841+
): ReturnType<typeof toStatusPr> | null => {
842+
const lastKnown = lastKnownPrByBranchKey.get(branchKey);
843+
if (!lastKnown) return null;
844+
if (lastKnown.headBranch !== current.headBranch) {
845+
return null;
846+
}
847+
848+
// The normalized URL catches both remote-alias changes and an existing
849+
// alias being repointed. It also lets an upstream appear after `push -u`
850+
// without invalidating the fallback when it still targets the same repo.
851+
if (lastKnown.headRemoteUrlKey !== null || current.headRemoteUrlKey !== null) {
852+
return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;
853+
}
854+
855+
// If neither remote URL is available, fall back to the remote identity
856+
// encoded by tracked branches. A null-to-non-null transition is allowed
857+
// because that is the expected first-push case.
858+
if (lastKnown.upstreamRef !== null && current.upstreamRef !== null) {
859+
return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;
860+
}
861+
return lastKnown.pr;
820862
};
821863
const lookupStatusPr = Effect.fn("lookupStatusPr")(function* (
822864
cwd: string,
@@ -826,14 +868,27 @@ export const make = Effect.gen(function* () {
826868
// `push -u`) must not orphan the fallback value for the same branch.
827869
const branchKey = `${cwd}\u0000${details.branch}`;
828870
return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(
829-
Effect.map((latest) => {
830-
if (!latest) return null;
871+
Effect.map(({ latest, headContext }) => {
872+
if (!latest) return { pr: null, headContext };
831873
// On the default branch, only surface open PRs.
832874
// Merged/closed matches are usually reverse-merge history, not the thread's PR context.
833-
if (details.isDefaultBranch && latest.state !== "open") return null;
834-
return toStatusPr(latest);
875+
if (details.isDefaultBranch && latest.state !== "open") {
876+
return { pr: null, headContext };
877+
}
878+
return { pr: toStatusPr(latest), headContext };
835879
}),
836-
Effect.tap((pr) => Effect.sync(() => rememberLastKnownPr(branchKey, pr))),
880+
Effect.tap(({ pr, headContext }) =>
881+
Effect.sync(() =>
882+
rememberLastKnownPr(branchKey, {
883+
pr,
884+
upstreamRef: details.upstreamRef,
885+
headBranch: headContext.headBranch,
886+
remoteName: headContext.remoteName,
887+
headRemoteUrlKey: headContext.headRemoteUrlKey,
888+
}),
889+
),
890+
),
891+
Effect.map(({ pr }) => pr),
837892
Effect.catch((error) =>
838893
Effect.logWarning("PR lookup failed; keeping last known PR state.").pipe(
839894
Effect.annotateLogs({
@@ -844,7 +899,15 @@ export const make = Effect.gen(function* () {
844899
? String(error._tag)
845900
: typeof error,
846901
}),
847-
Effect.as(lastKnownPrByBranchKey.get(branchKey) ?? null),
902+
Effect.andThen(resolveBranchHeadContext(cwd, details)),
903+
Effect.map((headContext) =>
904+
resolveLastKnownPr(branchKey, {
905+
upstreamRef: details.upstreamRef,
906+
headBranch: headContext.headBranch,
907+
remoteName: headContext.remoteName,
908+
headRemoteUrlKey: headContext.headRemoteUrlKey,
909+
}),
910+
),
848911
),
849912
),
850913
);
@@ -910,6 +973,7 @@ export const make = Effect.gen(function* () {
910973
) {
911974
if (!remoteName) {
912975
return {
976+
remoteUrlKey: null,
913977
repositoryNameWithOwner: null,
914978
ownerLogin: null,
915979
};
@@ -918,6 +982,7 @@ export const make = Effect.gen(function* () {
918982
const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);
919983
const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);
920984
return {
985+
remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,
921986
repositoryNameWithOwner,
922987
ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),
923988
};
@@ -988,6 +1053,9 @@ export const make = Effect.gen(function* () {
9881053
preferredHeadSelector:
9891054
ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,
9901055
remoteName,
1056+
headRemoteUrlKey:
1057+
remoteRepository.remoteUrlKey ??
1058+
(remoteName === null ? originRepository.remoteUrlKey : null),
9911059
headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,
9921060
headRepositoryOwnerLogin: remoteRepository.ownerLogin,
9931061
isCrossRepository,
@@ -1033,11 +1101,10 @@ export const make = Effect.gen(function* () {
10331101
return null;
10341102
});
10351103

1036-
const findLatestPr = Effect.fn("findLatestPr")(function* (
1104+
const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* (
10371105
cwd: string,
1038-
details: { branch: string; upstreamRef: string | null },
1106+
headContext: BranchHeadContext,
10391107
) {
1040-
const headContext = yield* resolveBranchHeadContext(cwd, details);
10411108
const parsedByNumber = new Map<number, PullRequestInfo>();
10421109

10431110
for (const headSelector of headContext.headSelectors) {
@@ -1064,7 +1131,6 @@ export const make = Effect.gen(function* () {
10641131
}
10651132
return parsed[0] ?? null;
10661133
});
1067-
10681134
const buildCompletionToast = Effect.fn("buildCompletionToast")(function* (
10691135
cwd: string,
10701136
result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,

0 commit comments

Comments
 (0)