The best way to control Claude Code, Codex and more from any computer or phone
fix(server): pull_request_create pushes an unpushed branch (#39903)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 20, 2026 at 16:34 UTC
3e837d0bdbd06619cdac3f525d2f04d20ddb6a62
4 files changed
+226
-42
apps/server/src/git/GitManager.test.ts
+153
-12
@@ -4426,7 +4426,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4426
}),
4427
);
4428
4429
- it.effect("createPullRequest refuses a branch with commits it has not pushed", () =>
4429
+ it.effect("createPullRequest pushes the branch before opening its PR", () =>
4430
Effect.gen(function* () {
4431
const repoDir = yield* makeTempDir("t3code-git-manager-");
4432
yield* initRepo(repoDir);
@@ -4434,27 +4434,94 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4434
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
4435
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
4436
yield* runGit(repoDir, ["checkout", "-b", "feature/unpushed"]);
4437
- yield* runGit(repoDir, ["push", "-u", "origin", "feature/unpushed"]);
4437
+ NodeFS.writeFileSync(NodePath.join(repoDir, "first.txt"), "first\n");
4438
+ yield* runGit(repoDir, ["add", "first.txt"]);
4439
+ yield* runGit(repoDir, ["commit", "-m", "First commit"]);
4440
+ const remoteHead = (branch: string) =>
4441
+ runGit(repoDir, ["ls-remote", "origin", `refs/heads/${branch}`]).pipe(
4442
+ Effect.map((result) => result.stdout.split("\t")[0]),
4443
+ );
4444
+ const localHead = () =>
4445
+ runGit(repoDir, ["rev-parse", "HEAD"]).pipe(Effect.map((result) => result.stdout.trim()));
4446
+
4447
+ // A branch without an upstream is published first.
4448
+ const unpublished = yield* makeManager({ providerScenario: { prListSequence: [[], []] } });
4449
+ yield* unpublished.manager.createPullRequest({
4450
+ cwd: repoDir,
4451
+ projectId: ProjectId.make("project-1"),
4452
+ title: "Feature",
4453
+ body: "Body",
4454
+ });
4455
+ expect(yield* remoteHead("feature/unpushed")).toBe(yield* localHead());
4456
+ expect(created(unpublished.providerCalls)).toMatchObject([
4457
+ { headSelector: "feature/unpushed" },
4458
+ ]);
4459
+
4460
+ // Commits made after publishing are pushed too.
4461
NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n");
4462
yield* runGit(repoDir, ["add", "late.txt"]);
4463
yield* runGit(repoDir, ["commit", "-m", "Late commit"]);
4441
- const { manager, providerCalls } = yield* makeManager({
4442
- providerScenario: { prListSequence: [[], []] },
4464
+ const ahead = yield* makeManager({ providerScenario: { prListSequence: [[], []] } });
4465
+ yield* ahead.manager.createPullRequest({
4466
+ cwd: repoDir,
4467
+ projectId: ProjectId.make("project-1"),
4468
+ title: "Feature",
4469
+ body: "Body",
4470
});
4444
-
4471
+ expect(yield* remoteHead("feature/unpushed")).toBe(yield* localHead());
4472
+ expect(created(ahead.providerCalls)).toHaveLength(1);
4473
+
4474
+ // A rejected push fails with git's reason and opens nothing; it never forces.
4475
+ const otherDir = yield* makeTempDir("t3code-git-manager-other-");
4476
+ yield* runGit(otherDir, ["clone", "--branch", "feature/unpushed", remoteDir, "."]);
4477
+ yield* runGit(otherDir, ["config", "user.email", "other@example.com"]);
4478
+ yield* runGit(otherDir, ["config", "user.name", "Other"]);
4479
+ NodeFS.writeFileSync(NodePath.join(otherDir, "theirs.txt"), "theirs\n");
4480
+ yield* runGit(otherDir, ["add", "theirs.txt"]);
4481
+ yield* runGit(otherDir, ["commit", "-m", "Their commit"]);
4482
+ yield* runGit(otherDir, ["push"]);
4483
+ const theirHead = yield* remoteHead("feature/unpushed");
4484
+ NodeFS.writeFileSync(NodePath.join(repoDir, "mine.txt"), "mine\n");
4485
+ yield* runGit(repoDir, ["add", "mine.txt"]);
4486
+ yield* runGit(repoDir, ["commit", "-m", "My commit"]);
4487
+ const rejected = yield* makeManager({ providerScenario: { prListSequence: [[], []] } });
4488
const error = yield* Effect.flip(
4446
- manager.createPullRequest({
4489
+ rejected.manager.createPullRequest({
4490
cwd: repoDir,
4491
projectId: ProjectId.make("project-1"),
4492
title: "Feature",
4493
body: "Body",
4494
}),
4495
);
4496
+ expect(error.message).toContain("Could not push feature/unpushed");
4497
+ expect(error.message).toContain("Pull or rebase, then push again");
4498
+ expect(yield* remoteHead("feature/unpushed")).toBe(theirHead);
4499
+ expect(created(rejected.providerCalls)).toEqual([]);
4500
+ yield* runGit(repoDir, ["fetch", "origin"]);
4501
+ yield* runGit(repoDir, ["reset", "--hard", "origin/feature/unpushed"]);
4502
+
4503
+ // A publish whose upstream cannot be recorded says so instead of claiming nothing was pushed.
4504
+ yield* runGit(repoDir, ["checkout", "-b", "feature/locked"]);
4505
+ const lockPath = NodePath.join(repoDir, ".git", "config.lock");
4506
+ NodeFS.writeFileSync(lockPath, "");
4507
+ const locked = yield* makeManager({ providerScenario: { prListSequence: [[], []] } });
4508
+ // The upstream write retries on the real clock before giving up.
4509
+ const lockedError = yield* Effect.flip(
4510
+ TestClock.withLive(
4511
+ locked.manager.createPullRequest({
4512
+ cwd: repoDir,
4513
+ projectId: ProjectId.make("project-1"),
4514
+ title: "Feature",
4515
+ body: "Body",
4516
+ }),
4517
+ ),
4518
+ );
4519
+ NodeFS.rmSync(lockPath);
4520
+ expect(lockedError.message).toContain("could not record it as the branch's upstream");
4521
+ expect(yield* remoteHead("feature/locked")).toBe(yield* localHead());
4522
+ expect(created(locked.providerCalls)).toEqual([]);
4523
+ yield* runGit(repoDir, ["checkout", "feature/unpushed"]);
4524
4454
- expect(error.message).toContain("1 unpushed commit");
4455
- expect(created(providerCalls)).toEqual([]);
4456
-
4457
- // An open PR is returned as it is; returning it publishes nothing.
4525
const open = {
4526
number: 7,
4527
title: "Feature",
@@ -4462,7 +4529,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4529
baseRefName: "main",
4530
headRefName: "feature/unpushed",
4531
};
4465
- const existing = yield* makeManager({ providerScenario: { prListSequence: [[open]] } });
4532
+ // Pushing into an open PR returns it, and status no longer reports the pushed commit.
4533
+ NodeFS.writeFileSync(NodePath.join(repoDir, "into-open.txt"), "into open\n");
4534
+ yield* runGit(repoDir, ["add", "into-open.txt"]);
4535
+ yield* runGit(repoDir, ["commit", "-m", "Into open PR"]);
4536
+ const existing = yield* makeManager({
4537
+ providerScenario: { prListSequence: [[open], [open], [open], [open]] },
4538
+ });
4539
+ expect((yield* existing.manager.status({ cwd: repoDir })).aheadCount).toBe(1);
4540
const found = yield* existing.manager.createPullRequest({
4541
cwd: repoDir,
4542
projectId: ProjectId.make("project-1"),
@@ -4470,6 +4544,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4544
body: "Body",
4545
});
4546
expect(found).toMatchObject({ status: "opened_existing", number: 7 });
4547
+ expect((yield* existing.manager.status({ cwd: repoDir })).aheadCount).toBe(0);
4548
4549
// A retry after a failed draft finds the open PR and still drafts it.
4550
const actions: Array<PullRequestActionInput> = [];
@@ -4492,7 +4567,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4567
]);
4568
4569
// A draft of a PR the host does not list yet fails, so a retry drafts it.
4495
- yield* runGit(repoDir, ["push"]);
4570
const unlisted = yield* makeManager({
4571
providerScenario: { prListSequence: [[], []], createsDraftChangeRequests: false },
4572
});
@@ -4533,6 +4607,73 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4607
}),
4608
);
4609
4610
+ it.effect("createPullRequest pushes to the push remote and never to the base branch", () =>
4611
+ Effect.gen(function* () {
4612
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
4613
+ yield* initRepo(repoDir);
4614
+ const originDir = yield* createBareRemote();
4615
+ const forkDir = yield* createBareRemote();
4616
+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
4617
+ yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
4618
+ yield* runGit(repoDir, ["remote", "add", "fork", forkDir]);
4619
+ const readOrigin = (branch: string) =>
4620
+ runGit(repoDir, ["ls-remote", "origin", `refs/heads/${branch}`]).pipe(
4621
+ Effect.map((result) => result.stdout),
4622
+ );
4623
+ const commit = (file: string) =>
4624
+ Effect.gen(function* () {
4625
+ NodeFS.writeFileSync(NodePath.join(repoDir, file), `${file}\n`);
4626
+ yield* runGit(repoDir, ["add", file]);
4627
+ yield* runGit(repoDir, ["commit", "-m", file]);
4628
+ });
4629
+ const createPr = (manager: GitManager.GitManager["Service"]) =>
4630
+ manager.createPullRequest({
4631
+ cwd: repoDir,
4632
+ projectId: ProjectId.make("project-1"),
4633
+ title: "Feature",
4634
+ body: "Body",
4635
+ });
4636
+
4637
+ // Commits on the base branch are never pushed to it.
4638
+ yield* commit("on-main.txt");
4639
+ const originMain = yield* readOrigin("main");
4640
+ const onBase = yield* makeManager({ providerScenario: { prListSequence: [[]] } });
4641
+ const error = yield* Effect.flip(createPr(onBase.manager));
4642
+ expect(error.message).toContain("main is the base branch");
4643
+ expect(yield* readOrigin("main")).toBe(originMain);
4644
+ expect(created(onBase.providerCalls)).toEqual([]);
4645
+ yield* runGit(repoDir, ["reset", "--hard", "origin/main"]);
4646
+
4647
+ // A push to a separate push remote leaves the upstream behind, and still opens the PR.
4648
+ yield* runGit(repoDir, ["checkout", "-b", "topic"]);
4649
+ yield* commit("topic.txt");
4650
+ yield* runGit(repoDir, ["push", "-u", "origin", "topic"]);
4651
+ yield* commit("late.txt");
4652
+ yield* configureVisibleRemoteUrlWithLocalRewrite(
4653
+ repoDir,
4654
+ "origin",
4655
+ "git@github.com:pingdotgg/codething-mvp.git",
4656
+ originDir,
4657
+ );
4658
+ yield* configureVisibleRemoteUrlWithLocalRewrite(
4659
+ repoDir,
4660
+ "fork",
4661
+ "git@github.com:octocat/codething-mvp.git",
4662
+ forkDir,
4663
+ );
4664
+ yield* runGit(repoDir, ["config", "remote.pushDefault", "fork"]);
4665
+ const viaFork = yield* makeManager();
4666
+ const result = yield* createPr(viaFork.manager);
4667
+ expect(result.status).toBe("created");
4668
+ expect(
4669
+ yield* runGit(forkDir, ["--git-dir=.", "log", "-1", "--pretty=%s", "topic"]),
4670
+ ).toMatchObject({ stdout: "late.txt\n" });
4671
+ expect(created(viaFork.providerCalls)).toEqual([
4672
+ { baseRefName: "main", headSelector: "octocat:topic" },
4673
+ ]);
4674
+ }),
4675
+ );
4676
+
4677
it.effect("generates PR content from the created worktree's selected remote base", () =>
4678
Effect.gen(function* () {
4679
const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/GitManager.ts
+71
-28
@@ -187,7 +187,7 @@ export class GitManager extends Context.Service<
187
input: GitRunStackedActionInput,
188
options?: GitRunStackedActionOptions,
189
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
190
- /** Opens a PR for the checkout's pushed branch, or returns the one already open. */
190
+ /** Pushes the checkout's branch when needed, then opens its PR or returns the one already open. */
191
readonly createPullRequest: (input: {
192
readonly cwd: string;
193
readonly projectId: ProjectId;
@@ -845,6 +845,22 @@ export const make = Effect.gen(function* () {
845
}
846
return result;
847
});
848
+ const createPrNeedsPush = Effect.fn("GitManager.createPrNeedsPush")(function* (
849
+ cwd: string,
850
+ status: {
851
+ readonly branch: string | null;
852
+ readonly hasUpstream: boolean;
853
+ readonly aheadCount: number;
854
+ },
855
+ ) {
856
+ if (!status.branch) return false;
857
+ if (!status.hasUpstream || status.aheadCount > 0) return true;
858
+ // A current upstream says nothing about a separate push remote, which may lack HEAD.
859
+ const target = yield* gitCore
860
+ .resolvePushTarget(cwd, { branch: status.branch, hasUpstream: true })
861
+ .pipe(Effect.orElseSucceed(() => null));
862
+ return target?.viaPushRemote === true;
863
+ });
864
const readWorktreeCreationSettings = serverSettingsService.getSettings.pipe(
865
Effect.map((settings) => ({
866
worktreesDirectory: settings.worktreesDirectory,
@@ -2511,8 +2527,9 @@ export const make = Effect.gen(function* () {
2527
};
2528
}
2529
2514
- // A PR opened from the remote branch would leave out commits not pushed yet.
2515
- if (details.aheadCount > 0) {
2530
+ // A PR opened from the remote branch would leave out commits not pushed yet. The ahead
2531
+ // count is against the upstream, which a push to a separate push remote leaves behind.
2532
+ if (!pushRemoteRef && details.aheadCount > 0) {
2533
return yield* new GitManagerError({
2534
operation: "runPrStep",
2535
cwd,
@@ -2649,17 +2666,57 @@ export const make = Effect.gen(function* () {
2666
const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn(
2667
"GitManager.createPullRequest",
2668
)(function* (input) {
2652
- const result = yield* openPrFromBranch(
2653
- input.cwd,
2654
- null,
2655
- () => Effect.void,
2656
- undefined,
2657
- input.baseBranch,
2658
- input.draft === true,
2659
- () => Effect.succeed({ title: input.title, body: input.body }),
2669
+ const status = yield* gitCore.statusDetails(input.cwd);
2670
+ const needsPush = yield* createPrNeedsPush(input.cwd, status);
2671
+ if (needsPush && status.branch) {
2672
+ yield* ensurePrHeadIsNotBase(
2673
+ input.cwd,
2674
+ { ...status, branch: status.branch },
2675
+ (yield* changeRequestTermsFor(input.cwd)).shortLabelWithArticle,
2676
+ );
2677
+ }
2678
+ const push = needsPush
2679
+ ? yield* pushCurrentBranch(input.cwd, status.branch).pipe(
2680
+ Effect.mapError(
2681
+ (cause) =>
2682
+ new GitManagerError({
2683
+ operation: "createPullRequest",
2684
+ cwd: input.cwd,
2685
+ detail: `Could not push ${status.branch}: ${cause.detail}${cause.reason === undefined ? "" : ` (${cause.reason})`}`,
2686
+ cause,
2687
+ }),
2688
+ ),
2689
+ )
2690
+ : null;
2691
+ const result = yield* Effect.gen(function* () {
2692
+ // Publishing records the upstream, which the PR step needs to find the head branch.
2693
+ if (!status.hasUpstream && push?.status === "pushed" && push.setUpstream === false) {
2694
+ return yield* new GitManagerError({
2695
+ operation: "createPullRequest",
2696
+ cwd: input.cwd,
2697
+ detail: `Pushed ${status.branch} to ${push.upstreamBranch}, but could not record it as the branch's upstream. Set the upstream, then try again.`,
2698
+ });
2699
+ }
2700
+ return yield* openPrFromBranch(
2701
+ input.cwd,
2702
+ null,
2703
+ () => Effect.void,
2704
+ push && "pushRemote" in push && push.pushRemote && push.upstreamBranch
2705
+ ? { remoteName: push.pushRemote, upstreamRef: push.upstreamBranch }
2706
+ : undefined,
2707
+ input.baseBranch,
2708
+ input.draft === true,
2709
+ () => Effect.succeed({ title: input.title, body: input.body }),
2710
+ );
2711
+ }).pipe(
2712
+ // A push changes the ahead count, and a new PR changes the branch's PR lookup, so
2713
+ // both leave cached status stale whatever the PR step does next.
2714
+ Effect.onExit((exit) =>
2715
+ push?.status === "pushed" || (Exit.isSuccess(exit) && exit.value.status === "created")
2716
+ ? invalidateStatus(input.cwd)
2717
+ : Effect.void,
2718
+ ),
2719
);
2661
- // The thread's branch PR comes from status, which may hold the lookup from before.
2662
- if (result.status === "created") yield* invalidateStatus(input.cwd);
2720
const openedAsDraft =
2721
result.status === "created" &&
2722
(yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true;
@@ -3614,26 +3671,12 @@ export const make = Effect.gen(function* () {
3671
> {
3672
const initialStatus = yield* gitCore.statusDetails(input.cwd);
3673
const wantsCommit = isCommitAction(input.action);
3617
- const upToDateBranch =
3618
- input.action === "create_pr" &&
3619
- initialStatus.hasUpstream &&
3620
- initialStatus.aheadCount === 0
3621
- ? initialStatus.branch
3622
- : null;
3623
- // A current upstream says nothing about a separate push remote, which may lack HEAD.
3624
- const pushTarget = upToDateBranch
3625
- ? yield* gitCore
3626
- .resolvePushTarget(input.cwd, { branch: upToDateBranch, hasUpstream: true })
3627
- .pipe(Effect.orElseSucceed(() => null))
3628
- : null;
3674
const wantsPush =
3675
input.action === "push" ||
3676
input.action === "commit_push" ||
3677
input.action === "commit_push_pr" ||
3678
(input.action === "create_pr" &&
3634
- (!initialStatus.hasUpstream ||
3635
- initialStatus.aheadCount > 0 ||
3636
- pushTarget?.viaPushRemote === true));
3679
+ (!initialStatus.hasUpstream || (yield* createPrNeedsPush(input.cwd, initialStatus))));
3680
const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr";
3681
3682
if (input.featureBranch && !wantsCommit) {
apps/server/src/mcp/toolkits/pullRequests/tools.ts
+1
-1
@@ -668,7 +668,7 @@ const ListPullRequestsTool = Tool.make("pull_request_list", {
668
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutForge);
669
670
const CreatePullRequestTool = Tool.make("pull_request_create", {
671
- description: "Open a PR from this thread's pushed branch and link it, or return its open PR.",
671
+ description: "Push this thread's branch, then open its PR and link it, or return its open PR.",
672
parameters: Schema.Struct({
673
environmentId: OrchestratorMcpEnvironmentTarget,
674
title: TrimmedNonEmptyString,
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 6245,
3
"codexAdditionalContextBytes": 7639,
4
- "mcpToolListJsonBytes": 58404
4
+ "mcpToolListJsonBytes": 58405
5
}