@devries-cameron20 / t3code Mirror · read-only / commits / 14978e35a5
Fork 0

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, 18:30 UTC

fix(server): PR worktrees keep local commits on an existing branch (#24674)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Victor committed Nov 12, 2026 at 16:49 UTC 14978e35a57b47c86eade9a2b3efa313396f0f57
2 files changed +321 -14
apps/server/src/git/GitManager.test.ts
+199
@@ -21,6 +21,7 @@ import * as Result from "effect/Result";
21 import * as Scope from "effect/Scope";
22 import * as Stream from "effect/Stream";
23 import * as TestClock from "effect/testing/TestClock";
24 +import * as HostProcess from "@t3tools/shared/HostProcess";
25 import { ChildProcessSpawner } from "effect/process";
26 import { expect } from "vite-plus/test";
27 import type {
@@ -5408,6 +5409,204 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5409 }),
5410 );
5411
5412 + it.effect.each([
5413 + { localBranch: "ahead", expectedHead: "local", isOnPullRequestHead: false },
5414 + { localBranch: "behind", expectedHead: "pull request", isOnPullRequestHead: true },
5415 + { localBranch: "rewritten", expectedHead: "pull request", isOnPullRequestHead: true },
5416 + { localBranch: "rewritten-fetched", expectedHead: "pull request", isOnPullRequestHead: true },
5417 + { localBranch: "wrong-ref", expectedHead: "pull request", isOnPullRequestHead: true },
5418 + { localBranch: "stale-head", expectedHead: "local", isOnPullRequestHead: false },
5419 + { localBranch: "checkout-race", expectedHead: "pull request", isOnPullRequestHead: true },
5420 + ] as const)(
5421 + "moves an existing PR branch into a new worktree only when nothing is lost ($localBranch)",
5422 + ({ localBranch, expectedHead, isOnPullRequestHead }) =>
5423 + Effect.gen(function* () {
5424 + const repoDir = yield* makeTempDir("t3code-git-manager-");
5425 + yield* initRepo(repoDir);
5426 + const remoteDir = yield* createBareRemote();
5427 + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5428 + yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
5429 + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing"]);
5430 + NodeFS.writeFileSync(NodePath.join(repoDir, "existing.txt"), "pushed\n");
5431 + yield* runGit(repoDir, ["add", "existing.txt"]);
5432 + yield* runGit(repoDir, ["commit", "-m", "Pushed PR commit"]);
5433 + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-existing"]);
5434 + if (localBranch === "ahead") {
5435 + NodeFS.writeFileSync(NodePath.join(repoDir, "mine.txt"), "mine\n");
5436 + yield* runGit(repoDir, ["add", "mine.txt"]);
5437 + yield* runGit(repoDir, ["commit", "-m", "My unpublished commit"]);
5438 + } else if (!localBranch.startsWith("rewritten")) {
5439 + yield* runGit(repoDir, ["checkout", "-b", "author-push"]);
5440 + NodeFS.writeFileSync(NodePath.join(repoDir, "authored.txt"), "authored\n");
5441 + yield* runGit(repoDir, ["add", "authored.txt"]);
5442 + yield* runGit(repoDir, ["commit", "-m", "New PR head commit"]);
5443 + yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-existing"]);
5444 + } else {
5445 + const staleHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim();
5446 + yield* runGit(repoDir, ["checkout", "-b", "author-rewrite"]);
5447 + NodeFS.writeFileSync(NodePath.join(repoDir, "existing.txt"), "rewritten\n");
5448 + yield* runGit(repoDir, ["add", "existing.txt"]);
5449 + yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten PR head"]);
5450 + yield* runGit(repoDir, [
5451 + "push",
5452 + "--force",
5453 + "origin",
5454 + "author-rewrite:feature/pr-existing",
5455 + ]);
5456 + if (localBranch === "rewritten") {
5457 + yield* runGit(repoDir, [
5458 + "update-ref",
5459 + "refs/remotes/origin/feature/pr-existing",
5460 + staleHead,
5461 + ]);
5462 + }
5463 + }
5464 + const localHead = (yield* runGit(repoDir, [
5465 + "rev-parse",
5466 + "feature/pr-existing",
5467 + ])).stdout.trim();
5468 + const pullHead = (yield* runGit(repoDir, [
5469 + "ls-remote",
5470 + "origin",
5471 + "refs/heads/feature/pr-existing",
5472 + ])).stdout.split("\t")[0];
5473 + yield* runGit(repoDir, ["checkout", "main"]);
5474 +
5475 + if (localBranch === "wrong-ref") {
5476 + yield* runGit(repoDir, ["push", "origin", "main:refs/pull/88/head"]);
5477 + }
5478 + const gate = {
5479 + matches: (args: ReadonlyArray<string>) =>
5480 + args[0] === "fetch" &&
5481 + args.some((arg) => arg.startsWith("+refs/heads/feature/pr-existing:")),
5482 + reached: yield* Deferred.make<void>(),
5483 + release: yield* Deferred.make<void>(),
5484 + };
5485 + const { manager } = yield* makeManager({
5486 + ...(localBranch === "checkout-race" ? { gitSpawnGate: gate } : {}),
5487 + providerScenario: {
5488 + pullRequest: {
5489 + number: 88,
5490 + title: "Existing branch PR",
5491 + url: "https://github.com/pingdotgg/codething-mvp/pull/88",
5492 + baseRefName: "main",
5493 + headRefName: "feature/pr-existing",
5494 + state: "open",
5495 + headSha: localBranch === "stale-head" ? localHead : pullHead,
5496 + isCrossRepository: false,
5497 + headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
5498 + headRepositoryOwnerLogin: "pingdotgg",
5499 + },
5500 + repositoryCloneUrls: {
5501 + "pingdotgg/codething-mvp": { url: remoteDir, sshUrl: remoteDir },
5502 + },
5503 + },
5504 + });
5505 +
5506 + const preparing = yield* Effect.forkChild(
5507 + preparePullRequestThread(manager, {
5508 + cwd: repoDir,
5509 + reference: "88",
5510 + mode: "worktree",
5511 + }),
5512 + );
5513 + if (localBranch === "checkout-race") {
5514 + yield* Deferred.await(gate.reached);
5515 + const checkout = yield* runGit(repoDir, ["checkout", "feature/pr-existing"], true);
5516 + yield* Deferred.succeed(gate.release, undefined);
5517 + expect(checkout.exitCode).not.toBe(0);
5518 + expect((yield* runGit(repoDir, ["branch", "--show-current"])).stdout.trim()).toBe("main");
5519 + }
5520 + const result = yield* Fiber.join(preparing);
5521 +
5522 + const head = expectedHead === "local" ? localHead : pullHead;
5523 + expect((yield* runGit(repoDir, ["rev-parse", "feature/pr-existing"])).stdout.trim()).toBe(
5524 + head,
5525 + );
5526 + expect(
5527 + (yield* runGit(result.worktreePath as string, ["rev-parse", "HEAD"])).stdout.trim(),
5528 + ).toBe(head);
5529 + expect(result).toMatchObject({ branch: "feature/pr-existing", isOnPullRequestHead });
5530 + }),
5531 + );
5532 +
5533 + it.effect.each(["adds", "removes"] as const)(
5534 + "checks out the submodules of the head an existing PR branch moves onto (head %s one)",
5535 + (headChange) =>
5536 + Effect.gen(function* () {
5537 + const submoduleDir = yield* makeTempDir("t3code-git-submodule-");
5538 + yield* initRepo(submoduleDir);
5539 + const repoDir = yield* makeTempDir("t3code-git-manager-");
5540 + yield* initRepo(repoDir);
5541 + const remoteDir = yield* createBareRemote();
5542 + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5543 + yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
5544 + yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing"]);
5545 + if (headChange === "removes") {
5546 + yield* runGit(repoDir, ["submodule", "add", submoduleDir, "shared"]);
5547 + yield* runGit(repoDir, ["commit", "-m", "Add shared submodule"]);
5548 + }
5549 + yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-existing"]);
5550 + yield* runGit(repoDir, ["checkout", "-b", "author-push"]);
5551 + if (headChange === "adds") {
5552 + yield* runGit(repoDir, ["submodule", "add", submoduleDir, "shared"]);
5553 + yield* runGit(repoDir, ["commit", "-m", "Add shared submodule"]);
5554 + } else {
5555 + yield* runGit(repoDir, ["rm", "shared"]);
5556 + yield* runGit(repoDir, ["commit", "-m", "Remove shared submodule"]);
5557 + }
5558 + yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-existing"]);
5559 + const pullHead = (yield* runGit(repoDir, ["rev-parse", "author-push"])).stdout.trim();
5560 + yield* runGit(repoDir, ["checkout", "main"]);
5561 +
5562 + const { manager } = yield* makeManager({
5563 + providerScenario: {
5564 + pullRequest: {
5565 + number: 89,
5566 + title: "Submodule PR",
5567 + headSha: pullHead,
5568 + url: "https://github.com/pingdotgg/codething-mvp/pull/89",
5569 + baseRefName: "main",
5570 + headRefName: "feature/pr-existing",
5571 + state: "open",
5572 + isCrossRepository: false,
5573 + headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
5574 + headRepositoryOwnerLogin: "pingdotgg",
5575 + },
5576 + repositoryCloneUrls: {
5577 + "pingdotgg/codething-mvp": { url: remoteDir, sshUrl: remoteDir },
5578 + },
5579 + },
5580 + });
5581 +
5582 + const result = yield* preparePullRequestThread(manager, {
5583 + cwd: repoDir,
5584 + reference: "89",
5585 + mode: "worktree",
5586 + });
5587 +
5588 + const worktreePath = result.worktreePath as string;
5589 + expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(pullHead);
5590 + expect(NodeFS.existsSync(NodePath.join(worktreePath, "shared", "README.md"))).toBe(
5591 + headChange === "adds",
5592 + );
5593 + expect((yield* runGit(worktreePath, ["status", "--porcelain"])).stdout).toBe("");
5594 + expect(result).toMatchObject({ isOnPullRequestHead: true });
5595 + }).pipe(
5596 + // Git refuses `file:` submodule transports by default (CVE-2022-39253) and ignores
5597 + // repo-level config for it, so a local fixture needs the env allowance.
5598 + (effect) =>
5599 + Effect.flatMap(HostProcess.Environment, (env) =>
5600 + effect.pipe(
5601 + Effect.provideService(HostProcess.Environment, {
5602 + ...env,
5603 + GIT_ALLOW_PROTOCOL: "file",
5604 + }),
5605 + ),
5606 + ),
5607 + ),
5608 + );
5609 +
5610 it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>
5611 Effect.gen(function* () {
5612 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/GitManager.ts
+122 -14
@@ -3094,6 +3094,97 @@ export const make = Effect.gen(function* () {
3094 return null;
3095 });
3096
3097 + // Claim the branch before refreshing, but initialize submodules only after selecting its head.
3098 + const refreshNewWorktree = Effect.fn("refreshNewWorktree")(function* (cwd: string) {
3099 + const upstreamCommitBeforeFetch = yield* gitCore
3100 + .resolveCommit({ cwd, revision: "@{upstream}" })
3101 + .pipe(
3102 + Effect.map((resolved) => resolved.commitSha),
3103 + Effect.orElseSucceed(() => null),
3104 + );
3105 + yield* configurePullRequestHeadUpstream(
3106 + cwd,
3107 + pullRequestWithRemoteInfo,
3108 + localPullRequestBranch,
3109 + );
3110 + const target = yield* changeRequestHeadRef(cwd, pullRequest.number).pipe(
3111 + Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd, ref })),
3112 + Effect.filterOrFail(
3113 + (resolved) =>
3114 + pullRequestSummary.headSha === undefined ||
3115 + resolved.commitSha === pullRequestSummary.headSha,
3116 + () =>
3117 + new GitManagerError({
3118 + operation: "preparePullRequestThread",
3119 + cwd,
3120 + detail: "The fetched ref does not match the pull request head.",
3121 + }),
3122 + ),
3123 + Effect.catch(() =>
3124 + gitCore.resolveCommit({ cwd, revision: "@{upstream}" }).pipe(
3125 + Effect.filterOrFail(
3126 + (resolved) => resolved.commitSha === pullRequestSummary.headSha,
3127 + () =>
3128 + new GitManagerError({
3129 + operation: "preparePullRequestThread",
3130 + cwd,
3131 + detail: "The configured upstream does not match the pull request head.",
3132 + }),
3133 + ),
3134 + ),
3135 + ),
3136 + );
3137 + const { commitSha: headCommit } = yield* gitCore.resolveCommit({ cwd, revision: "HEAD" });
3138 + // A head that was ever published loses nothing when reset, even if a fetch already moved its upstream.
3139 + const gitLines = (args: ReadonlyArray<string>) =>
3140 + gitCore
3141 + .execute({
3142 + operation: "GitManager.preparePullRequestThread.publishedHead",
3143 + cwd,
3144 + args,
3145 + allowNonZeroExit: true,
3146 + timeoutMs: 5_000,
3147 + })
3148 + .pipe(
3149 + Effect.map((result) =>
3150 + result.exitCode === 0 ? result.stdout.split("\n").filter(Boolean) : [],
3151 + ),
3152 + );
3153 + const publishedHead =
3154 + (yield* gitLines(["for-each-ref", "--contains", headCommit, "refs/remotes"])).length >
3155 + 0 ||
3156 + (yield* gitLines(["log", "--walk-reflogs", "--format=%H", "@{upstream}"])).includes(
3157 + headCommit,
3158 + );
3159 + return yield* gitCore
3160 + .refreshCheckedOutBranch({
3161 + cwd,
3162 + targetCommit: target.commitSha,
3163 + resetWhenHeadCommit: publishedHead ? headCommit : upstreamCommitBeforeFetch,
3164 + })
3165 + .pipe(Effect.map((result) => result.onTarget));
3166 + });
3167 +
3168 + const createPullRequestWorktree = Effect.fn("createPullRequestWorktree")(function* (
3169 + onWorktreeClaimed?: (path: string) => Effect.Effect<void>,
3170 + ) {
3171 + return yield* gitCore.createWorktree(
3172 + {
3173 + cwd: input.cwd,
3174 + refName: localPullRequestBranch,
3175 + path: null,
3176 + },
3177 + {
3178 + ...(onWorktreeClaimed ? { progress: { onWorktreeClaimed } } : {}),
3179 + ...(yield* readWorktreeCreationSettings),
3180 + submodules: yield* projectSettingsFor(input).pipe(
3181 + Effect.map(({ settings }) => settings.worktreeSubmodules),
3182 + Effect.orElseSucceed(() => null),
3183 + ),
3184 + },
3185 + );
3186 + });
3187 +
3188 const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);
3189 const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath
3190 ? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)
@@ -3115,6 +3206,36 @@ export const make = Effect.gen(function* () {
3206 "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
3207 });
3208 }
3209 + // Materializing would force this branch onto the head.
3210 + if (existingBranchBeforeFetch !== null) {
3211 + let isOnPullRequestHead = false;
3212 + const worktree = yield* createPullRequestWorktree((cwd) =>
3213 + refreshNewWorktree(cwd).pipe(
3214 + Effect.catch((error) =>
3215 + Effect.logWarning(
3216 + "GitManager.preparePullRequestThread existing branch refresh failed",
3217 + {
3218 + localBranch: localPullRequestBranch,
3219 + cause: error,
3220 + },
3221 + ).pipe(Effect.as(false)),
3222 + ),
3223 + Effect.tap((onTarget) =>
3224 + Effect.sync(() => {
3225 + isOnPullRequestHead = onTarget;
3226 + }),
3227 + ),
3228 + Effect.asVoid,
3229 + ),
3230 + );
3231 + yield* maybeRunSetupScript(worktree.worktree.path);
3232 + return {
3233 + pullRequest,
3234 + branch: worktree.worktree.refName,
3235 + worktreePath: worktree.worktree.path,
3236 + isOnPullRequestHead,
3237 + };
3238 + }
3239
3240 yield* materializePullRequestHeadBranch(
3241 input.cwd,
@@ -3144,20 +3265,7 @@ export const make = Effect.gen(function* () {
3265 });
3266 }
3267
3147 - const worktree = yield* gitCore.createWorktree(
3148 - {
3149 - cwd: input.cwd,
3150 - refName: localPullRequestBranch,
3151 - path: null,
3152 - },
3153 - {
3154 - ...(yield* readWorktreeCreationSettings),
3155 - submodules: yield* projectSettingsFor(input).pipe(
3156 - Effect.map(({ settings }) => settings.worktreeSubmodules),
3157 - Effect.orElseSucceed(() => null),
3158 - ),
3159 - },
3160 - );
3268 + const worktree = yield* createPullRequestWorktree();
3269 yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
3270 yield* maybeRunSetupScript(worktree.worktree.path);
3271