Skip to content

Commit 7e565c5

Browse files
fix(git): stop new threads inheriting historical branch PRs (pingdotgg#34218)
Co-authored-by: Vladislav Nikonorov <[email protected]>
1 parent a625e0b commit 7e565c5

8 files changed

Lines changed: 227 additions & 15 deletions

File tree

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5002,6 +5002,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
50025002
expect(NodeFS.readFileSync(NodePath.join(repoDir, "untracked.txt"), "utf8")).toBe(
50035003
"keep me\n",
50045004
);
5005+
expect(
5006+
(yield* runGit(repoDir, ["config", "branch.feature/pr-safe.t3-pull-request"])).stdout,
5007+
).toBe("https://github.com/pingdotgg/codething-mvp/pull/91\n");
50055008
}),
50065009
);
50075010

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

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,12 @@ export class GitManager extends Context.Service<
140140
input: { readonly cwd: string; readonly branch: string },
141141
options?: { readonly refresh?: boolean; readonly freshGitState?: boolean },
142142
) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
143+
/** Whether T3 checked this pull request out onto the branch, which ties it to later threads. */
144+
readonly checkedOutPullRequest: (input: {
145+
readonly cwd: string;
146+
readonly branch: string;
147+
readonly url: string;
148+
}) => Effect.Effect<boolean>;
143149
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
144150
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
145151
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -2755,6 +2761,9 @@ export const make = Effect.gen(function* () {
27552761
repositoryKey: pullRequestRepositoryKey(latest.url),
27562762
};
27572763
});
2764+
2765+
const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`;
2766+
27582767
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn(
27592768
"branchPullRequest",
27602769
)(function* ({ cwd, branch }, options) {
@@ -2799,6 +2808,16 @@ export const make = Effect.gen(function* () {
27992808
}
28002809
return confirmed;
28012810
});
2811+
2812+
const checkedOutPullRequest: GitManager["Service"]["checkedOutPullRequest"] = Effect.fn(
2813+
"checkedOutPullRequest",
2814+
)(function* ({ cwd, branch, url }) {
2815+
const checkedOutUrl = yield* gitCore
2816+
.readConfigValue(cwd, checkedOutPullRequestKey(branch))
2817+
.pipe(Effect.orElseSucceed(() => null));
2818+
return checkedOutUrl === url;
2819+
});
2820+
28022821
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
28032822
"invalidateLocalStatus",
28042823
)(function* (cwd) {
@@ -3133,7 +3152,25 @@ export const make = Effect.gen(function* () {
31333152
worktreePath: worktree.worktree.path,
31343153
isOnPullRequestHead: true,
31353154
};
3136-
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
3155+
}).pipe(
3156+
Effect.tap((result) =>
3157+
gitCore
3158+
.writeConfigValue({
3159+
cwd: input.cwd,
3160+
key: checkedOutPullRequestKey(result.branch),
3161+
value: result.pullRequest.url,
3162+
})
3163+
.pipe(
3164+
Effect.catch((cause) =>
3165+
Effect.logWarning("GitManager.preparePullRequestThread could not mark the branch", {
3166+
branch: result.branch,
3167+
cause,
3168+
}),
3169+
),
3170+
),
3171+
),
3172+
Effect.ensuring(invalidateStatus(input.cwd)),
3173+
);
31373174
}, asUserAction);
31383175

31393176
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -3392,6 +3429,7 @@ export const make = Effect.gen(function* () {
33923429
remoteStatus,
33933430
status,
33943431
branchPullRequest,
3432+
checkedOutPullRequest,
33953433
invalidateLocalStatus,
33963434
invalidateRemoteStatus,
33973435
invalidateStatus,

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,6 +1161,7 @@ const PullRequestThread = OrchestrationV2AppThreadJsonSchema.mapFields(
11611161
id,
11621162
projectId,
11631163
lineage,
1164+
createdAt,
11641165
branch,
11651166
worktreePath,
11661167
archivedAt,
@@ -1173,6 +1174,7 @@ const PullRequestThread = OrchestrationV2AppThreadJsonSchema.mapFields(
11731174
id,
11741175
projectId,
11751176
lineage,
1177+
createdAt,
11761178
branch,
11771179
worktreePath,
11781180
archivedAt,

‎apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,132 @@ describe("ThreadPullRequestServiceV2 reads", () => {
556556
),
557557
);
558558

559+
it.effect.each([
560+
{ state: "open", checkedOut: false },
561+
{ state: "merged", checkedOut: false },
562+
{ state: "closed", checkedOut: false },
563+
{ state: "merged", checkedOut: true },
564+
] as const)(
565+
"associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
566+
({ state, checkedOut }) =>
567+
Effect.scoped(
568+
Effect.gen(function* () {
569+
const reference = {
570+
projectId: ProjectId.make("project-1"),
571+
repository: "acme/project",
572+
number: 42,
573+
url: "https://github.com/acme/project/pull/42",
574+
};
575+
const terminalAt = "2026-09-19T00:00:00.000Z";
576+
const detected = {
577+
number: 42,
578+
url: reference.url,
579+
title: "Previous staging work",
580+
baseRef: "main",
581+
headRef: "staging",
582+
state,
583+
updatedAt: terminalAt,
584+
closedAt: state === "closed" ? terminalAt : null,
585+
mergedAt: state === "merged" ? terminalAt : null,
586+
repositoryKey: "github.com/acme/project",
587+
};
588+
const threads = [
589+
{ ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
590+
{ ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
591+
threadShell("new"),
592+
{ ...threadShell("saved"), branchPullRequest: reference },
593+
{ ...threadShell("explicit"), linkedPullRequest: reference },
594+
].map((thread) => ({ ...thread, branch: "staging" }));
595+
const project: OrchestrationProjectShell = {
596+
id: reference.projectId,
597+
title: "Project",
598+
workspaceRoot: "/workspace/project",
599+
defaultModelSelection: null,
600+
scripts: [],
601+
createdAt: "2026-08-01T00:00:00.000Z",
602+
updatedAt: "2026-08-01T00:00:00.000Z",
603+
};
604+
const activation = yield* Deferred.make<void>();
605+
const sweepStarted = yield* Deferred.make<void>();
606+
const commands: Array<OrchestrationV2ServerCommand> = [];
607+
const dependencies = Layer.mergeAll(
608+
Layer.mock(Orchestrator.OrchestratorV2)({
609+
streamDomainEvents: Stream.never,
610+
getPullRequestSnapshot: () =>
611+
Deferred.succeed(sweepStarted, undefined).pipe(
612+
Effect.as({ snapshotSequence: 1, threads }),
613+
),
614+
dispatch: (command) =>
615+
Effect.sync(() => {
616+
commands.push(command);
617+
return { sequence: 2, storedEvents: [] };
618+
}),
619+
}),
620+
Layer.mock(ProjectStore.ProjectStoreV2)({
621+
listShells: () => Effect.succeed([project]),
622+
getShell: () => Effect.succeedSome(project),
623+
}),
624+
Layer.mock(GitManager.GitManager)({
625+
branchPullRequest: () => Effect.succeed(detected),
626+
checkedOutPullRequest: () => Effect.succeed(checkedOut),
627+
}),
628+
Layer.mock(PullRequestService.PullRequestService)({
629+
summary: () =>
630+
Effect.succeed({
631+
...detected,
632+
...reference,
633+
provider: SourceControlProviderKind.make("github"),
634+
baseBranch: detected.baseRef,
635+
headBranch: detected.headRef,
636+
}),
637+
}),
638+
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
639+
resolve: () =>
640+
Effect.succeed({
641+
canonicalKey: "github.com/acme/project",
642+
locator: {
643+
source: "git-remote" as const,
644+
remoteName: "origin",
645+
remoteUrl: "[email protected]:acme/project.git",
646+
},
647+
provider: SourceControlProviderKind.make("github"),
648+
owner: "acme",
649+
name: "project",
650+
}),
651+
}),
652+
Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
653+
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
654+
Layer.succeed(
655+
SecureRandom.SecureRandom,
656+
SecureRandom.make((size) => new Uint8Array(size).fill(1)),
657+
),
658+
FileSystem.layerNoop({}),
659+
Path.layer,
660+
);
661+
yield* Effect.gen(function* () {
662+
const service = yield* ThreadPullRequestService.make;
663+
yield* service.start();
664+
yield* Deferred.succeed(activation, undefined);
665+
yield* Deferred.await(sweepStarted);
666+
yield* service.drain;
667+
}).pipe(Effect.provide(dependencies));
668+
669+
expect(
670+
commands.map((command) => {
671+
if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
672+
expect(command).not.toHaveProperty("linkedPullRequest");
673+
return [command.threadId, command.branchPullRequest];
674+
}),
675+
).toEqual(
676+
(state === "open" || checkedOut
677+
? ["older", "same-time", "new", "explicit"]
678+
: ["older", "same-time"]
679+
).map((id) => [id, reference]),
680+
);
681+
}),
682+
),
683+
);
684+
559685
it.effect.each([
560686
{ state: "closed", sameBranch: false },
561687
{ state: "merged", sameBranch: false },
@@ -590,6 +716,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
590716
const activation = yield* Deferred.make<void>();
591717
const sweepStarted = yield* Deferred.make<void>();
592718
const commands: Array<OrchestrationV2ServerCommand> = [];
719+
let snapshotThread: unknown;
593720
const dependencies = Layer.mergeAll(
594721
Layer.mock(Orchestrator.OrchestratorV2)({
595722
streamDomainEvents: Stream.never,
@@ -617,6 +744,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
617744
])
618745
yield* sql.unsafe(`DROP TABLE ${table}`);
619746
const snapshot = yield* store.getPullRequestSnapshot(options);
747+
snapshotThread = snapshot.threads[0];
620748
yield* Deferred.succeed(sweepStarted, undefined);
621749
return snapshot;
622750
}).pipe(
@@ -681,6 +809,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
681809
yield* service.drain;
682810
}).pipe(Effect.provide(dependencies));
683811

812+
expect(snapshotThread).toHaveProperty("createdAt", NOW);
684813
if (sameBranch) {
685814
expect(commands).toEqual([]);
686815
} else {

‎apps/server/src/orchestration-v2/ThreadPullRequestService.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@ import {
33
type OrchestrationProjectShell,
44
type OrchestrationV2DomainEvent,
55
type OrchestrationV2ThreadShell,
6+
type PullRequestSummary,
67
type ThreadId,
78
type ThreadLinkedPullRequest,
89
} from "@t3tools/contracts";
910
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
1011
import * as Cause from "effect/Cause";
1112
import * as Context from "effect/Context";
1213
import * as SecureRandom from "effect/crypto/SecureRandom";
14+
import * as DateTime from "effect/DateTime";
1315
import * as Effect from "effect/Effect";
1416
import * as FileSystem from "effect/FileSystem";
1517
import * as Option from "effect/Option";
@@ -49,6 +51,19 @@ function samePullRequest(
4951
);
5052
}
5153

54+
function pullRequestPredatesThread(
55+
pullRequest: Pick<PullRequestSummary, "state" | "closedAt" | "mergedAt">,
56+
createdAt: DateTime.Utc,
57+
): boolean {
58+
const terminalAt =
59+
pullRequest.state === "merged"
60+
? pullRequest.mergedAt
61+
: pullRequest.state === "closed"
62+
? pullRequest.closedAt
63+
: null;
64+
return terminalAt != null && Date.parse(terminalAt) < DateTime.toEpochMillis(createdAt);
65+
}
66+
5267
function pullRequestMatchesProject(
5368
pullRequest: GitManager.GitBranchPullRequest,
5469
project: OrchestrationProjectShell,
@@ -209,9 +224,22 @@ export const make = Effect.gen(function* () {
209224
}
210225
: null;
211226

227+
// Only a new association is refused: a thread keeps a PR it already saved, and a PR the
228+
// user checked out stays with the threads made for it, however long ago it closed.
229+
const isHistoricalFor = (thread: (typeof group)[number]) =>
230+
detected !== null &&
231+
pullRequestPredatesThread(detected, thread.createdAt) &&
232+
!samePullRequest(thread.branchPullRequest, detectedReference);
233+
const dropsHistorical =
234+
detected !== null &&
235+
first.branch !== null &&
236+
group.some(isHistoricalFor) &&
237+
!(yield* git.checkedOutPullRequest({ cwd, branch: first.branch, url: detected.url }));
238+
212239
const plans = yield* Effect.forEach(group, (thread) =>
213240
Effect.gen(function* () {
214-
let branchPullRequest = detectedReference;
241+
let branchPullRequest =
242+
dropsHistorical && isHistoricalFor(thread) ? null : detectedReference;
215243
if (
216244
branchPullRequest === null &&
217245
thread.branch !== null &&

‎apps/web/src/components/BranchToolbarBranchSelector.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import {
5959
import {
6060
ThreadPullRequestBadgeControl,
6161
prStatusIndicator,
62+
resolveDisplayedThreadPr,
6263
resolveThreadPullRequestBadge,
6364
useLinkedThreadPullRequest,
6465
} from "./ThreadStatusIndicators";
@@ -595,10 +596,10 @@ export function BranchToolbarBranchSelector({
595596
activeThreadBranch,
596597
resolvedActiveBranch,
597598
});
598-
const branchPr =
599-
branchPrBranch !== null && branchStatusQuery.data?.refName === branchPrBranch
600-
? (branchStatusQuery.data.pr ?? null)
601-
: null;
599+
const branchPr = resolveDisplayedThreadPr({
600+
threadBranch: branchPrBranch,
601+
gitStatus: branchStatusQuery.data,
602+
});
602603
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId);
603604
const linkedStatus = useLinkedThreadPullRequest(
604605
environmentId,

‎apps/web/src/components/ThreadStatusIndicators.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,22 @@ describe("resolveDisplayedThreadPr", () => {
103103
expect(resolveDisplayedThreadPrProvider(input)).toEqual(provider);
104104
});
105105

106+
it.each(["open", "merged", "closed"] as const)(
107+
"only shows an unlinked branch PR while open (state=%s)",
108+
(state) => {
109+
const branchPr = { ...mergedPr, state };
110+
const input = {
111+
threadBranch: featureBranch,
112+
gitStatus: status({ pr: branchPr, sourceControlProvider: provider }),
113+
};
114+
115+
expect(resolveDisplayedThreadPr(input)).toEqual(state === "open" ? branchPr : null);
116+
expect(resolveDisplayedThreadPrProvider(input)).toEqual(
117+
state === "open" ? provider : undefined,
118+
);
119+
},
120+
);
121+
106122
it("never attaches a PR reported by main to the feature thread", () => {
107123
const mainPr = {
108124
number: 99,

‎apps/web/src/components/ThreadStatusIndicators.tsx‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ export function resolveDisplayedThreadPr(input: {
467467
threadBranch !== null &&
468468
gitStatus !== null &&
469469
gitStatus.refName === threadBranch &&
470-
gitStatus.pr != null
470+
gitStatus.pr?.state === "open"
471471
) {
472472
return gitStatus.pr;
473473
}
@@ -481,17 +481,12 @@ export function resolveDisplayedThreadPrProvider(input: {
481481
linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
482482
linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
483483
}): VcsStatusResult["sourceControlProvider"] | undefined {
484-
const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
484+
const { gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
485485
if (linkedPullRequest != null) {
486486
return linkedPullRequestStatus?.sourceControlProvider;
487487
}
488-
if (
489-
threadBranch !== null &&
490-
gitStatus !== null &&
491-
gitStatus.refName === threadBranch &&
492-
gitStatus.pr != null
493-
) {
494-
return gitStatus.sourceControlProvider;
488+
if (resolveDisplayedThreadPr(input) !== null) {
489+
return gitStatus?.sourceControlProvider;
495490
}
496491

497492
return undefined;

0 commit comments

Comments
 (0)