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 23, 00:30 UTC
fix(server): new worktrees fetch their base branch's own remote (#21032)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Stephen Benjamin committed
Oct 19, 2026 at 18:56 UTC
673c5e3b3c85a7f2cd2df9ed73d6b712328378c6
24 files changed
+970
-316
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+2
-2
@@ -387,8 +387,8 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
387
<SettingsSection title="Worktrees">
388
<SettingsSwitchRow
389
icon="arrow.triangle.branch"
390
- label="Start from origin"
391
- subtitle="Base new worktrees on the remote branch."
390
+ label="Start from remote"
391
+ subtitle="Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing."
392
value={uniform("newWorktreesStartFromOrigin")}
393
disabled={disabledFor("newWorktreesStartFromOrigin")}
394
onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
apps/mobile/src/features/threads/NewTaskContextPickerScreens.tsx
+1
-1
@@ -438,7 +438,7 @@ export function BranchPickerScreen(props: {
438
>
439
<ToggleRow
440
onValueChange={props.worktree.onChangeStartFromOrigin}
441
- title="Start from origin"
441
+ title="Start from remote"
442
value={props.worktree.startFromOrigin}
443
/>
444
</View>
apps/mobile/src/features/threads/new-task-context-presentation.test.ts
+2
-2
@@ -117,14 +117,14 @@ describe("resolveNewTaskBranchLabel", () => {
117
).toBe("From main");
118
});
119
120
- it("labels a remote worktree base with From origin", () => {
120
+ it("labels a remote worktree base with a remote marker", () => {
121
expect(
122
resolveNewTaskBranchLabel({
123
branchName: "main",
124
startFromOrigin: true,
125
workspaceMode: "worktree",
126
}),
127
- ).toBe("From origin/main");
127
+ ).toBe("From main (remote)");
128
});
129
130
it("prompts when no branch is available", () => {
apps/mobile/src/features/threads/new-task-context-presentation.ts
+2
-2
@@ -78,8 +78,8 @@ export function resolveNewTaskBranchLabel(input: {
78
return input.branchName;
79
}
80
81
- const baseRef = input.startFromOrigin ? `origin/${input.branchName}` : input.branchName;
82
- return `From ${baseRef}`;
81
+ // Only the server can determine a local branch's configured remote.
82
+ return input.startFromOrigin ? `From ${input.branchName} (remote)` : `From ${input.branchName}`;
83
}
84
85
export function shouldCheckoutNewTaskBranch(input: {
apps/server/src/git/GitManager.test.ts
+256
-56
@@ -5384,77 +5384,277 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5384
}),
5385
);
5386
5387
- it.effect("generates PR content from branch changes when the remote base advances", () =>
5387
+ it.effect("generates PR content from the created worktree's selected remote base", () =>
5388
Effect.gen(function* () {
5389
const repoDir = yield* makeTempDir("t3code-git-manager-");
5390
yield* initRepo(repoDir);
5391
- const remoteDir = yield* createBareRemote();
5392
- yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5393
- yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
5394
- yield* runGit(remoteDir, ["--git-dir=.", "symbolic-ref", "HEAD", "refs/heads/main"]);
5395
-
5396
- const peerDir = yield* makeTempDir("t3code-git-peer-");
5397
- yield* runGit(peerDir, ["clone", remoteDir, "."]);
5398
- yield* runGit(peerDir, ["config", "user.email", "peer@example.com"]);
5399
- yield* runGit(peerDir, ["config", "user.name", "Peer User"]);
5400
- NodeFS.writeFileSync(NodePath.join(peerDir, "remote.txt"), "remote\n");
5401
- yield* runGit(peerDir, ["add", "remote.txt"]);
5402
- yield* runGit(peerDir, ["commit", "-m", "Remote base commit"]);
5403
- yield* runGit(peerDir, ["push", "origin", "main"]);
5404
-
5405
- yield* runGit(repoDir, ["fetch", "origin"]);
5406
- yield* runGit(repoDir, [
5407
- "checkout",
5408
- "--no-track",
5409
- "-b",
5410
- "feature/remote-base",
5411
- "origin/main",
5412
- ]);
5413
- NodeFS.writeFileSync(NodePath.join(repoDir, "feature.txt"), "feature\n");
5414
- yield* runGit(repoDir, ["add", "feature.txt"]);
5415
- yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
5416
- yield* runGit(repoDir, ["push", "-u", "origin", "feature/remote-base"]);
5417
- yield* runGit(repoDir, ["config", "branch.feature/remote-base.gh-merge-base", "main"]);
5418
-
5419
- NodeFS.writeFileSync(NodePath.join(peerDir, "later-main.txt"), "unrelated\n");
5420
- yield* runGit(peerDir, ["add", "later-main.txt"]);
5421
- yield* runGit(peerDir, ["commit", "-m", "Later main commit"]);
5422
- yield* runGit(peerDir, ["push", "origin", "main"]);
5423
- yield* runGit(repoDir, ["fetch", "origin"]);
5391
+ const originDir = yield* createBareRemote();
5392
+ const upstreamDir = yield* createBareRemote();
5393
+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
5394
+ yield* runGit(repoDir, ["remote", "add", "upstream", upstreamDir]);
5395
+ yield* runGit(repoDir, ["checkout", "-b", "fork-release"]);
5396
+ NodeFS.writeFileSync(NodePath.join(repoDir, "fork.txt"), "fork-only work\n");
5397
+ NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
5398
+ NodeFS.writeFileSync(
5399
+ NodePath.join(repoDir, ".github/pull_request_template.md"),
5400
+ "Fork template",
5401
+ );
5402
+ yield* runGit(repoDir, ["add", "."]);
5403
+ yield* runGit(repoDir, ["commit", "-m", "Fork release commit"]);
5404
+ yield* runGit(repoDir, ["push", "origin", "HEAD:refs/heads/release"]);
5405
+ yield* runGit(repoDir, ["checkout", "-b", "stable", "main"]);
5406
+ NodeFS.writeFileSync(NodePath.join(repoDir, "upstream.txt"), "upstream-only work\n");
5407
+ NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
5408
+ NodeFS.writeFileSync(
5409
+ NodePath.join(repoDir, ".github/pull_request_template.md"),
5410
+ "Upstream template",
5411
+ );
5412
+ yield* runGit(repoDir, ["add", "."]);
5413
+ yield* runGit(repoDir, ["commit", "-m", "Upstream release commit"]);
5414
+ yield* runGit(repoDir, ["push", "-u", "upstream", "stable:release"]);
5415
+ yield* runGit(repoDir, ["branch", "upstream/release", "fork-release"]);
5416
+
5417
+ const driver = yield* GitVcsDriver.GitVcsDriver;
5418
+ const fetched = yield* driver.fetchWorktreeBaseCommit({ cwd: repoDir, refName: "stable" });
5419
+ expect(fetched).not.toBeNull();
5420
+ const worktreePath = NodePath.join(yield* makeTempDir("t3code-git-worktrees-"), "feature");
5421
+ yield* driver.createWorktree({
5422
+ cwd: repoDir,
5423
+ path: worktreePath,
5424
+ refName: fetched!.commitSha,
5425
+ newRefName: "feature/from-upstream",
5426
+ baseRefName: `refs/remotes/${fetched!.remoteRefName}`,
5427
+ });
5428
+ NodeFS.writeFileSync(NodePath.join(worktreePath, "feature.txt"), "feature work\n");
5429
+ yield* runGit(worktreePath, ["add", "feature.txt"]);
5430
+ yield* runGit(worktreePath, ["commit", "-m", "Feature commit"]);
5431
+ yield* runGit(worktreePath, ["push", "-u", "origin", "feature/from-upstream"]);
5432
5425
- let generatedCommitSummary = "";
5426
- let generatedDiffSummary = "";
5427
- let generatedDiffPatch = "";
5428
- const { manager } = yield* makeManager({
5429
- ghScenario: {
5430
- prListSequence: ["[]", "[]"],
5431
- },
5433
+ const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
5434
+ const { manager, ghCalls } = yield* makeManager({
5435
+ ghScenario: { prListSequence: ["[]", "[]"] },
5436
textGeneration: {
5437
generatePrContent: (input) => {
5434
- generatedCommitSummary = input.commitSummary;
5435
- generatedDiffSummary = input.diffSummary;
5436
- generatedDiffPatch = input.diffPatch;
5438
+ generatedInputs.push(input);
5439
return Effect.succeed({ title: "Feature PR", body: "Feature body" });
5440
},
5441
},
5442
});
5441
-
5442
- const result = yield* runStackedAction(manager, {
5443
- cwd: repoDir,
5444
- action: "create_pr",
5445
- });
5443
+ const result = yield* runStackedAction(manager, { cwd: worktreePath, action: "create_pr" });
5444
5445
expect(result.pr.status).toBe("created");
5448
- expect(generatedCommitSummary).toContain("Feature commit");
5449
- expect(generatedCommitSummary).not.toContain("Remote base commit");
5450
- expect(generatedCommitSummary).not.toContain("Later main commit");
5451
- expect(generatedDiffSummary).toContain("feature.txt");
5452
- expect(generatedDiffSummary).not.toContain("later-main.txt");
5453
- expect(generatedDiffPatch).toContain("feature.txt");
5454
- expect(generatedDiffPatch).not.toContain("later-main.txt");
5446
+ expect(generatedInputs).toHaveLength(1);
5447
+ const generated = generatedInputs[0]!;
5448
+ expect.soft(generated.commitSummary).toContain("Feature commit");
5449
+ expect.soft(generated.commitSummary).not.toContain("Upstream release commit");
5450
+ expect.soft(generated.commitSummary).not.toContain("Fork release commit");
5451
+ expect.soft(generated.diffSummary).toContain("feature.txt");
5452
+ expect.soft(generated.diffSummary).not.toContain("upstream.txt");
5453
+ expect.soft(generated.diffSummary).not.toContain("fork.txt");
5454
+ expect.soft(generated.diffPatch).toContain("+feature work");
5455
+ expect.soft(generated.diffPatch).not.toContain("upstream-only work");
5456
+ expect.soft(generated.diffPatch).not.toContain("fork-only work");
5457
+ expect.soft(generated.changeRequestTemplate).toBe("Upstream template");
5458
+ expect(
5459
+ ghCalls.some((call) =>
5460
+ call.includes("pr create --base release --head feature/from-upstream"),
5461
+ ),
5462
+ ).toBe(true);
5463
}),
5464
);
5465
5466
+ it.effect(
5467
+ "preserves a local worktree PR base that shadows a remote ref, including legacy bases",
5468
+ () =>
5469
+ Effect.gen(function* () {
5470
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
5471
+ yield* initRepo(repoDir);
5472
+ const originDir = yield* createBareRemote();
5473
+ const upstreamDir = yield* createBareRemote();
5474
+ yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
5475
+ yield* runGit(repoDir, ["remote", "add", "upstream", upstreamDir]);
5476
+ yield* runGit(repoDir, ["checkout", "-b", "release"]);
5477
+ NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
5478
+ NodeFS.writeFileSync(NodePath.join(repoDir, "remote.txt"), "remote-only work\n");
5479
+ NodeFS.writeFileSync(
5480
+ NodePath.join(repoDir, ".github/pull_request_template.md"),
5481
+ "Remote release template",
5482
+ );
5483
+ yield* runGit(repoDir, ["add", "."]);
5484
+ yield* runGit(repoDir, ["commit", "-m", "Remote release commit"]);
5485
+ yield* runGit(repoDir, ["push", "upstream", "release"]);
5486
+
5487
+ yield* runGit(repoDir, ["checkout", "-b", "upstream/release", "main"]);
5488
+ NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
5489
+ NodeFS.writeFileSync(NodePath.join(repoDir, "local.txt"), "local-base work\n");
5490
+ NodeFS.writeFileSync(
5491
+ NodePath.join(repoDir, ".github/pull_request_template.md"),
5492
+ "Local branch template",
5493
+ );
5494
+ yield* runGit(repoDir, ["add", "."]);
5495
+ yield* runGit(repoDir, ["commit", "-m", "Local base commit"]);
5496
+ yield* runGit(repoDir, ["push", "upstream", "refs/heads/upstream/release"]);
5497
+ yield* runGit(repoDir, ["push", "origin", "refs/heads/upstream/release"]);
5498
+
5499
+ const driver = yield* GitVcsDriver.GitVcsDriver;
5500
+ const worktreePath = NodePath.join(yield* makeTempDir("t3code-git-worktrees-"), "feature");
5501
+ yield* driver.createWorktree({
5502
+ cwd: repoDir,
5503
+ path: worktreePath,
5504
+ refName: "refs/heads/upstream/release",
5505
+ newRefName: "feature/from-local",
5506
+ baseRefName: "refs/heads/upstream/release",
5507
+ });
5508
+ NodeFS.writeFileSync(NodePath.join(worktreePath, "feature.txt"), "feature work\n");
5509
+ yield* runGit(worktreePath, ["add", "feature.txt"]);
5510
+ yield* runGit(worktreePath, ["commit", "-m", "Feature commit"]);
5511
+ yield* runGit(worktreePath, ["push", "-u", "origin", "feature/from-local"]);
5512
+
5513
+ const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
5514
+ const { manager, ghCalls } = yield* makeManager({
5515
+ ghScenario: { prListSequence: ["[]", "[]", "[]", "[]"] },
5516
+ textGeneration: {
5517
+ generatePrContent: (input) => {
5518
+ generatedInputs.push(input);
5519
+ return Effect.succeed({ title: "Feature PR", body: "Feature body" });
5520
+ },
5521
+ },
5522
+ });
5523
+ const result = yield* runStackedAction(manager, { cwd: worktreePath, action: "create_pr" });
5524
+ expect(result.pr.status).toBe("created");
5525
+
5526
+ // A branch created outside T3 has only gh's legacy short base setting.
5527
+ yield* runGit(worktreePath, ["checkout", "-b", "feature/legacy-local-base"]);
5528
+ yield* runGit(worktreePath, [
5529
+ "config",
5530
+ "branch.feature/legacy-local-base.gh-merge-base",
5531
+ "upstream/release",
5532
+ ]);
5533
+ yield* runGit(worktreePath, ["push", "-u", "origin", "feature/legacy-local-base"]);
5534
+ const legacyResult = yield* runStackedAction(manager, {
5535
+ cwd: worktreePath,
5536
+ action: "create_pr",
5537
+ });
5538
+ expect(legacyResult.pr.status).toBe("created");
5539
+ expect(generatedInputs).toHaveLength(2);
5540
+ for (const generated of generatedInputs) {
5541
+ expect.soft(generated.baseBranch).toBe("upstream/release");
5542
+ expect.soft(generated.commitSummary.trim()).toMatch(/^[a-f0-9]+ Feature commit$/);
5543
+ expect.soft(generated.diffSummary).toContain("feature.txt");
5544
+ expect.soft(generated.diffSummary).toContain("1 file changed, 1 insertion(+)");
5545
+ expect.soft(generated.diffPatch).toContain("+feature work");
5546
+ expect.soft(generated.diffPatch).not.toContain("local-base work");
5547
+ expect.soft(generated.diffPatch).not.toContain("remote-only work");
5548
+ expect.soft(generated.diffPatch).not.toContain("pull_request_template.md");
5549
+ expect.soft(generated.changeRequestTemplate).toBe("Local branch template");
5550
+ }
5551
+ expect
5552
+ .soft(ghCalls.filter((call) => call.startsWith("pr create ")))
5553
+ .toEqual([
5554
+ expect.stringContaining("pr create --base upstream/release --head feature/from-local"),
5555
+ expect.stringContaining(
5556
+ "pr create --base upstream/release --head feature/legacy-local-base",
5557
+ ),
5558
+ ]);
5559
+ }),
5560
+ );
5561
+
5562
+ it.effect.each(["main", "release/1.2"])(
5563
+ "generates PR content from branch changes when the remote base advances (%s)",
5564
+ (baseBranch) =>
5565
+ Effect.gen(function* () {
5566
+ const repoDir = yield* makeTempDir("t3code-git-manager-");
5567
+ yield* initRepo(repoDir);
5568
+ yield* runGit(repoDir, ["branch", "-m", baseBranch]);
5569
+ const remoteDir = yield* createBareRemote();
5570
+ yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5571
+ yield* runGit(repoDir, ["push", "-u", "origin", baseBranch]);
5572
+ yield* runGit(remoteDir, [
5573
+ "--git-dir=.",
5574
+ "symbolic-ref",
5575
+ "HEAD",
5576
+ `refs/heads/${baseBranch}`,
5577
+ ]);
5578
+
5579
+ const driver = yield* GitVcsDriver.GitVcsDriver;
5580
+ const worktreePath = NodePath.join(yield* makeTempDir("t3code-git-worktrees-"), "feature");
5581
+ yield* driver.createWorktree({
5582
+ cwd: repoDir,
5583
+ path: worktreePath,
5584
+ refName: baseBranch,
5585
+ newRefName: "feature/remote-base",
5586
+ baseRefName: baseBranch,
5587
+ });
5588
+ NodeFS.writeFileSync(NodePath.join(worktreePath, "feature.txt"), "feature\n");
5589
+ yield* runGit(worktreePath, ["add", "feature.txt"]);
5590
+ yield* runGit(worktreePath, ["commit", "-m", "Feature commit"]);
5591
+
5592
+ const peerDir = yield* makeTempDir("t3code-git-peer-");
5593
+ yield* runGit(peerDir, ["clone", remoteDir, "."]);
5594
+ yield* runGit(peerDir, ["config", "user.email", "peer@example.com"]);
5595
+ yield* runGit(peerDir, ["config", "user.name", "Peer User"]);
5596
+ NodeFS.writeFileSync(NodePath.join(peerDir, "remote.txt"), "remote\n");
5597
+ NodeFS.mkdirSync(NodePath.join(peerDir, ".github"));
5598
+ NodeFS.writeFileSync(
5599
+ NodePath.join(peerDir, ".github/pull_request_template.md"),
5600
+ "Updated main template",
5601
+ );
5602
+ yield* runGit(peerDir, ["add", "."]);
5603
+ yield* runGit(peerDir, ["commit", "-m", "Remote base commit"]);
5604
+ yield* runGit(peerDir, ["push", "origin", baseBranch]);
5605
+
5606
+ NodeFS.writeFileSync(NodePath.join(peerDir, "later-main.txt"), "unrelated\n");
5607
+ yield* runGit(peerDir, ["add", "later-main.txt"]);
5608
+ yield* runGit(peerDir, ["commit", "-m", "Later main commit"]);
5609
+ yield* runGit(peerDir, ["push", "origin", baseBranch]);
5610
+ yield* runGit(worktreePath, ["fetch", "origin"]);
5611
+ yield* runGit(worktreePath, ["rebase", `origin/${baseBranch}`]);
5612
+
5613
+ const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath });
5614
+ const changes = preview.sources.find((source) => source.kind === "branch-range")!;
5615
+ expect
5616
+ .soft(changes.files)
5617
+ .toEqual([{ path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }]);
5618
+ yield* runGit(worktreePath, ["push", "-u", "origin", "feature/remote-base"]);
5619
+
5620
+ const generatedInputs: TextGeneration.PrContentGenerationInput[] = [];
5621
+ const { manager, ghCalls } = yield* makeManager({
5622
+ ghScenario: {
5623
+ prListSequence: ["[]", "[]"],
5624
+ },
5625
+ textGeneration: {
5626
+ generatePrContent: (input) => {
5627
+ generatedInputs.push(input);
5628
+ return Effect.succeed({ title: "Feature PR", body: "Feature body" });
5629
+ },
5630
+ },
5631
+ });
5632
+
5633
+ const result = yield* runStackedAction(manager, {
5634
+ cwd: worktreePath,
5635
+ action: "create_pr",
5636
+ });
5637
+
5638
+ expect(result.pr.status).toBe("created");
5639
+ expect(generatedInputs).toHaveLength(1);
5640
+ const generated = generatedInputs[0]!;
5641
+ expect.soft(generated.baseBranch).toBe(baseBranch);
5642
+ expect.soft(generated.commitSummary.trim()).toMatch(/^[a-f0-9]+ Feature commit$/);
5643
+ expect.soft(generated.diffSummary).toContain("feature.txt");
5644
+ expect.soft(generated.diffSummary).toContain("1 file changed, 1 insertion(+)");
5645
+ expect.soft(generated.diffPatch).toContain("+feature");
5646
+ expect.soft(generated.diffPatch).not.toContain("remote.txt");
5647
+ expect.soft(generated.diffPatch).not.toContain("later-main.txt");
5648
+ expect.soft(generated.diffPatch).not.toContain("pull_request_template.md");
5649
+ expect.soft(generated.changeRequestTemplate).toBe("Updated main template");
5650
+ expect(
5651
+ ghCalls.some((call) =>
5652
+ call.includes(`pr create --base ${baseBranch} --head feature/remote-base`),
5653
+ ),
5654
+ ).toBe(true);
5655
+ }),
5656
+ );
5657
+
5658
it.effect(
5659
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
5660
() =>
apps/server/src/git/GitManager.ts
+37
-8
@@ -1967,16 +1967,39 @@ export const make = Effect.gen(function* () {
1967
};
1968
});
1969
1970
- const resolveBaseBranch = Effect.fn("resolveBaseBranch")(function* (
1970
+ const resolvePrBase = Effect.fn("resolvePrBase")(function* (
1971
cwd: string,
1972
branch: string,
1973
upstreamRef: string | null,
1974
headContext: Pick<BranchHeadContext, "isCrossRepository" | "remoteName">,
1975
) {
1976
+ const configuredRef = yield* gitCore.readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`);
1977
+ if (configuredRef?.startsWith("refs/heads/") || configuredRef?.startsWith("refs/remotes/")) {
1978
+ const configuredBranch = yield* gitCore.resolveBranchName(cwd, configuredRef);
1979
+ if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredRef };
1980
+ }
1981
+
1982
const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
1983
if (configured) {
1984
+ const localRef = configured.startsWith("refs/") ? configured : `refs/heads/${configured}`;
1985
+ const localBranch = yield* gitCore.resolveBranchName(cwd, localRef);
1986
+ if (localBranch) {
1987
+ const shadowsRemote =
1988
+ configured.includes("/") &&
1989
+ !configured.startsWith("refs/") &&
1990
+ (yield* gitCore.resolveBranchName(cwd, `refs/remotes/${configured}`)) !== null;
1991
+ return {
1992
+ baseBranch: localBranch,
1993
+ baseRef: configured.startsWith("refs/") || shadowsRemote ? localRef : localBranch,
1994
+ };
1995
+ }
1996
+ if (configured.includes("/") && !configured.startsWith("refs/")) {
1997
+ const remoteRef = `refs/remotes/${configured}`;
1998
+ const remoteBranch = yield* gitCore.resolveBranchName(cwd, remoteRef);
1999
+ if (remoteBranch) return { baseBranch: remoteBranch, baseRef: remoteRef };
2000
+ }
2001
const configuredBranch = yield* gitCore.resolveBranchName(cwd, configured);
1979
- if (configuredBranch) return configuredBranch;
2002
+ if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredBranch };
2003
}
2004
2005
if (upstreamRef && !headContext.isCrossRepository) {
@@ -1984,7 +2007,7 @@ export const make = Effect.gen(function* () {
2007
remoteName: headContext.remoteName,
2008
});
2009
if (upstreamBranch.length > 0 && upstreamBranch !== branch) {
1987
- return upstreamBranch;
2010
+ return { baseBranch: upstreamBranch, baseRef: upstreamBranch };
2011
}
2012
}
2013
@@ -1993,7 +2016,7 @@ export const make = Effect.gen(function* () {
2016
Effect.orElseSucceed(() => null),
2017
);
2018
if (defaultFromProvider) {
1996
- return defaultFromProvider;
2019
+ return { baseBranch: defaultFromProvider, baseRef: defaultFromProvider };
2020
}
2021
2022
const defaultFromRemote = yield* gitCore.resolvePrimaryRemoteName(cwd).pipe(
@@ -2001,16 +2024,17 @@ export const make = Effect.gen(function* () {
2024
Effect.orElseSucceed(() => null),
2025
);
2026
if (defaultFromRemote) {
2004
- return defaultFromRemote;
2027
+ return { baseBranch: defaultFromRemote, baseRef: defaultFromRemote };
2028
}
2029
2007
- return "main";
2030
+ return { baseBranch: "main", baseRef: "main" };
2031
});
2032
2033
const resolveBaseRangeRef = Effect.fn("resolveBaseRangeRef")(function* (
2034
cwd: string,
2035
baseBranch: string,
2036
) {
2037
+ if (baseBranch.startsWith("refs/")) return baseBranch;
2038
const remoteName = yield* gitCore
2039
.resolvePrimaryRemoteName(cwd)
2040
.pipe(Effect.orElseSucceed(() => null));
@@ -2235,13 +2259,18 @@ export const make = Effect.gen(function* () {
2259
};
2260
}
2261
2238
- const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);
2262
+ const { baseBranch, baseRef } = yield* resolvePrBase(
2263
+ cwd,
2264
+ branch,
2265
+ details.upstreamRef,
2266
+ headContext,
2267
+ );
2268
yield* emit({
2269
kind: "phase_started",
2270
phase: "pr",
2271
label: `Generating ${terms.shortLabel} content...`,
2272
});
2244
- const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);
2273
+ const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef);
2274
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
2275
const policy = yield* resolveStylePolicy(cwd, settings);
2276
const changeRequestTemplate =
apps/server/src/git/GitWorkflowService.ts
+16
@@ -98,6 +98,14 @@ export class GitWorkflowService extends Context.Service<
98
{ readonly commitSha: string; readonly remoteRefName: string },
99
GitCommandError
100
>;
101
+ readonly resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"];
102
+ readonly fetchWorktreeBaseCommit: (input: {
103
+ readonly cwd: string;
104
+ readonly refName: string;
105
+ }) => Effect.Effect<
106
+ { readonly commitSha: string; readonly remoteRefName: string } | null,
107
+ GitCommandError
108
+ >;
109
readonly removeWorktree: (
110
input: VcsRemoveWorktreeInput,
111
) => Effect.Effect<void, GitCommandError>;
@@ -392,6 +400,14 @@ export const make = Effect.gen(function* () {
400
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
401
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
402
),
403
+ resolveWorktreeBaseRemote: (input) =>
404
+ ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe(
405
+ Effect.andThen(git.resolveWorktreeBaseRemote(input)),
406
+ ),
407
+ fetchWorktreeBaseCommit: (input) =>
408
+ ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe(
409
+ Effect.andThen(git.fetchWorktreeBaseCommit(input)),
410
+ ),
411
removeWorktree: (input) =>
412
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
413
Effect.andThen(git.removeWorktree(input)),
apps/server/src/mcp/WorktreeMcpService.test.ts
+76
-50
@@ -15,11 +15,14 @@ import * as Deferred from "effect/Deferred";
15
import * as Effect from "effect/Effect";
16
import * as Exit from "effect/Exit";
17
import * as Fiber from "effect/Fiber";
18
+import * as FileSystem from "effect/FileSystem";
19
import * as Layer from "effect/Layer";
20
import * as Option from "effect/Option";
21
import * as Schema from "effect/Schema";
22
23
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
24
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
25
+import * as ServerConfig from "../config.ts";
26
import {
27
OrchestratorDispatchError,
28
OrchestratorProjectionError,
@@ -85,6 +88,7 @@ const project: Project = {
88
} as Project;
89
90
interface HarnessOptions {
91
+ readonly git?: Partial<GitWorkflowService.GitWorkflowService["Service"]>;
92
readonly thread?: ThreadFixture | null;
93
readonly threadReadError?: "projection" | "dispatch";
94
readonly capabilities?: ReadonlySet<McpInvocationContext.McpCapability>;
@@ -104,8 +108,8 @@ interface HarnessOptions {
108
readonly projectReadFails?: boolean;
109
readonly existingBranchWorktreePath?: string | null;
110
readonly createWorktreeFails?: boolean;
107
- readonly fetchRemoteFails?: boolean;
108
- readonly resolveRemoteFails?: boolean;
111
+ readonly fetchWorktreeBaseFails?: boolean;
112
+ readonly worktreeBaseMissing?: boolean;
113
readonly removeWorktreeFails?: boolean;
114
readonly deleteLocalBranchFails?: boolean;
115
readonly createWorktreeGate?: Effect.Effect<void>;
@@ -206,13 +210,12 @@ const makeHarness = (options: HarnessOptions = {}) => {
210
? (Effect.fail("simulated local branch deletion failure") as never)
211
: Effect.void,
212
);
209
- const fetchRemote = vi.fn((_: unknown) =>
210
- options.fetchRemoteFails ? (Effect.fail("simulated fetch failure") as never) : Effect.void,
211
- );
212
- const resolveRemoteTrackingCommit = vi.fn((_: unknown) =>
213
- options.resolveRemoteFails
214
- ? (Effect.fail("simulated remote resolve failure") as never)
215
- : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
213
+ const fetchWorktreeBaseCommit = vi.fn((_: unknown) =>
214
+ options.fetchWorktreeBaseFails
215
+ ? (Effect.fail("simulated fetch failure") as never)
216
+ : options.worktreeBaseMissing
217
+ ? Effect.succeed(null)
218
+ : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }),
219
);
220
const createWorktree = vi.fn(
221
(input: { readonly newRefName?: string | undefined; readonly path: string | null }) =>
@@ -303,11 +306,11 @@ const makeHarness = (options: HarnessOptions = {}) => {
306
listRefs,
307
listLocalBranchNames,
308
localStatus,
306
- fetchRemote,
307
- resolveRemoteTrackingCommit,
309
+ fetchWorktreeBaseCommit,
310
createWorktree,
311
removeWorktree,
312
deleteLocalBranch,
313
+ ...options.git,
314
} satisfies Partial<GitWorkflowService.GitWorkflowService["Service"]>),
315
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
316
runForThread,
@@ -325,8 +328,7 @@ const makeHarness = (options: HarnessOptions = {}) => {
328
scope,
329
dispatch,
330
sendToThread,
328
- fetchRemote,
329
- resolveRemoteTrackingCommit,
331
+ fetchWorktreeBaseCommit,
332
createWorktree,
333
removeWorktree,
334
deleteLocalBranch,
@@ -387,7 +389,7 @@ describe("t3_worktree_handoff", () => {
389
scriptName: "Setup",
390
});
391
390
- expect(harness.fetchRemote).not.toHaveBeenCalled();
392
+ expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled();
393
expect(harness.createWorktree).toHaveBeenCalledWith({
394
cwd: workspaceRoot,
395
refName: "dev",
@@ -487,46 +489,66 @@ describe("t3_worktree_handoff", () => {
489
});
490
});
491
490
- it.effect("starts from origin and honors an explicit baseRef", () => {
491
- const harness = makeHarness();
492
- return Effect.gen(function* () {
492
+ it.effect("uses the fetched commit and remote PR base for an explicit local alias", () =>
493
+ Effect.gen(function* () {
494
+ const fs = yield* FileSystem.FileSystem;
495
+ const git = yield* GitVcsDriver.GitVcsDriver;
496
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "handoff-remote-base-" });
497
+ const cwd = `${directory}/repo`;
498
+ const remote = `${directory}/remote.git`;
499
+ const worktreePath = `${directory}/worktree`;
500
+ yield* fs.makeDirectory(cwd);
501
+ const command = (at: string, args: string[]) =>
502
+ git.execute({ operation: "handoff-test", cwd: at, args });
503
+ yield* command(cwd, ["init", "-b", "stable"]);
504
+ yield* command(cwd, ["config", "user.name", "Test"]);
505
+ yield* command(cwd, ["config", "user.email", "test@example.test"]);
506
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "remote base"]);
507
+ const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
508
+ yield* command(cwd, ["init", "--bare", remote]);
509
+ yield* command(cwd, ["remote", "add", "upstream", remote]);
510
+ yield* command(cwd, ["push", "-u", "upstream", "stable:release"]);
511
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]);
512
+ const harness = makeHarness({
513
+ git: {
514
+ fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }),
515
+ createWorktree: (input) => git.createWorktree({ ...input, cwd, path: worktreePath }),
516
+ },
517
+ });
518
const result = yield* runHandoff(harness, {
494
- branch: "feature/from-origin",
495
- baseRef: "dev",
519
+ branch: "feature/from-remote",
520
+ baseRef: "stable",
521
startFromOrigin: true,
522
runSetupScript: false,
523
});
524
500
- expect(harness.fetchRemote).toHaveBeenCalledWith({
501
- cwd: workspaceRoot,
502
- remoteName: "origin",
503
- });
504
- expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({
505
- cwd: workspaceRoot,
506
- refName: "dev",
507
- fallbackRemoteName: "origin",
508
- });
509
- expect(harness.createWorktree).toHaveBeenCalledWith({
510
- cwd: workspaceRoot,
511
- refName: "abc123",
512
- newRefName: "feature/from-origin",
513
- baseRefName: "dev",
514
- path: null,
515
- });
516
- expect(harness.localStatus).toHaveBeenCalled();
517
- expect(harness.runForThread).not.toHaveBeenCalled();
518
- expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin");
525
+ expect(result.worktreePath).toBe(worktreePath);
526
expect(result.startedFromOrigin).toBe(true);
527
expect(result.setupScript).toEqual({ status: "skipped" });
521
- });
522
- });
528
+ expect((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(remoteHead);
529
+ const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath });
530
+ const comparisonBase = preview.sources.find(
531
+ (source) => source.kind === "branch-range",
532
+ )!.baseRef;
533
+ expect(
534
+ (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(),
535
+ ).toBe(remoteHead);
536
+ }).pipe(
537
+ Effect.provide(
538
+ GitVcsDriver.layer.pipe(
539
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "handoff-remote-git-" })),
540
+ Layer.provideMerge(NodeServices.layer),
541
+ ),
542
+ ),
543
+ ),
544
+ );
545
546
it.effect("uses the server setting for startFromOrigin when unspecified", () => {
547
const harness = makeHarness({ newWorktreesStartFromOrigin: true });
548
return Effect.gen(function* () {
549
const result = yield* runHandoff(harness, { branch: "feature/settings-origin" });
550
expect(result.startedFromOrigin).toBe(true);
529
- expect(harness.fetchRemote).toHaveBeenCalled();
551
+ expect(harness.fetchWorktreeBaseCommit).toHaveBeenCalled();
552
});
553
});
554
@@ -613,7 +635,7 @@ describe("t3_worktree_handoff", () => {
635
expect(error.message).toContain("already exists");
636
expect(error.message).toContain("/elsewhere/checkout");
637
expect(harness.createWorktree).not.toHaveBeenCalled();
616
- expect(harness.fetchRemote).not.toHaveBeenCalled();
638
+ expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled();
639
});
640
});
641
@@ -668,8 +690,8 @@ describe("t3_worktree_handoff", () => {
690
});
691
});
692
671
- it.effect("maps an origin fetch failure to operation_failed", () => {
672
- const harness = makeHarness({ fetchRemoteFails: true });
693
+ it.effect("maps a remote base fetch failure to operation_failed", () => {
694
+ const harness = makeHarness({ fetchWorktreeBaseFails: true });
695
return Effect.gen(function* () {
696
const exit = yield* Effect.exit(
697
runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }),
@@ -679,14 +701,18 @@ describe("t3_worktree_handoff", () => {
701
});
702
});
703
682
- it.effect("maps a remote-tracking resolve failure to operation_failed", () => {
683
- const harness = makeHarness({ resolveRemoteFails: true });
704
+ it.effect("falls back to the local base when no remote holds it", () => {
705
+ const harness = makeHarness({ worktreeBaseMissing: true });
706
return Effect.gen(function* () {
685
- const exit = yield* Effect.exit(
686
- runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }),
707
+ const result = yield* runHandoff(harness, {
708
+ branch: "feature/local-fallback",
709
+ baseRef: "dev",
710
+ startFromOrigin: true,
711
+ });
712
+ expect(harness.createWorktree).toHaveBeenCalledWith(
713
+ expect.objectContaining({ refName: "dev", baseRefName: "dev" }),
714
);
688
- expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" });
689
- expect(harness.createWorktree).not.toHaveBeenCalled();
715
+ expect(result.startedFromOrigin).toBe(false);
716
});
717
});
718
apps/server/src/mcp/WorktreeMcpService.ts
+11
-12
@@ -210,18 +210,17 @@ const make = Effect.gen(function* () {
210
const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
211
212
let worktreeBaseRef = baseRef;
213
+ let baseRefName = baseRef;
214
+ let startedFromOrigin = false;
215
if (startFromOrigin) {
214
- yield* gitWorkflow
215
- .fetchRemote({ cwd: projectCwd, remoteName: "origin" })
216
- .pipe(asOperationFailed("Unable to fetch origin"));
216
const resolvedRemoteBase = yield* gitWorkflow
218
- .resolveRemoteTrackingCommit({
219
- cwd: projectCwd,
220
- refName: baseRef,
221
- fallbackRemoteName: "origin",
222
- })
223
- .pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`));
224
- worktreeBaseRef = resolvedRemoteBase.commitSha;
217
+ .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef })
218
+ .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`));
219
+ if (resolvedRemoteBase !== null) {
220
+ worktreeBaseRef = resolvedRemoteBase.commitSha;
221
+ baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`;
222
+ startedFromOrigin = true;
223
+ }
224
}
225
226
const ids = yield* handoffIds(scope);
@@ -242,7 +241,7 @@ const make = Effect.gen(function* () {
241
cwd: projectCwd,
242
refName: worktreeBaseRef,
243
newRefName: input.branch,
245
- baseRefName: baseRef,
244
+ baseRefName,
245
path: null,
246
})
247
.pipe(asOperationFailed("Unable to create the worktree")),
@@ -385,7 +384,7 @@ const make = Effect.gen(function* () {
384
worktreePath,
385
branch: worktree.worktree.refName,
386
baseRef,
388
- startedFromOrigin: startFromOrigin,
387
+ startedFromOrigin,
388
setupScript,
389
continuation,
390
note:
apps/server/src/mcp/toolkits/project/handlers.ts
+2
-2
@@ -116,8 +116,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
116
code: "invalid_request",
117
message: `${error.message} No thread was created. Pass a branch, tag, or commit that exists there${
118
strategy.startFromOrigin === true
119
- ? "; the project has no origin remote to fetch it from."
120
- : ", or set startFromOrigin:true if it exists only on origin."
119
+ ? "; the project has no usable remote to fetch it from."
120
+ : ", or set startFromOrigin:true if it exists only on a remote."
121
}`,
122
}),
123
),
apps/server/src/mcp/toolkits/project/tools.ts
+1
-1
@@ -104,7 +104,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", {
104
const ThreadLaunchTool = Tool.make("t3_thread_launch", {
105
...shared,
106
description:
107
- 'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. For upstream commits, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread\'s current title. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.',
107
+ 'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. To fetch and start from the base branch\'s remote, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread\'s current title. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.',
108
parameters: Schema.Struct({
109
projectId: Schema.optional(ProjectId),
110
scratch: Schema.optional(
apps/server/src/mcp/toolkits/worktree/tools.ts
+1
-1
@@ -27,7 +27,7 @@ const WorktreeToolFailure = Schema.Union([WorktreeMcpFailure, OrchestratorMcpFai
27
28
const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", {
29
description:
30
- "Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from origin), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",
30
+ "Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from the base branch's remote), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.",
31
parameters: WorktreeMcpHandoffInput,
32
success: WorktreeMcpHandoffResult,
33
failure: WorktreeToolFailure,
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+141
-11
@@ -121,7 +121,7 @@ interface HarnessOptions {
121
readonly adapters?: ReadonlyArray<ProviderAdapter.ProviderAdapterV2["Service"]>;
122
readonly managedFolders?: Layer.Layer<ManagedProjectFolders.ManagedProjectFolders>;
123
readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
124
- readonly fetchRemote?: GitWorkflow.GitWorkflowService["Service"]["fetchRemote"];
124
+ readonly fetchWorktreeBaseCommit?: GitWorkflow.GitWorkflowService["Service"]["fetchWorktreeBaseCommit"];
125
readonly remoteExists?: GitWorkflow.GitWorkflowService["Service"]["remoteExists"];
126
readonly hasCommit?: GitWorkflow.GitWorkflowService["Service"]["hasCommit"];
127
readonly renameBranch?: GitWorkflow.GitWorkflowService["Service"]["renameBranch"];
@@ -198,13 +198,14 @@ function makeHarness(options: HarnessOptions = {}) {
198
Layer.mock(GitWorkflow.GitWorkflowService)({
199
createWorktree,
200
renameBranch,
201
- fetchRemote: options.fetchRemote ?? (() => Effect.void),
201
+ fetchWorktreeBaseCommit:
202
+ options.fetchWorktreeBaseCommit ??
203
+ (() => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" })),
204
hasCommit: options.hasCommit ?? (() => Effect.succeed(false)),
205
+ resolveWorktreeBaseRemote: () => Effect.succeed({ remoteName: "origin", branchName: "main" }),
206
remoteExists: options.remoteExists ?? (() => Effect.succeed(true)),
207
remoteBranchExists: () => Effect.succeed(true),
208
removeWorktree,
206
- resolveRemoteTrackingCommit: () =>
207
- Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
209
...options.git,
210
}),
211
Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, {
@@ -1735,11 +1736,139 @@ it.effect("renames a temporary branch on an existing worktree to a generated nam
1736
}),
1737
);
1738
1739
+it.effect.each(["stable", "upstream/release"])(
1740
+ "launches from %s with the fetched commit and remote PR base",
1741
+ (baseRef) =>
1742
+ Effect.gen(function* () {
1743
+ const fs = yield* FileSystem.FileSystem;
1744
+ const git = yield* GitVcsDriver.GitVcsDriver;
1745
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "launch-remote-base-" });
1746
+ const cwd = `${directory}/repo`;
1747
+ const remote = `${directory}/remote.git`;
1748
+ const worktreePath = `${directory}/worktree`;
1749
+ yield* fs.makeDirectory(cwd);
1750
+ const command = (at: string, args: string[]) =>
1751
+ git.execute({ operation: "launch-test", cwd: at, args });
1752
+ yield* command(cwd, ["init", "-b", "stable"]);
1753
+ yield* command(cwd, ["config", "user.name", "Test"]);
1754
+ yield* command(cwd, ["config", "user.email", "test@example.test"]);
1755
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "initial"]);
1756
+ const localHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
1757
+ yield* command(cwd, ["init", "--bare", remote]);
1758
+ yield* command(cwd, ["remote", "add", "upstream", remote]);
1759
+ yield* command(cwd, ["push", "-u", "upstream", "stable:release"]);
1760
+ yield* command(cwd, ["commit", "--allow-empty", "-m", "remote advance"]);
1761
+ yield* command(cwd, ["push", "upstream", "stable:release"]);
1762
+ const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim();
1763
+ yield* command(cwd, ["reset", "--hard", localHead]);
1764
+ yield* command(cwd, ["update-ref", "-d", "refs/remotes/upstream/release"]);
1765
+
1766
+ const setupStarted = yield* Deferred.make<void>();
1767
+ const harness = makeHarness({
1768
+ hasCommit: ({ refName }) =>
1769
+ command(cwd, ["rev-parse", "--verify", `${refName}^{commit}`]).pipe(
1770
+ Effect.as(true),
1771
+ Effect.orElseSucceed(() => false),
1772
+ ),
1773
+ git: {
1774
+ resolveWorktreeBaseRemote: (input) => git.resolveWorktreeBaseRemote({ ...input, cwd }),
1775
+ hasRefNamed: () => Effect.succeed(false),
1776
+ },
1777
+ fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }),
1778
+ createWorktree: (input, options) =>
1779
+ git.createWorktree({ ...input, cwd, path: worktreePath }, options),
1780
+ runSetup: () =>
1781
+ Deferred.succeed(setupStarted, undefined).pipe(
1782
+ Effect.as({ status: "no-script" as const }),
1783
+ ),
1784
+ });
1785
+ yield* Effect.gen(function* () {
1786
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
1787
+ const threads = yield* ThreadManagement.ThreadManagementService;
1788
+ const workspace = {
1789
+ type: "worktree" as const,
1790
+ baseRef,
1791
+ branch: "feature",
1792
+ startFromOrigin: true,
1793
+ };
1794
+ yield* launches.checkWorktreeBase({ projectId, workspaceStrategy: workspace });
1795
+ const launched = yield* launches.launch(
1796
+ launchInput({
1797
+ command: "command:launch:remote-base",
1798
+ thread: "thread:launch:remote-base",
1799
+ workspace,
1800
+ }),
1801
+ );
1802
+ yield* Deferred.await(setupStarted);
1803
+ const projection = yield* threads.getThreadProjection(launched.threadId);
1804
+ assert.equal(projection.thread.worktreePath, worktreePath);
1805
+ assert.equal(
1806
+ (yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim(),
1807
+ remoteHead,
1808
+ );
1809
+ const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath });
1810
+ const comparisonBase = preview.sources.find(
1811
+ (source) => source.kind === "branch-range",
1812
+ )!.baseRef;
1813
+ assert.equal(
1814
+ (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(),
1815
+ remoteHead,
1816
+ );
1817
+ }).pipe(Effect.provide(harness.layer));
1818
+ }).pipe(
1819
+ Effect.provide(
1820
+ GitVcsDriver.layer.pipe(
1821
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "launch-remote-git-" })),
1822
+ Layer.provideMerge(NodeServices.layer),
1823
+ ),
1824
+ ),
1825
+ ),
1826
+);
1827
+
1828
+it.effect.each([false, true])(
1829
+ "skips fetch only when no remote is selected (remote selected: %s)",
1830
+ (remoteSelected) =>
1831
+ Effect.gen(function* () {
1832
+ const setupStarted = yield* Deferred.make<void>();
1833
+ const fetchWorktreeBaseCommit = vi.fn(() => Effect.succeed(null));
1834
+ const harness = makeHarness({
1835
+ git: {
1836
+ resolveWorktreeBaseRemote: () =>
1837
+ Effect.succeed(remoteSelected ? { remoteName: "origin", branchName: "main" } : null),
1838
+ },
1839
+ fetchWorktreeBaseCommit,
1840
+ runSetup: () =>
1841
+ Deferred.succeed(setupStarted, undefined).pipe(
1842
+ Effect.as({ status: "no-script" as const }),
1843
+ ),
1844
+ });
1845
+ yield* Effect.gen(function* () {
1846
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
1847
+ const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
1848
+ const launched = yield* launches.launch(
1849
+ launchInput({
1850
+ command: "command:launch:fetch-progress",
1851
+ thread: "thread:launch:fetch-progress",
1852
+ workspace: { type: "worktree", baseRef: "main", startFromOrigin: true },
1853
+ }),
1854
+ );
1855
+ yield* Deferred.await(setupStarted);
1856
+ const snapshot = yield* tracker.get(launched.threadId);
1857
+ assert.equal(
1858
+ snapshot?.stages.find((stage) => stage.id === "fetch")?.status,
1859
+ remoteSelected ? "done" : "skipped",
1860
+ );
1861
+ assert.equal(fetchWorktreeBaseCommit.mock.calls.length, remoteSelected ? 1 : 0);
1862
+ assert.equal(harness.createWorktree.mock.calls[0]?.[0]?.refName, "main");
1863
+ }).pipe(Effect.provide(harness.layer));
1864
+ }),
1865
+);
1866
+
1867
it.effect("shows the fetch diagnosis when preparing a worktree from origin fails", () => {
1868
const detail =
1869
"Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.";
1870
const harness = makeHarness({
1742
- fetchRemote: () =>
1871
+ fetchWorktreeBaseCommit: () =>
1872
Effect.fail(
1873
new GitCommandError({
1874
operation: "GitVcsDriver.fetchRemote",
@@ -1787,7 +1916,7 @@ it.effect("shows the fetch diagnosis when preparing a worktree from origin fails
1916
it.effect("retries a failed workspace preparation on the same run", () => {
1917
let fetchFailures = 1;
1918
const harness = makeHarness({
1790
- fetchRemote: () =>
1919
+ fetchWorktreeBaseCommit: () =>
1920
fetchFailures-- > 0
1921
? Effect.fail(
1922
new GitCommandError({
@@ -1798,7 +1927,7 @@ it.effect("retries a failed workspace preparation on the same run", () => {
1927
exitCode: 1,
1928
}),
1929
)
1801
- : Effect.void,
1930
+ : Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }),
1931
});
1932
return Effect.gen(function* () {
1933
const launches = yield* ThreadLaunch.ThreadLaunchService;
@@ -1861,9 +1990,9 @@ it.effect.each(["fails", "is interrupted"] as const)(
1990
const allowFetch = yield* Deferred.make<void>();
1991
let fetchFailures = 1;
1992
const harness = makeHarness({
1864
- fetchRemote: () =>
1993
+ fetchWorktreeBaseCommit: () =>
1994
fetchFailures-- <= 0
1866
- ? Effect.void
1995
+ ? Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" })
1996
: Deferred.succeed(fetchEntered, undefined).pipe(
1997
Effect.andThen(Deferred.await(allowFetch)),
1998
Effect.andThen(
@@ -1943,7 +2072,7 @@ it.effect.each(["failed", "interrupted"] as const)(
2072
(ending) => {
2073
let fetchEntered: Deferred.Deferred<void> | null = null;
2074
const harness = makeHarness({
1946
- fetchRemote: () =>
2075
+ fetchWorktreeBaseCommit: () =>
2076
ending === "interrupted"
2077
? Deferred.succeed(fetchEntered!, undefined).pipe(Effect.andThen(Effect.never))
2078
: Effect.fail(
@@ -3034,7 +3163,8 @@ it.effect.each([
3163
const harness = makeHarness({
3164
hasCommit: ({ refName }) => Effect.succeed(refName === "HEAD"),
3165
git: {
3037
- remoteExists: () => Effect.succeed(testCase.origin),
3166
+ resolveWorktreeBaseRemote: () =>
3167
+ Effect.succeed(testCase.origin ? { remoteName: "origin", branchName: "main" } : null),
3168
hasRefNamed: () => Effect.succeed(false),
3169
},
3170
});
apps/server/src/orchestration-v2/ThreadLaunchService.ts
+14
-26
@@ -269,7 +269,7 @@ const make = Effect.gen(function* () {
269
return undefined;
270
if (
271
strategy.startFromOrigin === true &&
272
- (yield* git.remoteExists({ cwd, remoteName: "origin" }))
272
+ (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null
273
)
274
return undefined;
275
// `git worktree add` also starts from a remote-tracking branch of that
@@ -390,41 +390,29 @@ const make = Effect.gen(function* () {
390
.pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
391
}
392
let startRef = input.workspaceStrategy.baseRef;
393
- const startFromOrigin =
393
+ let baseRefName = input.workspaceStrategy.baseRef;
394
+ const shouldFetch =
395
input.workspaceStrategy.startFromOrigin === true &&
396
(yield* git
396
- .remoteExists({ cwd: project.workspaceRoot, remoteName: "origin" })
397
- .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))));
398
- yield* setupTracker.stageStatus(threadId, "fetch", startFromOrigin ? "running" : "skipped");
399
- if (startFromOrigin) {
400
- yield* git
401
- .fetchRemote({
397
+ .resolveWorktreeBaseRemote({
398
cwd: project.workspaceRoot,
403
- remoteName: "origin",
399
refName: input.workspaceStrategy.baseRef,
400
})
406
- .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
407
- const remoteBaseExists = yield* git
408
- .remoteBranchExists({
401
+ .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)))) !== null;
402
+ yield* setupTracker.stageStatus(threadId, "fetch", shouldFetch ? "running" : "skipped");
403
+ if (shouldFetch) {
404
+ const remoteBase = yield* git
405
+ .fetchWorktreeBaseCommit({
406
cwd: project.workspaceRoot,
407
refName: input.workspaceStrategy.baseRef,
411
- remoteName: "origin",
408
})
409
.pipe(Effect.mapError(mapError(input, "provision-worktree", threadId)));
414
- if (remoteBaseExists) {
415
- startRef = yield* git
416
- .resolveRemoteTrackingCommit({
417
- cwd: project.workspaceRoot,
418
- refName: input.workspaceStrategy.baseRef,
419
- fallbackRemoteName: "origin",
420
- })
421
- .pipe(
422
- Effect.map((resolved) => resolved.commitSha),
423
- Effect.mapError(mapError(input, "provision-worktree", threadId)),
424
- );
410
+ if (remoteBase !== null) {
411
+ startRef = remoteBase.commitSha;
412
+ baseRefName = `refs/remotes/${remoteBase.remoteRefName}`;
413
}
414
}
427
- if (startFromOrigin) yield* setupTracker.stageStatus(threadId, "fetch", "done");
415
+ if (shouldFetch) yield* setupTracker.stageStatus(threadId, "fetch", "done");
416
if (
417
branch !== null &&
418
isTemporaryWorktreeBranch(branch) &&
@@ -444,7 +432,7 @@ const make = Effect.gen(function* () {
432
cwd: project.workspaceRoot,
433
refName: startRef,
434
newRefName: branch!,
447
- baseRefName: input.workspaceStrategy.baseRef,
435
+ baseRefName,
436
path: null,
437
},
438
{
apps/server/src/vcs/GitVcsDriver.ts
+12
@@ -279,6 +279,11 @@ export interface GitResolveRemoteTrackingCommitResult {
279
remoteRefName: string;
280
}
281
282
+export interface GitFetchWorktreeBaseCommitInput {
283
+ cwd: string;
284
+ refName: string;
285
+}
286
+
287
export interface GitSetBranchUpstreamInput {
288
cwd: string;
289
branch: string;
@@ -372,6 +377,13 @@ export class GitVcsDriver extends Context.Service<
377
readonly resolveRemoteTrackingCommit: (
378
input: GitResolveRemoteTrackingCommitInput,
379
) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
380
+ readonly resolveWorktreeBaseRemote: (
381
+ input: GitFetchWorktreeBaseCommitInput,
382
+ ) => Effect.Effect<{ remoteName: string; branchName: string } | null, GitCommandError>;
383
+ /** Fetches the configured upstream, explicit remote ref, or origin; null uses the local base. */
384
+ readonly fetchWorktreeBaseCommit: (
385
+ input: GitFetchWorktreeBaseCommitInput,
386
+ ) => Effect.Effect<GitResolveRemoteTrackingCommitResult | null, GitCommandError>;
387
readonly fetchRemoteBranch: (
388
input: GitFetchRemoteBranchInput,
389
) => Effect.Effect<void, GitCommandError>;
apps/server/src/vcs/GitVcsDriverCore.test.ts
+151
-9
@@ -2422,21 +2422,21 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2422
yield* git(cwd, [
2423
"config",
2424
"branch.feature/configured-base.gh-merge-base",
2425
- "upstream/main",
2425
+ "refs/remotes/upstream/main",
2426
]);
2427
yield* writeTextFile(cwd, "upstream.txt", "feature edits upstream file\n");
2428
for (const shadowRef of ["refs/heads/upstream/main", "refs/tags/upstream/main"]) {
2429
yield* git(cwd, ["update-ref", shadowRef, "HEAD~2"]);
2430
const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true });
2431
assert.deepStrictEqual(status.branchChanges, {
2432
- baseRef: "upstream/main",
2432
+ baseRef: "refs/remotes/upstream/main",
2433
insertions: 2,
2434
deletions: 1,
2435
});
2436
assert.strictEqual(status.aheadCount, 1);
2437
const preview = yield* driver.getReviewDiffPreview({ cwd });
2438
const changes = preview.sources.find((source) => source.kind === "branch-range")!;
2439
- assert.strictEqual(changes.baseRef, "upstream/main");
2439
+ assert.strictEqual(changes.baseRef, "refs/remotes/upstream/main");
2440
assert.deepStrictEqual(changes.files, [
2441
{ path: "feature.txt", previousPath: null, additions: 1, deletions: 0 },
2442
{ path: "upstream.txt", previousPath: null, additions: 1, deletions: 1 },
@@ -3630,17 +3630,22 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3630
const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]);
3631
const path = yield* Path.Path;
3632
const driver = yield* GitVcsDriver.GitVcsDriver;
3633
+ const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote");
3634
yield* driver.createWorktree({
3635
cwd,
3635
- path: path.join(yield* makeTmpDir("git-worktrees-"), "remote"),
3636
+ path: worktreePath,
3637
refName: commit,
3638
newRefName: "feature/remote",
3639
baseRefName: baseRef,
3640
});
3641
3642
+ const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath });
3643
+ const comparisonBase = preview.sources.find(
3644
+ (source) => source.kind === "branch-range",
3645
+ )!.baseRef;
3646
assert.equal(
3642
- yield* driver.readConfigValue(cwd, "branch.feature/remote.gh-merge-base"),
3643
- "release/v2",
3647
+ yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]),
3648
+ commit,
3649
);
3650
}),
3651
);
@@ -4553,9 +4558,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4558
});
4559
4560
assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead);
4561
+ const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath });
4562
+ const comparisonBase = preview.sources.find(
4563
+ (source) => source.kind === "branch-range",
4564
+ )!.baseRef;
4565
assert.equal(
4557
- yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.gh-merge-base"),
4558
- initialBranch,
4566
+ yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]),
4567
+ remoteHead,
4568
);
4569
assert.equal(
4570
yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.remote"),
@@ -4572,6 +4581,123 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4581
}),
4582
);
4583
4584
+ it.effect("fetches the selected worktree base for Changes", () =>
4585
+ Effect.gen(function* () {
4586
+ const cwd = yield* makeTmpDir();
4587
+ const fork = yield* makeTmpDir("git-fork-");
4588
+ const source = yield* makeTmpDir("git-source-");
4589
+ yield* initRepoWithCommit(cwd);
4590
+ yield* git(cwd, ["branch", "-M", "stable"]);
4591
+ yield* git(fork, ["init", "--bare"]);
4592
+ yield* git(source, ["init", "--bare"]);
4593
+ yield* git(cwd, ["remote", "add", "origin", fork]);
4594
+ yield* git(cwd, ["remote", "add", "upstream", source]);
4595
+ yield* git(cwd, ["push", "origin", "stable"]);
4596
+ yield* git(cwd, ["push", "-u", "upstream", "stable:release"]);
4597
+ const localHead = yield* git(cwd, ["rev-parse", "HEAD"]);
4598
+
4599
+ yield* writeTextFile(cwd, "fork.txt", "fork-only work\n");
4600
+ yield* git(cwd, ["add", "fork.txt"]);
4601
+ yield* git(cwd, ["commit", "-m", "fork work"]);
4602
+ yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release"]);
4603
+ yield* git(cwd, ["reset", "--hard", localHead]);
4604
+
4605
+ // Advance the source without updating this checkout's tracking refs.
4606
+ yield* writeTextFile(cwd, "upstream.txt", "upstream-only work\n");
4607
+ yield* git(cwd, ["add", "upstream.txt"]);
4608
+ yield* git(cwd, ["commit", "-m", "source advance"]);
4609
+ const remoteHead = yield* git(cwd, ["rev-parse", "HEAD"]);
4610
+ yield* git(source, ["--git-dir=.", "fetch", cwd, "stable:refs/heads/release"]);
4611
+ yield* git(cwd, ["reset", "--hard", localHead]);
4612
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4613
+
4614
+ const fetched = yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "stable" });
4615
+ assert.deepEqual(fetched, {
4616
+ commitSha: remoteHead,
4617
+ remoteRefName: "upstream/release",
4618
+ });
4619
+ yield* git(cwd, ["update-ref", "-d", "refs/remotes/upstream/release"]);
4620
+ assert.deepEqual(
4621
+ yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "upstream/release" }),
4622
+ { commitSha: remoteHead, remoteRefName: "upstream/release" },
4623
+ );
4624
+ yield* git(cwd, ["branch", "--unset-upstream", "stable"]);
4625
+ assert.deepEqual(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "stable" }), {
4626
+ commitSha: localHead,
4627
+ remoteRefName: "origin/stable",
4628
+ });
4629
+ assert.equal(yield* git(cwd, ["rev-parse", "stable"]), localHead);
4630
+
4631
+ const path = yield* Path.Path;
4632
+ const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "feature");
4633
+ yield* driver.createWorktree({
4634
+ cwd,
4635
+ path: worktreePath,
4636
+ refName: fetched!.commitSha,
4637
+ newRefName: "feature/from-upstream",
4638
+ baseRefName: `refs/remotes/${fetched!.remoteRefName}`,
4639
+ });
4640
+ assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead);
4641
+ yield* writeTextFile(worktreePath, "feature.txt", "feature work\n");
4642
+ yield* git(worktreePath, ["add", "feature.txt"]);
4643
+ yield* git(worktreePath, ["commit", "-m", "feature work"]);
4644
+
4645
+ const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath });
4646
+ const changes = preview.sources.find((source) => source.kind === "branch-range")!;
4647
+ assert.deepStrictEqual(changes.files, [
4648
+ { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 },
4649
+ ]);
4650
+ assert.include(changes.diff, "+feature work");
4651
+ assert.notInclude(changes.diff, "upstream-only work");
4652
+ const status = yield* driver.statusDetailsLocal(worktreePath, {
4653
+ includeBranchChanges: true,
4654
+ });
4655
+ assert.strictEqual(status.aheadCount, 1);
4656
+ assert.strictEqual(status.branchChanges?.insertions, 1);
4657
+ assert.strictEqual(status.branchChanges?.deletions, 0);
4658
+ // gh pr create consumes this setting verbatim as the hosted target branch.
4659
+ assert.equal(
4660
+ yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.gh-merge-base"),
4661
+ "release",
4662
+ );
4663
+ assert.equal(changes.baseRef, "upstream/release");
4664
+ }),
4665
+ );
4666
+
4667
+ it.effect("does not use a deleted remote worktree base's stale tracking commit", () =>
4668
+ Effect.gen(function* () {
4669
+ const cwd = yield* makeTmpDir();
4670
+ const remote = yield* makeTmpDir("git-remote-");
4671
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
4672
+ yield* git(remote, ["init", "--bare"]);
4673
+ yield* git(cwd, ["remote", "add", "origin", remote]);
4674
+ yield* git(cwd, ["push", "-u", "origin", `${initialBranch}:release`]);
4675
+ yield* git(remote, ["--git-dir=.", "update-ref", "-d", "refs/heads/release"]);
4676
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4677
+
4678
+ assert.equal(
4679
+ yield* git(cwd, ["rev-parse", "refs/remotes/origin/release"]),
4680
+ yield* git(cwd, ["rev-parse", "HEAD"]),
4681
+ );
4682
+ assert.isNull(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: initialBranch }));
4683
+ yield* git(cwd, ["remote", "remove", "origin"]);
4684
+ assert.isNull(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: initialBranch }));
4685
+ }),
4686
+ );
4687
+
4688
+ it.effect("fails instead of falling back when the worktree base remote is unreachable", () =>
4689
+ Effect.gen(function* () {
4690
+ const cwd = yield* makeTmpDir();
4691
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
4692
+ yield* git(cwd, ["remote", "add", "origin", `${cwd}/missing.git`]);
4693
+ const driver = yield* GitVcsDriver.GitVcsDriver;
4694
+ const error = yield* driver
4695
+ .fetchWorktreeBaseCommit({ cwd, refName: initialBranch })
4696
+ .pipe(Effect.flip);
4697
+ assert.equal(error._tag, "GitCommandError");
4698
+ }),
4699
+ );
4700
+
4701
it.effect("pushes with upstream setup and skips when already up to date", () =>
4702
Effect.gen(function* () {
4703
const cwd = yield* makeTmpDir();
@@ -4757,6 +4883,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4883
Effect.gen(function* () {
4884
const cwd = yield* makeTmpDir();
4885
const remote = yield* makeTmpDir("git-remote-");
4886
+ const upstream = yield* makeTmpDir("git-upstream-");
4887
yield* initRepoWithCommit(cwd);
4888
const driver = yield* GitVcsDriver.GitVcsDriver;
4889
yield* git(cwd, ["branch", "-M", "main"]);
@@ -4766,7 +4893,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4893
yield* git(cwd, ["checkout", "-b", "dev"]);
4894
yield* git(cwd, ["push", "-u", "origin", "dev"]);
4895
const devSha = yield* git(cwd, ["rev-parse", "HEAD"]);
4769
- yield* git(cwd, ["checkout", "-b", "feature/x", "origin/dev"]);
4896
+ yield* git(upstream, ["init", "--bare"]);
4897
+ yield* git(cwd, ["remote", "add", "upstream", upstream]);
4898
+ yield* writeTextFile(cwd, "upstream.txt", "upstream work\n");
4899
+ yield* git(cwd, ["add", "-A"]);
4900
+ yield* driver.commit(cwd, "Add upstream update", "");
4901
+ yield* git(cwd, ["push", "upstream", "dev"]);
4902
+ const upstreamDevSha = yield* git(cwd, ["rev-parse", "HEAD"]);
4903
+ yield* git(cwd, ["checkout", "-b", "feature/x", "upstream/dev"]);
4904
yield* writeTextFile(cwd, "feature.txt", "feature\n");
4905
yield* git(cwd, ["add", "-A"]);
4906
yield* driver.commit(cwd, "Add feature", "");
@@ -4784,11 +4918,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4918
"Add feature",
4919
);
4920
assert.equal(yield* git(remote, ["--git-dir=.", "rev-parse", "dev"]), devSha);
4921
+ assert.equal(yield* git(upstream, ["--git-dir=.", "rev-parse", "dev"]), upstreamDevSha);
4922
assert.equal(
4923
yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
4924
"origin/feature/x",
4925
);
4926
assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.gh-merge-base"), "dev");
4927
+
4928
+ const preview = yield* driver.getReviewDiffPreview({ cwd });
4929
+ const changes = preview.sources.find((source) => source.kind === "branch-range")!;
4930
+ assert.deepStrictEqual(changes.files, [
4931
+ { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 },
4932
+ ]);
4933
+ assert.equal(changes.baseRef, "upstream/dev");
4934
}),
4935
);
4936
apps/server/src/vcs/GitVcsDriverCore.ts
+221
-109
@@ -1656,19 +1656,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1656
return remoteName;
1657
});
1658
1659
- const resolveRemoteBaseRef = Effect.fn("resolveRemoteBaseRef")(function* (
1659
+ const resolveComparisonBaseRef = Effect.fn("resolveComparisonBaseRef")(function* (
1660
cwd: string,
1661
baseRef: string,
1662
) {
1663
- if (!baseRef.includes("/") || baseRef.startsWith("refs/")) return null;
1664
- const comparisonRef = `refs/remotes/${baseRef}`;
1665
- const remoteBase = yield* executeGit(
1666
- "GitVcsDriver.resolveRemoteBaseRef",
1663
+ const comparisonRef =
1664
+ baseRef.startsWith("refs/heads/") || baseRef.startsWith("refs/remotes/")
1665
+ ? baseRef
1666
+ : baseRef.includes("/") && !baseRef.startsWith("refs/")
1667
+ ? `refs/remotes/${baseRef}`
1668
+ : null;
1669
+ if (comparisonRef === null) return null;
1670
+ const resolved = yield* executeGit(
1671
+ "GitVcsDriver.resolveComparisonBaseRef",
1672
cwd,
1673
["show-ref", "--verify", "--quiet", comparisonRef],
1674
{ allowNonZeroExit: true },
1675
);
1671
- return remoteBase.exitCode === 0 ? { baseRef, comparisonRef } : null;
1676
+ return resolved.exitCode === 0 ? { baseRef, comparisonRef } : null;
1677
});
1678
1679
// Tracking may point to a different remote than the primary one. Resolve its
@@ -1693,16 +1698,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1698
refName: string,
1699
options?: { readonly allowRemoteOfCurrent?: boolean },
1700
) {
1696
- const configuredBaseBranch = yield* runGitStdout(
1697
- "GitVcsDriver.resolveBaseBranchForNoUpstream.config",
1698
- cwd,
1699
- ["config", "--get", `branch.${refName}.gh-merge-base`],
1700
- true,
1701
- ).pipe(Effect.map((stdout) => stdout.trim()));
1701
+ const configuredBaseRef = yield* readConfigValue(cwd, `branch.${refName}.t3-merge-base-ref`);
1702
+ if (
1703
+ configuredBaseRef?.startsWith("refs/heads/") ||
1704
+ configuredBaseRef?.startsWith("refs/remotes/")
1705
+ ) {
1706
+ const base = yield* resolveComparisonBaseRef(cwd, configuredBaseRef);
1707
+ if (base !== null) {
1708
+ const shortRef = configuredBaseRef.replace(/^refs\/remotes\//, "");
1709
+ return {
1710
+ ...base,
1711
+ baseRef: (yield* branchExists(cwd, shortRef)) ? configuredBaseRef : shortRef,
1712
+ };
1713
+ }
1714
+ }
1715
1703
- // Keep the configured remote and compare its exact ref even when a local ref shadows it.
1704
- const configuredRemoteBase = yield* resolveRemoteBaseRef(cwd, configuredBaseBranch);
1705
- if (configuredRemoteBase !== null) return configuredRemoteBase;
1716
+ const configuredBaseBranch =
1717
+ (yield* readConfigValue(cwd, `branch.${refName}.gh-merge-base`)) ?? "";
1718
+ const configuredBase = yield* resolveComparisonBaseRef(cwd, configuredBaseBranch);
1719
+ if (
1720
+ configuredBase !== null &&
1721
+ configuredBaseBranch.includes("/") &&
1722
+ !configuredBaseBranch.startsWith("refs/") &&
1723
+ (yield* branchExists(cwd, configuredBaseBranch))
1724
+ ) {
1725
+ const comparisonRef = `refs/heads/${configuredBaseBranch}`;
1726
+ return { baseRef: comparisonRef, comparisonRef };
1727
+ }
1728
+ if (configuredBase !== null) return configuredBase;
1729
1730
const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(
1731
Effect.orElseSucceed(() => null),
@@ -2496,9 +2519,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2519
);
2520
const remoteName = publishRemoteName ?? currentUpstream.remoteName;
2521
const publishBranch = yield* resolvePublishBranchName(cwd, branch);
2499
- // `-u` retargets the upstream to the published branch, so keep the
2500
- // base recorded first; base resolution reads gh-merge-base before the
2501
- // upstream ref.
2522
+ // Publishing retargets the upstream, so preserve its comparison base first.
2523
const configuredMergeBase = yield* runGitStdout(
2524
"GitVcsDriver.pushCurrentBranch.readMergeBase",
2525
cwd,
@@ -2511,6 +2532,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2532
`branch.${branch}.gh-merge-base`,
2533
currentUpstream.branchName,
2534
]);
2535
+ if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {
2536
+ yield* runGit("GitVcsDriver.pushCurrentBranch.recordComparisonRef", cwd, [
2537
+ "config",
2538
+ `branch.${branch}.t3-merge-base-ref`,
2539
+ `refs/remotes/${currentUpstream.upstreamRef}`,
2540
+ ]);
2541
+ }
2542
}
2543
yield* runGit(
2544
"GitVcsDriver.pushCurrentBranch.pushOwnBranch",
@@ -2777,7 +2805,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2805
) {
2806
const base =
2807
explicitBaseRef !== undefined
2780
- ? ((yield* resolveRemoteBaseRef(cwd, explicitBaseRef)) ?? {
2808
+ ? ((yield* resolveComparisonBaseRef(cwd, explicitBaseRef)) ?? {
2809
baseRef: explicitBaseRef,
2810
comparisonRef:
2811
!explicitBaseRef.startsWith("refs/") && (yield* branchExists(cwd, explicitBaseRef))
@@ -3155,7 +3183,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3183
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
3184
);
3185
3158
- const resolveBranchName = Effect.fn("GitVcsDriver.resolveBranchName")(function* (
3186
+ const resolveBranchBase = Effect.fn("GitVcsDriver.resolveBranchBase")(function* (
3187
cwd: string,
3188
refName: string,
3189
) {
@@ -3170,19 +3198,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3198
Effect.orElseSucceed(() => null),
3199
);
3200
return remoteName && (yield* remoteBranchExists({ cwd, remoteName, refName }))
3173
- ? refName
3201
+ ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName }
3202
: null;
3203
}
3204
const ref = result.stdout.trim();
3177
- if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
3205
+ if (ref.startsWith("refs/heads/")) {
3206
+ const branchName = ref.slice("refs/heads/".length);
3207
+ return { baseRef: ref, branchName };
3208
+ }
3209
if (!ref.startsWith("refs/remotes/")) return null;
3210
const remoteNames = yield* listRemoteNames(cwd);
3180
- return (
3181
- parseRemoteRefWithRemoteNames(
3182
- ref.slice("refs/remotes/".length),
3183
- remoteNames.toSorted((left, right) => right.length - left.length),
3184
- )?.branchName ?? null
3211
+ const remoteRef = parseRemoteRefWithRemoteNames(
3212
+ ref.slice("refs/remotes/".length),
3213
+ remoteNames.toSorted((left, right) => right.length - left.length),
3214
);
3215
+ return remoteRef ? { baseRef: ref, branchName: remoteRef.branchName } : null;
3216
+ });
3217
+
3218
+ const resolveBranchName = Effect.fn("GitVcsDriver.resolveBranchName")(function* (
3219
+ cwd: string,
3220
+ refName: string,
3221
+ ) {
3222
+ const base = yield* resolveBranchBase(cwd, refName);
3223
+ return base?.branchName ?? null;
3224
});
3225
3226
const readGitRefsSnapshot = Effect.fn("readGitRefsSnapshot")(function* (gitCommonDir: string) {
@@ -3608,13 +3646,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3646
}
3647
3648
if (input.newRefName && input.baseRefName) {
3611
- const baseBranch = yield* resolveBranchName(input.cwd, input.baseRefName);
3612
- if (baseBranch) {
3613
- yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
3614
- "config",
3615
- `branch.${input.newRefName}.gh-merge-base`,
3616
- baseBranch,
3617
- ]).pipe(
3649
+ const base = yield* resolveBranchBase(input.cwd, input.baseRefName);
3650
+ if (base) {
3651
+ yield* Effect.gen(function* () {
3652
+ yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
3653
+ "config",
3654
+ `branch.${input.newRefName}.gh-merge-base`,
3655
+ base.branchName,
3656
+ ]);
3657
+ if (base.baseRef.startsWith("refs/remotes/")) {
3658
+ // gh consumes its key as a provider branch; T3 also needs the selected remote.
3659
+ yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
3660
+ "config",
3661
+ `branch.${input.newRefName}.t3-merge-base-ref`,
3662
+ base.baseRef,
3663
+ ]);
3664
+ }
3665
+ }).pipe(
3666
Effect.catchTags({
3667
GitCommandError: () =>
3668
Effect.logWarning(
@@ -3742,83 +3790,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3790
return { headCommit: input.targetCommit, moved: true, onTarget: true };
3791
});
3792
3745
- const fetchRemote: GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"] = Effect.fn("fetchRemote")(
3746
- function* (input) {
3747
- const args = ["fetch", "--quiet", "--", input.remoteName];
3748
- const options = {
3749
- env: STATUS_UPSTREAM_REFRESH_ENV,
3750
- fallbackErrorDetail: `git fetch ${input.remoteName} failed`,
3751
- };
3752
- // Another fetch in the same repository, such as the background status
3753
- // poll, can win the race for a remote-tracking ref. The loser fails, but
3754
- // the ref is free again by the time a rerun needs it, so retry once.
3755
- const runFetch = (fetchArgs: readonly string[]) => {
3756
- const run = executeGitWithStableDiagnostics(
3757
- "GitVcsDriver.fetchRemote",
3758
- input.cwd,
3759
- fetchArgs,
3760
- {
3761
- ...options,
3762
- allowNonZeroExit: true,
3763
- },
3764
- );
3765
- return run.pipe(
3766
- Effect.flatMap((result) =>
3767
- result.exitCode !== 0 && isRefLockFailure(result.stderr) ? run : Effect.succeed(result),
3768
- ),
3769
- );
3770
- };
3771
- const fetchAll = runFetch(args).pipe(
3793
+ const fetchRemote = Effect.fn("fetchRemote")(function* (input: GitVcsDriver.GitFetchRemoteInput) {
3794
+ const args = ["fetch", "--quiet", "--", input.remoteName];
3795
+ const options = {
3796
+ env: STATUS_UPSTREAM_REFRESH_ENV,
3797
+ fallbackErrorDetail: `git fetch ${input.remoteName} failed`,
3798
+ };
3799
+ // Another fetch in the same repository, such as the background status
3800
+ // poll, can win the race for a remote-tracking ref. The loser fails, but
3801
+ // the ref is free again by the time a rerun needs it, so retry once.
3802
+ const runFetch = (fetchArgs: readonly string[]) => {
3803
+ const run = executeGitWithStableDiagnostics(
3804
+ "GitVcsDriver.fetchRemote",
3805
+ input.cwd,
3806
+ fetchArgs,
3807
+ {
3808
+ ...options,
3809
+ allowNonZeroExit: true,
3810
+ },
3811
+ );
3812
+ return run.pipe(
3813
Effect.flatMap((result) =>
3773
- result.exitCode === 0
3774
- ? Effect.void
3775
- : Effect.fail(
3776
- new GitCommandError({
3777
- ...gitCommandContext({
3778
- operation: "GitVcsDriver.fetchRemote",
3779
- cwd: input.cwd,
3780
- args,
3781
- }),
3782
- detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3783
- ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3784
- stdoutLength: result.stdout.length,
3785
- stderrLength: result.stderr.length,
3786
- }),
3787
- ),
3814
+ result.exitCode !== 0 && isRefLockFailure(result.stderr) ? run : Effect.succeed(result),
3815
),
3816
);
3790
- if (input.refName === undefined) {
3791
- return yield* fetchAll.pipe(Effect.asVoid);
3792
- }
3793
- const branch =
3794
- parseRemoteRefWithRemoteNames(input.refName, [input.remoteName])?.branchName ??
3795
- input.refName;
3796
- const scopedArgs = [
3797
- ...args,
3798
- `+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`,
3799
- ];
3800
- const result = yield* runFetch(scopedArgs);
3801
- if (result.exitCode === 0) return;
3802
- if (
3803
- result.stderr
3804
- .split(/\r?\n/)
3805
- .includes(`fatal: couldn't find remote ref refs/heads/${branch}`)
3806
- ) {
3807
- return yield* fetchAll.pipe(Effect.asVoid);
3808
- }
3809
- return yield* new GitCommandError({
3810
- ...gitCommandContext({
3811
- operation: "GitVcsDriver.fetchRemote",
3812
- cwd: input.cwd,
3813
- args: scopedArgs,
3814
- }),
3815
- detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3816
- ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3817
- stdoutLength: result.stdout.length,
3818
- stderrLength: result.stderr.length,
3819
- });
3820
- },
3821
- );
3817
+ };
3818
+ const fetchAll = runFetch(args).pipe(
3819
+ Effect.flatMap((result) =>
3820
+ result.exitCode === 0
3821
+ ? Effect.void
3822
+ : Effect.fail(
3823
+ new GitCommandError({
3824
+ ...gitCommandContext({
3825
+ operation: "GitVcsDriver.fetchRemote",
3826
+ cwd: input.cwd,
3827
+ args,
3828
+ }),
3829
+ detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3830
+ ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3831
+ stdoutLength: result.stdout.length,
3832
+ stderrLength: result.stderr.length,
3833
+ }),
3834
+ ),
3835
+ ),
3836
+ );
3837
+ if (input.refName === undefined) {
3838
+ return yield* fetchAll.pipe(Effect.as(true));
3839
+ }
3840
+ const branch =
3841
+ parseRemoteRefWithRemoteNames(input.refName, [input.remoteName])?.branchName ?? input.refName;
3842
+ const scopedArgs = [
3843
+ ...args,
3844
+ `+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`,
3845
+ ];
3846
+ const result = yield* runFetch(scopedArgs);
3847
+ if (result.exitCode === 0) return true;
3848
+ if (
3849
+ result.stderr.split(/\r?\n/).includes(`fatal: couldn't find remote ref refs/heads/${branch}`)
3850
+ ) {
3851
+ return false;
3852
+ }
3853
+ return yield* new GitCommandError({
3854
+ ...gitCommandContext({
3855
+ operation: "GitVcsDriver.fetchRemote",
3856
+ cwd: input.cwd,
3857
+ args: scopedArgs,
3858
+ }),
3859
+ detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3860
+ ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3861
+ stdoutLength: result.stdout.length,
3862
+ stderrLength: result.stderr.length,
3863
+ });
3864
+ });
3865
3866
const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveRemoteTrackingCommit"] =
3867
Effect.fn("resolveRemoteTrackingCommit")(function* (input) {
@@ -3838,6 +3881,62 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3881
return { commitSha, remoteRefName };
3882
});
3883
3884
+ const resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"] =
3885
+ Effect.fn("resolveWorktreeBaseRemote")(function* (input) {
3886
+ const remoteNames = (yield* listRemoteNames(input.cwd)).toSorted(
3887
+ (left, right) => right.length - left.length,
3888
+ );
3889
+ // Upstream atoms read config even before the tracking ref has been fetched.
3890
+ // Match the exact local ref: for-each-ref also returns its descendants.
3891
+ const localBranch = yield* runGitStdout("GitVcsDriver.resolveWorktreeBaseRemote", input.cwd, [
3892
+ "for-each-ref",
3893
+ "--format=%(refname)\t%(upstream:remotename)\t%(upstream:remoteref)",
3894
+ `refs/heads/${input.refName}`,
3895
+ ]).pipe(
3896
+ Effect.map((stdout) =>
3897
+ stdout
3898
+ .split("\n")
3899
+ .map((line) => line.split("\t"))
3900
+ .find(([refName]) => refName === `refs/heads/${input.refName}`),
3901
+ ),
3902
+ );
3903
+ let target: { remoteName: string; branchName: string } | null;
3904
+ if (localBranch) {
3905
+ // A remote of "." tracks another local branch; it is not a remote name.
3906
+ const [, remoteName = "", merge = ""] = localBranch;
3907
+ target =
3908
+ remoteNames.includes(remoteName) && merge.startsWith("refs/heads/")
3909
+ ? { remoteName, branchName: merge.slice("refs/heads/".length) }
3910
+ : null;
3911
+ } else {
3912
+ target = parseRemoteRefWithRemoteNames(input.refName, remoteNames);
3913
+ }
3914
+ const { remoteName, branchName } = target ?? {
3915
+ remoteName: "origin",
3916
+ branchName: input.refName,
3917
+ };
3918
+ return remoteNames.includes(remoteName) ? { remoteName, branchName } : null;
3919
+ });
3920
+
3921
+ const fetchWorktreeBaseCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchWorktreeBaseCommit"] =
3922
+ Effect.fn("fetchWorktreeBaseCommit")(function* (input) {
3923
+ const target = yield* resolveWorktreeBaseRemote(input);
3924
+ if (target === null) return null;
3925
+ const { remoteName, branchName } = target;
3926
+ const remoteRefName = `${remoteName}/${branchName}`;
3927
+ // A missing remote branch can leave a stale tracking ref; never resolve it.
3928
+ if (!(yield* fetchRemote({ cwd: input.cwd, remoteName, refName: remoteRefName }))) {
3929
+ return null;
3930
+ }
3931
+ const resolved = yield* executeGit(
3932
+ "GitVcsDriver.fetchWorktreeBaseCommit",
3933
+ input.cwd,
3934
+ ["rev-parse", "--verify", "--quiet", `refs/remotes/${remoteRefName}^{commit}`],
3935
+ { allowNonZeroExit: true },
3936
+ );
3937
+ return resolved.exitCode === 0 ? { commitSha: resolved.stdout.trim(), remoteRefName } : null;
3938
+ });
3939
+
3940
const fetchRemoteBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteBranch"] = Effect.fn(
3941
"fetchRemoteBranch",
3942
)(function* (input) {
@@ -4174,10 +4273,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4273
ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),
4274
resolvePrimaryRemoteName,
4275
resolveDefaultBranchName,
4177
- fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)),
4276
+ fetchRemote: (input) =>
4277
+ withListRefsInvalidation(
4278
+ input.cwd,
4279
+ fetchRemote(input).pipe(
4280
+ Effect.flatMap((fetched) =>
4281
+ fetched
4282
+ ? Effect.void
4283
+ : fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid),
4284
+ ),
4285
+ ),
4286
+ ),
4287
remoteExists,
4288
remoteBranchExists,
4289
resolveRemoteTrackingCommit,
4290
+ resolveWorktreeBaseRemote,
4291
+ fetchWorktreeBaseCommit: (input) =>
4292
+ withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)),
4293
fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),
4294
fetchRemoteTrackingBranch: (input) =>
4295
withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)),
apps/web/src/components/BranchPicker.tsx
+5
-4
@@ -229,21 +229,22 @@ export function BranchPicker({
229
>
230
<span className="flex min-w-0 items-center gap-1.5 font-medium text-muted-foreground">
231
<RefreshIcon aria-hidden="true" className="size-3 shrink-0" />
232
- <span className="truncate">Start from origin</span>
232
+ <span className="truncate">Start from remote</span>
233
</span>
234
<Switch
235
id={startFromOriginSwitchId}
236
checked={originControl.checked}
237
size="sm"
238
- aria-label="Start worktree from origin"
238
+ aria-label="Start worktree from remote"
239
onCheckedChange={(checked) => originControl.onCheckedChange(Boolean(checked))}
240
/>
241
</label>
242
}
243
/>
244
<TooltipPopup side="top" className="max-w-72 whitespace-normal">
245
- Creates the worktree from the latest matching branch on origin instead of your local
246
- branch.
245
+ Uses the latest commit of the base branch’s tracked remote branch, even if its name
246
+ differs. Otherwise uses the same-named branch on origin. Uses your local branch if
247
+ that remote branch is missing.
248
</TooltipPopup>
249
</Tooltip>
250
) : null}
apps/web/src/components/BranchToolbar.logic.test.ts
+7
-7
@@ -178,7 +178,7 @@ describe("resolveBranchToolbarValue", () => {
178
});
179
180
describe("resolveBranchTriggerLabel", () => {
181
- it("shows the origin ref when a new worktree will start from origin", () => {
181
+ it("marks the remote base when a new worktree will start from remote", () => {
182
expect(
183
resolveBranchTriggerLabel({
184
activeWorktreePath: null,
@@ -187,10 +187,10 @@ describe("resolveBranchTriggerLabel", () => {
187
resolvedActiveBranchIsRemote: false,
188
startFromOrigin: true,
189
}),
190
- ).toBe("From origin/main");
190
+ ).toBe("From main (remote)");
191
});
192
193
- it("shows the origin ref for local branch names that contain slashes", () => {
193
+ it("marks the remote base for local branch names that contain slashes", () => {
194
expect(
195
resolveBranchTriggerLabel({
196
activeWorktreePath: null,
@@ -199,10 +199,10 @@ describe("resolveBranchTriggerLabel", () => {
199
resolvedActiveBranchIsRemote: false,
200
startFromOrigin: true,
201
}),
202
- ).toBe("From origin/feature/demo");
202
+ ).toBe("From feature/demo (remote)");
203
});
204
205
- it("shows the local ref when start from origin is disabled", () => {
205
+ it("shows the local ref when start from remote is disabled", () => {
206
expect(
207
resolveBranchTriggerLabel({
208
activeWorktreePath: null,
@@ -214,7 +214,7 @@ describe("resolveBranchTriggerLabel", () => {
214
).toBe("From main");
215
});
216
217
- it("does not duplicate the origin prefix for an explicit remote ref", () => {
217
+ it("does not add a remote marker for an explicit remote ref", () => {
218
expect(
219
resolveBranchTriggerLabel({
220
activeWorktreePath: null,
@@ -259,7 +259,7 @@ describe("resolveBranchTriggerLabel", () => {
259
).toBe("Select ref");
260
});
261
262
- it("does not fabricate an origin ref while branch metadata is loading", () => {
262
+ it("does not fabricate a remote marker while branch metadata is loading", () => {
263
expect(
264
resolveBranchTriggerLabel({
265
activeWorktreePath: null,
apps/web/src/components/BranchToolbar.logic.ts
+4
-5
@@ -215,11 +215,10 @@ export function resolveBranchTriggerLabel(input: {
215
return "Select ref";
216
}
217
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
218
- const baseRef =
219
- startFromOrigin && resolvedActiveBranchIsRemote === false
220
- ? `origin/${resolvedActiveBranch}`
221
- : resolvedActiveBranch;
222
- return `From ${baseRef}`;
218
+ // Only the server can determine a local branch's configured remote.
219
+ return startFromOrigin && resolvedActiveBranchIsRemote === false
220
+ ? `From ${resolvedActiveBranch} (remote)`
221
+ : `From ${resolvedActiveBranch}`;
222
}
223
return resolvedActiveBranch;
224
}
apps/web/src/components/settings/SettingsPanels.tsx
+4
-4
@@ -635,7 +635,7 @@ export function useSettingsRestore(onRestored?: () => void) {
635
: []),
636
...(settings.newWorktreesStartFromOrigin !==
637
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin
638
- ? ["New worktrees start from origin"]
638
+ ? ["New worktrees start from remote"]
639
: []),
640
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
641
? ["Add project base directory"]
@@ -2940,12 +2940,12 @@ export function GeneralSettingsPanel() {
2940
serverScoped
2941
settingKeys={["newWorktreesStartFromOrigin"]}
2942
{...searchableSetting("start-from-origin")}
2943
- description="Creates the worktree from the latest matching branch on origin instead of your local branch."
2943
+ description="Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing."
2944
resetAction={
2945
settings.newWorktreesStartFromOrigin !==
2946
DEFAULT_UNIFIED_SETTINGS.newWorktreesStartFromOrigin ? (
2947
<SettingResetButton
2948
- label="new worktrees start from origin"
2948
+ label="new worktrees start from remote"
2949
onClick={() =>
2950
updateSettings({
2951
newWorktreesStartFromOrigin:
@@ -2962,7 +2962,7 @@ export function GeneralSettingsPanel() {
2962
onCheckedChange={(checked) =>
2963
updateSettings({ newWorktreesStartFromOrigin: Boolean(checked) })
2964
}
2965
- aria-label="Start new worktrees from origin by default"
2965
+ aria-label="Start new worktrees from remote by default"
2966
/>
2967
}
2968
/>
apps/web/src/components/settings/settingsSearch.ts
+2
-2
@@ -467,10 +467,10 @@ export const SETTINGS_SEARCH_ITEMS = [
467
},
468
{
469
id: "start-from-origin",
470
- title: "Start from origin",
470
+ title: "Start from remote",
471
to: "/settings/general",
472
scope: "project-defaults",
473
- searchTerms: ["new worktrees latest matching remote branch local"],
473
+ searchTerms: ["new worktrees start remote origin latest fetched branch local"],
474
},
475
{
476
id: "add-project-starts-in",
packages/contracts/src/worktreeMcp.ts
+1
-1
@@ -21,7 +21,7 @@ export const WorktreeMcpHandoffInput = Schema.Struct({
21
startFromOrigin: Schema.optional(
22
Schema.Boolean.annotate({
23
description:
24
- "Fetch origin and start the worktree branch from the remote-tracking commit of baseRef instead of the local ref. Defaults to the server's 'new worktrees start from origin' setting.",
24
+ "Fetch the remote baseRef belongs to and start the worktree branch from its remote-tracking commit instead of the local ref. Defaults to the server's 'new worktrees start from remote' setting.",
25
}),
26
),
27
runSetupScript: Schema.optional(
packages/provider-core/src/server/orchestrationInstructions.ts
+1
-1
@@ -24,7 +24,7 @@ For independent implementation or a PR stack in its own worktree, use \`t3_threa
24
- Existing worktree: \`{"title":"Continue cleanup","workspaceStrategy":{"type":"existing_worktree","worktreePath":"/absolute/path/to/worktree","branch":"feature/ui-cleanup"},"message":"Continue the cleanup."}\`
25
- Project's main checkout: \`workspaceStrategy:{"type":"root"}\`. Omitting workspaceStrategy also selects root; it does not inherit the caller's worktree.
26
27
-For stacked work, set \`baseRef\` to the intended parent branch and \`startFromOrigin:false\` to use its local commits. Use \`startFromOrigin:true\` when you intend to fetch and start from origin. Uncommitted edits are not copied. Use \`t3_worktree_list\` to discover existing checkout paths. Project, model selection, and modes inherit unless supplied; a launched thread may not run with broader modes than yours.
27
+For stacked work, set \`baseRef\` to the intended parent branch and \`startFromOrigin:false\` to use its local commits. Use \`startFromOrigin:true\` when you intend to fetch the base branch's remote and start from it. Uncommitted edits are not copied. Use \`t3_worktree_list\` to discover existing checkout paths. Project, model selection, and modes inherit unless supplied; a launched thread may not run with broader modes than yours.
28
29
\`t3_thread_launch\` is the single-thread launch tool. Use \`create_threads\` only for a batch of threads intentionally sharing the caller's checkout: it always inherits the caller's project, branch, and worktree and has no workspace override. Asking an agent to run \`git worktree add\` or \`cd\` in its prompt does not update T3's thread binding. Select the workspace in the launch call instead. \`t3_worktree_handoff\` moves the calling thread, not another thread, and cannot move a thread already attached to a worktree.
30