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 21, 23:30 UTC
fix(git): stop new threads inheriting historical branch PRs (#34218)
Co-authored-by: Vladislav Nikonorov <vladislav@nikonorov.dev>
Julius Marminge committed
Nov 11, 2026 at 09:35 UTC
7e565c510d6dfaef2e1fd97bf9d89a97ce9cece7
8 files changed
+227
-15
apps/server/src/git/GitManager.test.ts
+3
@@ -5002,6 +5002,9 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5002
expect(NodeFS.readFileSync(NodePath.join(repoDir, "untracked.txt"), "utf8")).toBe(
5003
"keep me\n",
5004
);
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");
5008
}),
5009
);
5010
apps/server/src/git/GitManager.ts
+39
-1
@@ -140,6 +140,12 @@ export class GitManager extends Context.Service<
140
input: { readonly cwd: string; readonly branch: string },
141
options?: { readonly refresh?: boolean; readonly freshGitState?: boolean },
142
) => 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>;
149
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
150
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
151
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -2755,6 +2761,9 @@ export const make = Effect.gen(function* () {
2761
repositoryKey: pullRequestRepositoryKey(latest.url),
2762
};
2763
});
2764
+
2765
+ const checkedOutPullRequestKey = (branch: string) => `branch.${branch}.t3-pull-request`;
2766
+
2767
const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn(
2768
"branchPullRequest",
2769
)(function* ({ cwd, branch }, options) {
@@ -2799,6 +2808,16 @@ export const make = Effect.gen(function* () {
2808
}
2809
return confirmed;
2810
});
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
+
2821
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
2822
"invalidateLocalStatus",
2823
)(function* (cwd) {
@@ -3133,7 +3152,25 @@ export const make = Effect.gen(function* () {
3152
worktreePath: worktree.worktree.path,
3153
isOnPullRequestHead: true,
3154
};
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
+ );
3174
}, asUserAction);
3175
3176
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
@@ -3392,6 +3429,7 @@ export const make = Effect.gen(function* () {
3429
remoteStatus,
3430
status,
3431
branchPullRequest,
3432
+ checkedOutPullRequest,
3433
invalidateLocalStatus,
3434
invalidateRemoteStatus,
3435
invalidateStatus,
apps/server/src/orchestration-v2/ProjectionStore.ts
+2
@@ -1161,6 +1161,7 @@ const PullRequestThread = OrchestrationV2AppThreadJsonSchema.mapFields(
1161
id,
1162
projectId,
1163
lineage,
1164
+ createdAt,
1165
branch,
1166
worktreePath,
1167
archivedAt,
@@ -1173,6 +1174,7 @@ const PullRequestThread = OrchestrationV2AppThreadJsonSchema.mapFields(
1174
id,
1175
projectId,
1176
lineage,
1177
+ createdAt,
1178
branch,
1179
worktreePath,
1180
archivedAt,
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+129
@@ -556,6 +556,132 @@ describe("ThreadPullRequestServiceV2 reads", () => {
556
),
557
);
558
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: "git@github.com: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
+
685
it.effect.each([
686
{ state: "closed", sameBranch: false },
687
{ state: "merged", sameBranch: false },
@@ -590,6 +716,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
716
const activation = yield* Deferred.make<void>();
717
const sweepStarted = yield* Deferred.make<void>();
718
const commands: Array<OrchestrationV2ServerCommand> = [];
719
+ let snapshotThread: unknown;
720
const dependencies = Layer.mergeAll(
721
Layer.mock(Orchestrator.OrchestratorV2)({
722
streamDomainEvents: Stream.never,
@@ -617,6 +744,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
744
])
745
yield* sql.unsafe(`DROP TABLE ${table}`);
746
const snapshot = yield* store.getPullRequestSnapshot(options);
747
+ snapshotThread = snapshot.threads[0];
748
yield* Deferred.succeed(sweepStarted, undefined);
749
return snapshot;
750
}).pipe(
@@ -681,6 +809,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
809
yield* service.drain;
810
}).pipe(Effect.provide(dependencies));
811
812
+ expect(snapshotThread).toHaveProperty("createdAt", NOW);
813
if (sameBranch) {
814
expect(commands).toEqual([]);
815
} else {
apps/server/src/orchestration-v2/ThreadPullRequestService.ts
+29
-1
@@ -3,6 +3,7 @@ import {
3
type OrchestrationProjectShell,
4
type OrchestrationV2DomainEvent,
5
type OrchestrationV2ThreadShell,
6
+ type PullRequestSummary,
7
type ThreadId,
8
type ThreadLinkedPullRequest,
9
} from "@t3tools/contracts";
@@ -10,6 +11,7 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
11
import * as Cause from "effect/Cause";
12
import * as Context from "effect/Context";
13
import * as SecureRandom from "effect/crypto/SecureRandom";
14
+import * as DateTime from "effect/DateTime";
15
import * as Effect from "effect/Effect";
16
import * as FileSystem from "effect/FileSystem";
17
import * as Option from "effect/Option";
@@ -49,6 +51,19 @@ function samePullRequest(
51
);
52
}
53
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
+
67
function pullRequestMatchesProject(
68
pullRequest: GitManager.GitBranchPullRequest,
69
project: OrchestrationProjectShell,
@@ -209,9 +224,22 @@ export const make = Effect.gen(function* () {
224
}
225
: null;
226
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
+
239
const plans = yield* Effect.forEach(group, (thread) =>
240
Effect.gen(function* () {
214
- let branchPullRequest = detectedReference;
241
+ let branchPullRequest =
242
+ dropsHistorical && isHistoricalFor(thread) ? null : detectedReference;
243
if (
244
branchPullRequest === null &&
245
thread.branch !== null &&
apps/web/src/components/BranchToolbarBranchSelector.tsx
+5
-4
@@ -59,6 +59,7 @@ import {
59
import {
60
ThreadPullRequestBadgeControl,
61
prStatusIndicator,
62
+ resolveDisplayedThreadPr,
63
resolveThreadPullRequestBadge,
64
useLinkedThreadPullRequest,
65
} from "./ThreadStatusIndicators";
@@ -595,10 +596,10 @@ export function BranchToolbarBranchSelector({
596
activeThreadBranch,
597
resolvedActiveBranch,
598
});
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
+ });
603
const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId);
604
const linkedStatus = useLinkedThreadPullRequest(
605
environmentId,
apps/web/src/components/ThreadStatusIndicators.test.ts
+16
@@ -103,6 +103,22 @@ describe("resolveDisplayedThreadPr", () => {
103
expect(resolveDisplayedThreadPrProvider(input)).toEqual(provider);
104
});
105
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
+
122
it("never attaches a PR reported by main to the feature thread", () => {
123
const mainPr = {
124
number: 99,
apps/web/src/components/ThreadStatusIndicators.tsx
+4
-9
@@ -467,7 +467,7 @@ export function resolveDisplayedThreadPr(input: {
467
threadBranch !== null &&
468
gitStatus !== null &&
469
gitStatus.refName === threadBranch &&
470
- gitStatus.pr != null
470
+ gitStatus.pr?.state === "open"
471
) {
472
return gitStatus.pr;
473
}
@@ -481,17 +481,12 @@ export function resolveDisplayedThreadPrProvider(input: {
481
linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
482
linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
483
}): VcsStatusResult["sourceControlProvider"] | undefined {
484
- const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
484
+ const { gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
485
if (linkedPullRequest != null) {
486
return linkedPullRequestStatus?.sourceControlProvider;
487
}
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;
490
}
491
492
return undefined;