mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 14:45:25 +00:00
Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
148bc0f174 | ||
|
|
21d2d49a1b | ||
|
|
8ce2097629 | ||
|
|
4c865ad3ee | ||
|
|
89156075d9 | ||
|
|
ca677c8ce9 | ||
|
|
45278bde21 | ||
|
|
c368daa82e | ||
|
|
cc939cdc09 | ||
|
|
638cf1e63b | ||
|
|
98dd572bab | ||
|
|
47eb0ef98c | ||
|
|
84145a3a4c | ||
|
|
309a6cf118 | ||
|
|
8e0488bf75 | ||
|
|
4c8031704d | ||
|
|
bfd5eef413 | ||
|
|
5a3a884377 | ||
|
|
cc6fa498c3 | ||
|
|
580c75384c |
@@ -19,7 +19,12 @@ import {
|
||||
} from "../support/helpers/mock-agent";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedSavedSettingsHosts } from "../support/helpers/settings";
|
||||
import { submitNewWorkspaceEmpty } from "../support/helpers/new-workspace";
|
||||
import {
|
||||
expectPickerSelected,
|
||||
selectWorkspaceIsolation,
|
||||
submitNewWorkspaceEmpty,
|
||||
} from "../support/helpers/new-workspace";
|
||||
import { checkoutBranch } from "../support/helpers/workspace";
|
||||
|
||||
const test = base.extend<{
|
||||
seedForkWorkspace: (options: MockAgentOptions) => Promise<MockAgentWorkspace>;
|
||||
@@ -176,7 +181,9 @@ test.describe("Assistant fork menu", () => {
|
||||
title: "Assistant fork workspace",
|
||||
initialPrompt: "emit 1 coalesced agent stream updates for assistant fork new workspace.",
|
||||
model: "ten-second-stream",
|
||||
repo: { withRemote: true, branches: ["main", "feature/fork-source"] },
|
||||
});
|
||||
checkoutBranch(session.cwd, "feature/fork-source");
|
||||
|
||||
await openAgentRoute(page, session);
|
||||
await expectComposerVisible(page);
|
||||
@@ -188,6 +195,11 @@ test.describe("Assistant fork menu", () => {
|
||||
await expect(page).toHaveURL(/\/new\?.*draftId=/, { timeout: 30_000 });
|
||||
await expectChatHistoryAttachment(page);
|
||||
|
||||
// A fork continues the source agent's work, so it starts from the branch that agent is
|
||||
// on rather than the repository default a fresh workspace starts from.
|
||||
await selectWorkspaceIsolation(page, "worktree");
|
||||
await expectPickerSelected(page, "feature/fork-source");
|
||||
|
||||
await page.getByTestId("host-picker-trigger").click();
|
||||
await page
|
||||
.getByTestId("new-workspace-host-picker-option-secondary-assistant-fork-host")
|
||||
|
||||
@@ -272,6 +272,10 @@ test.afterEach(async () => {
|
||||
|
||||
test("Changes without a comparison base explains how to view pending changes", async ({ page }) => {
|
||||
const workspace = await createWorkspaceWithManyTinyDiffs(2, "dev");
|
||||
// A sole branch such as dev is the repository default. With several custom branches, no
|
||||
// remote and a detached HEAD, nothing says which branch to compare against.
|
||||
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
|
||||
execFileSync("git", ["checkout", "--detach"], { cwd: workspace.repoPath, stdio: "ignore" });
|
||||
await openWorkspaceChangesTree(page, workspace);
|
||||
await expect(
|
||||
page.getByText("Comparison base is unavailable. Select Uncommitted to view pending changes."),
|
||||
@@ -584,6 +588,33 @@ test("Changes selects exact local and remote bases and retains the selection aft
|
||||
);
|
||||
});
|
||||
|
||||
test("Changes treats a worktree on the default branch as on its base and labels a local pin", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const workspace = await createWorktreeCheckedOutOnMain();
|
||||
await openWorkspaceChangesTree(page, workspace);
|
||||
const tree = page.getByTestId("changes-tree-panel").filter({ visible: true });
|
||||
const picker = tree.getByTestId("workspace-base-branch-trigger");
|
||||
|
||||
await test.step("a worktree on main compares against origin and offers no feature actions", async () => {
|
||||
await expect(picker).toHaveText("main");
|
||||
await expectNoFeatureActions(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("on-base-worktree.png") });
|
||||
});
|
||||
|
||||
await test.step("pinning local main reads as local next to origin", async () => {
|
||||
await chooseBase(page, picker, "main");
|
||||
await expect(picker).toHaveText("main (local)");
|
||||
await expectNoFeatureActions(page);
|
||||
await page.screenshot({ path: testInfo.outputPath("local-base-pinned.png") });
|
||||
});
|
||||
|
||||
await test.step("pinning origin main drops the qualifier again", async () => {
|
||||
await chooseBase(page, picker, "origin/main");
|
||||
await expect(picker).toHaveText("main");
|
||||
});
|
||||
});
|
||||
|
||||
test("Changes lets a compact workspace change its base in a sheet", async ({ page }, testInfo) => {
|
||||
const workspace = await createWorktreeWithCommittedDiff();
|
||||
execFileSync("git", ["branch", "release"], { cwd: workspace.repoPath });
|
||||
@@ -2272,6 +2303,27 @@ async function expectInSyncWithRemote(workspace: RemoteWorkspace): Promise<void>
|
||||
}
|
||||
|
||||
// A clean main that is in sync with its remote has no git action, so the button is gone.
|
||||
async function chooseBase(page: Page, picker: Locator, label: string): Promise<void> {
|
||||
await picker.click();
|
||||
await page
|
||||
.getByTestId("combobox-desktop-container")
|
||||
.getByRole("button", { name: label, exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
// Merging, merging the base in and opening a PR only make sense on a branch off the base.
|
||||
async function expectNoFeatureActions(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("changes-primary-cta")).toHaveAccessibleName("Archive workspace", {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await page.getByTestId("changes-primary-cta-caret").click();
|
||||
await expect(page.getByTestId("changes-primary-cta-menu")).toBeVisible();
|
||||
for (const action of ["merge-branch", "merge-from-base", "pr"]) {
|
||||
await expect(page.getByTestId(`changes-menu-${action}`)).toHaveCount(0);
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
async function expectNoGitActionLeft(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("changes-primary-cta")).toBeHidden({ timeout: 30_000 });
|
||||
}
|
||||
@@ -2417,6 +2469,34 @@ async function createWorktreeWithCommittedDiff(): Promise<DirtyWorkspace> {
|
||||
return { id: created.workspace.id, repoPath: cwd };
|
||||
}
|
||||
|
||||
// The user checks out the default branch itself in a worktree while the main checkout sits on
|
||||
// other work, so the worktree is on its own base.
|
||||
async function createWorktreeCheckedOutOnMain(): Promise<DirtyWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-on-base-", {
|
||||
withRemote: true,
|
||||
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
|
||||
});
|
||||
const client = await connectSeedClient();
|
||||
cleanupTasks.push({
|
||||
run: async () => {
|
||||
await client.close();
|
||||
await repo.cleanup();
|
||||
},
|
||||
});
|
||||
execFileSync("git", ["checkout", "-b", "unrelated"], { cwd: repo.path });
|
||||
const created = await client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: repo.path,
|
||||
action: "checkout",
|
||||
refName: "main",
|
||||
worktreeSlug: "on-main",
|
||||
},
|
||||
});
|
||||
if (!created.workspace) throw new Error(created.error ?? "Failed to create worktree");
|
||||
return { id: created.workspace.id, repoPath: created.workspace.workspaceDirectory };
|
||||
}
|
||||
|
||||
async function createWorkspaceWithCommittedDiff(): Promise<DirtyWorkspace> {
|
||||
const repo = await createTempGitRepo("changes-committed-", {
|
||||
files: [{ path: "tracked.ts", content: "export const tracked = 1;\n" }],
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
submitNewWorkspacePrompt,
|
||||
} from "../support/helpers/new-workspace";
|
||||
import {
|
||||
checkoutBranch,
|
||||
commitLocalOnly,
|
||||
createTempGitRepo,
|
||||
readRepoRef,
|
||||
@@ -816,6 +817,34 @@ test.describe("New workspace flow", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("branches off the repository default when the checkout is on a feature branch", async ({
|
||||
page,
|
||||
}) => {
|
||||
const tempRepo = await createTempGitRepo("ref-default-feature-", {
|
||||
withRemote: true,
|
||||
branches: ["main", "feature/unrelated"],
|
||||
});
|
||||
|
||||
try {
|
||||
const originHead = readRepoRef(tempRepo.path, "refs/remotes/origin/main");
|
||||
checkoutBranch(tempRepo.path, "feature/unrelated");
|
||||
const featureHead = commitLocalOnly(tempRepo.path, "feature work");
|
||||
|
||||
const openedProject = await openWorktreeComposerForRepo(page, tempRepo.path);
|
||||
await expectPickerSelected(page, "main");
|
||||
const created = await createWorktreeAndRead(page, openedProject);
|
||||
|
||||
expect(created.branchInfo.hasAncestor(originHead)).toBe(true);
|
||||
expect(created.branchInfo.hasAncestor(featureHead)).toBe(false);
|
||||
expect(await readWorktreeBaseMetadata(created.workspaceDirectory)).toEqual({
|
||||
baseRefName: "main",
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
} finally {
|
||||
await tempRepo.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("branches off the local ref when the local row is chosen explicitly", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
@@ -864,7 +893,7 @@ test.describe("New workspace flow", () => {
|
||||
// tracks gets its own row rather than silently sharing origin's. Two rows reading
|
||||
// "main" is the ambiguity this whole change exists to remove.
|
||||
await expectStartingRefRows(page, [
|
||||
"main (upstream), upstream branch",
|
||||
"main (upstream), default branch",
|
||||
"main, origin branch",
|
||||
]);
|
||||
await expectPickerSelected(page, "main (upstream)");
|
||||
|
||||
@@ -204,6 +204,11 @@ export async function trackForkUpstream(repoPath: string): Promise<string> {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Leaves the checkout on `branch`, the way a user working on a feature has it. */
|
||||
export function checkoutBranch(repoPath: string, branch: string): void {
|
||||
execSync(`git checkout ${JSON.stringify(branch)}`, { cwd: repoPath, stdio: "ignore" });
|
||||
}
|
||||
|
||||
export function readRepoRef(repoPath: string, ref: string): string {
|
||||
return execSync(`git rev-parse ${JSON.stringify(ref)}`, { cwd: repoPath, stdio: "pipe" })
|
||||
.toString()
|
||||
|
||||
@@ -471,6 +471,7 @@ interface ChangesPullRequestLinkModel extends Pick<PrHint, "forge" | "number" |
|
||||
|
||||
interface ChangesRepositoryToolbarModel {
|
||||
baseRef: string | null;
|
||||
hasRemote: boolean;
|
||||
isWorktree: boolean;
|
||||
branchName: string | null;
|
||||
cwd: string;
|
||||
@@ -499,6 +500,7 @@ interface ChangesHeaderProps {
|
||||
|
||||
interface BuildChangesHeaderModelInput {
|
||||
baseRef: string | null;
|
||||
hasRemote: boolean;
|
||||
isWorktree: boolean;
|
||||
branchName: string | null;
|
||||
committedDescription?: string;
|
||||
@@ -524,6 +526,7 @@ function buildChangesHeaderModel(input: BuildChangesHeaderModelInput): {
|
||||
return {
|
||||
repository: {
|
||||
baseRef: input.baseRef,
|
||||
hasRemote: input.hasRemote,
|
||||
isWorktree: input.isWorktree,
|
||||
branchName: input.branchName,
|
||||
cwd: input.cwd,
|
||||
@@ -672,6 +675,7 @@ function ChangesRepositoryToolbar({
|
||||
workspaceId={model.workspaceId}
|
||||
cwd={model.cwd}
|
||||
baseRef={model.baseRef}
|
||||
hasRemote={model.hasRemote}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
@@ -1894,6 +1898,7 @@ export function ChangesSurface({
|
||||
() =>
|
||||
buildChangesHeaderModel({
|
||||
baseRef: baseRef ?? null,
|
||||
hasRemote: status?.isGit === true && status.hasRemote,
|
||||
isWorktree: isManagedWorktree(status),
|
||||
branchName: currentBranchName,
|
||||
committedDescription: committedDiffDescription,
|
||||
|
||||
@@ -5,8 +5,7 @@ import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
actionsWithoutPrimary,
|
||||
buildGitActions,
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
readBaseBranchRelation,
|
||||
readSyncRemotes,
|
||||
readUpstreamState,
|
||||
type BuildGitActionsInput,
|
||||
@@ -229,23 +228,106 @@ describe("git-actions-policy", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("distinguishes exact local and remote base refs and retains legacy names", () => {
|
||||
expect(isCurrentBranchBase("release", "refs/heads/release")).toBe(true);
|
||||
expect(isCurrentBranchBase("release", "refs/remotes/origin/release")).toBe(false);
|
||||
expect(isCurrentBranchBase("release", "release")).toBe(true);
|
||||
expect(isCurrentBranchBase("release", "origin/release")).toBe(true);
|
||||
expect(isCurrentBranchBase(null, "refs/heads/release")).toBe(false);
|
||||
expect(canMergeIntoLocalBase("release", "refs/heads/release")).toBe(false);
|
||||
expect(canMergeIntoLocalBase("feature", "refs/remotes/origin/release")).toBe(true);
|
||||
expect(canMergeIntoLocalBase("release", "refs/remotes/upstream/release")).toBe(false);
|
||||
it("reads whether the checkout is on its base from the branch the daemon resolves", () => {
|
||||
// A worktree checked out on main, whose base is the origin/main it tracks.
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "main",
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: true, canMergeLocally: false });
|
||||
// A fork's main tracking upstream/main.
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "main",
|
||||
baseRef: "refs/remotes/upstream/main",
|
||||
baseRefBranch: { branch: "main", remote: "upstream", isCurrent: true },
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: true, canMergeLocally: false });
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "feature",
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: false },
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: false, canMergeLocally: true });
|
||||
// The daemon merges locally only into a local base or origin's branch.
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "feature",
|
||||
baseRef: "refs/remotes/upstream/main",
|
||||
baseRefBranch: { branch: "main", remote: "upstream", isCurrent: false },
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
|
||||
// A release branch with no upstream only shares its name with the remote base.
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "release",
|
||||
baseRef: "refs/remotes/origin/release",
|
||||
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
|
||||
expect(
|
||||
readBaseBranchRelation({
|
||||
currentBranch: "feature",
|
||||
baseRef: "refs/tags/v1",
|
||||
baseRefBranch: null,
|
||||
}),
|
||||
).toEqual({ isOnBaseBranch: false, canMergeLocally: false });
|
||||
});
|
||||
|
||||
it("reads exact local and remote base refs from daemons that predate the base branch", () => {
|
||||
function legacy(currentBranch: string | null, baseRef: string) {
|
||||
return readBaseBranchRelation({ currentBranch, baseRef });
|
||||
}
|
||||
expect(legacy("release", "refs/heads/release")).toEqual({
|
||||
isOnBaseBranch: true,
|
||||
canMergeLocally: false,
|
||||
});
|
||||
expect(legacy("release", "refs/remotes/origin/release").isOnBaseBranch).toBe(false);
|
||||
expect(legacy("release", "release").isOnBaseBranch).toBe(true);
|
||||
expect(legacy("release", "origin/release").isOnBaseBranch).toBe(true);
|
||||
expect(legacy(null, "refs/heads/release").isOnBaseBranch).toBe(false);
|
||||
expect(legacy("feature", "refs/remotes/origin/release").canMergeLocally).toBe(true);
|
||||
expect(legacy("release", "refs/remotes/upstream/release").canMergeLocally).toBe(false);
|
||||
});
|
||||
|
||||
it("offers no feature actions on a worktree checked out on its default branch", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
isPaseoOwnedWorktree: true,
|
||||
hasRemote: true,
|
||||
...readBaseBranchRelation({
|
||||
currentBranch: "main",
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
}),
|
||||
baseRefLabel: "main",
|
||||
aheadCount: 1,
|
||||
behindBaseCount: 2,
|
||||
aheadOfOrigin: 1,
|
||||
behindOfOrigin: 2,
|
||||
shipDefault: "merge",
|
||||
}),
|
||||
);
|
||||
expect(actions.primary?.id).toBe("pull");
|
||||
expect(actionsWithoutPrimary(actions).map((action) => action.id)).toEqual([
|
||||
"push",
|
||||
"pull-and-push",
|
||||
"archive-workspace",
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers local merge when the selected local base starts with origin slash", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: isCurrentBranchBase("release", "refs/heads/origin/release"),
|
||||
canMergeLocally: canMergeIntoLocalBase("release", "refs/heads/origin/release"),
|
||||
...readBaseBranchRelation({
|
||||
currentBranch: "release",
|
||||
baseRef: "refs/heads/origin/release",
|
||||
baseRefBranch: { branch: "origin/release", remote: null, isCurrent: false },
|
||||
}),
|
||||
baseRefLabel: "origin/release",
|
||||
aheadCount: 1,
|
||||
shipDefault: "merge",
|
||||
@@ -259,7 +341,11 @@ describe("git-actions-policy", () => {
|
||||
createInput({
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
canMergeLocally: canMergeIntoLocalBase("feature", "refs/remotes/upstream/release"),
|
||||
canMergeLocally: readBaseBranchRelation({
|
||||
currentBranch: "feature",
|
||||
baseRef: "refs/remotes/upstream/release",
|
||||
baseRefBranch: { branch: "release", remote: "upstream", isCurrent: false },
|
||||
}).canMergeLocally,
|
||||
baseRefLabel: "upstream/release",
|
||||
aheadCount: 1,
|
||||
behindBaseCount: 1,
|
||||
@@ -277,7 +363,11 @@ describe("git-actions-policy", () => {
|
||||
createInput({
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: false,
|
||||
canMergeLocally: canMergeIntoLocalBase("release", "refs/remotes/origin/release"),
|
||||
canMergeLocally: readBaseBranchRelation({
|
||||
currentBranch: "release",
|
||||
baseRef: "refs/remotes/origin/release",
|
||||
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
|
||||
}).canMergeLocally,
|
||||
baseRefLabel: "release",
|
||||
aheadCount: 1,
|
||||
behindBaseCount: 1,
|
||||
@@ -294,7 +384,11 @@ describe("git-actions-policy", () => {
|
||||
const actions = buildGitActions(
|
||||
createInput({
|
||||
isPaseoOwnedWorktree: true,
|
||||
isOnBaseBranch: isCurrentBranchBase("release", "refs/remotes/origin/release"),
|
||||
isOnBaseBranch: readBaseBranchRelation({
|
||||
currentBranch: "release",
|
||||
baseRef: "refs/remotes/origin/release",
|
||||
baseRefBranch: { branch: "release", remote: "origin", isCurrent: false },
|
||||
}).isOnBaseBranch,
|
||||
baseRefLabel: "release",
|
||||
behindBaseCount: 1,
|
||||
aheadOfOrigin: null,
|
||||
|
||||
@@ -54,22 +54,55 @@ interface GitActionRuntimeState {
|
||||
handler: () => void;
|
||||
}
|
||||
|
||||
export function isCurrentBranchBase(
|
||||
currentBranch: string | null | undefined,
|
||||
baseRef: string | null | undefined,
|
||||
): boolean {
|
||||
if (!currentBranch || !baseRef) return false;
|
||||
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
|
||||
|
||||
export interface BaseBranchRelation {
|
||||
/** The checkout is on its base branch, so it has no feature to merge, update, or open a PR for. */
|
||||
isOnBaseBranch: boolean;
|
||||
/** Merge can go into the local branch the base stands for. */
|
||||
canMergeLocally: boolean;
|
||||
}
|
||||
|
||||
/** `baseRef` is the exact base ref (`baseRefExact`) once the status cache has normalized it. */
|
||||
export function readBaseBranchRelation(
|
||||
status: Pick<CheckoutStatusPayload, "currentBranch" | "baseRef" | "baseRefBranch">,
|
||||
): BaseBranchRelation {
|
||||
const { currentBranch, baseRefBranch } = status;
|
||||
if (baseRefBranch === undefined) {
|
||||
return readLegacyBaseBranchRelation(currentBranch, status.baseRef);
|
||||
}
|
||||
if (!currentBranch || !baseRefBranch) return { isOnBaseBranch: false, canMergeLocally: false };
|
||||
return {
|
||||
isOnBaseBranch: baseRefBranch.isCurrent,
|
||||
// The daemon merges into a local branch it infers only from a local base or origin's branch.
|
||||
canMergeLocally:
|
||||
(baseRefBranch.remote === null || baseRefBranch.remote === "origin") &&
|
||||
baseRefBranch.branch !== currentBranch,
|
||||
};
|
||||
}
|
||||
|
||||
// COMPAT(checkoutBaseRefBranch): added in v0.19.2, remove after 2027-06-05 once the daemon floor
|
||||
// reports baseRefBranch. Older daemons send only the base ref, so its branch is read from the
|
||||
// ref's spelling and a remote is assumed to be origin.
|
||||
function readLegacyBaseBranchRelation(
|
||||
currentBranch: string | null,
|
||||
baseRef: string | null,
|
||||
): BaseBranchRelation {
|
||||
if (!currentBranch || !baseRef) return { isOnBaseBranch: false, canMergeLocally: false };
|
||||
return {
|
||||
isOnBaseBranch: isLegacyCurrentBranchBase(currentBranch, baseRef),
|
||||
canMergeLocally: canMergeIntoLegacyLocalBase(currentBranch, baseRef),
|
||||
};
|
||||
}
|
||||
|
||||
function isLegacyCurrentBranchBase(currentBranch: string, baseRef: string): boolean {
|
||||
if (baseRef.startsWith("refs/heads/")) return baseRef === `refs/heads/${currentBranch}`;
|
||||
if (baseRef.startsWith("refs/")) return false;
|
||||
// Older hosts send a display name, which cannot distinguish a local ref from its remote.
|
||||
return currentBranch === baseRef.replace(/^origin\//, "");
|
||||
}
|
||||
|
||||
export function canMergeIntoLocalBase(
|
||||
currentBranch: string | null | undefined,
|
||||
baseRef: string | null | undefined,
|
||||
): boolean {
|
||||
if (!currentBranch || !baseRef) return false;
|
||||
function canMergeIntoLegacyLocalBase(currentBranch: string, baseRef: string): boolean {
|
||||
if (baseRef.startsWith("refs/remotes/") && !baseRef.startsWith("refs/remotes/origin/")) {
|
||||
return false;
|
||||
}
|
||||
@@ -77,8 +110,6 @@ export function canMergeIntoLocalBase(
|
||||
return currentBranch !== localTarget;
|
||||
}
|
||||
|
||||
type CheckoutStatusPayload = CheckoutStatusResponse["payload"];
|
||||
|
||||
export type GitUpstreamState = NonNullable<CheckoutStatusPayload["upstreamState"]>;
|
||||
|
||||
export function readUpstreamState(
|
||||
|
||||
@@ -12,11 +12,11 @@ import { type CheckoutStatusPayload, useCheckoutStatusQuery } from "@/git/use-st
|
||||
import { type CheckoutPrStatusPayload, useCheckoutPrStatusQuery } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
buildGitActions,
|
||||
isCurrentBranchBase,
|
||||
canMergeIntoLocalBase,
|
||||
narrowPullRequestState,
|
||||
readBaseBranchRelation,
|
||||
readSyncRemotes,
|
||||
readUpstreamState,
|
||||
type BaseBranchRelation,
|
||||
type BuildGitActionsInput,
|
||||
type GitAction,
|
||||
type GitActions,
|
||||
@@ -119,10 +119,10 @@ interface DeriveGitActionsStateArgs {
|
||||
hasUncommittedChanges: boolean;
|
||||
postShipArchiveSuggested: boolean;
|
||||
isStatusLoading: boolean;
|
||||
baseRef: string | undefined;
|
||||
}
|
||||
|
||||
const NO_SYNC_REMOTES: SyncRemotes = { hasPullRemote: false, hasPushRemote: false };
|
||||
const NOT_ON_A_BASE: BaseBranchRelation = { isOnBaseBranch: false, canMergeLocally: false };
|
||||
|
||||
interface DerivedGitActionsState extends SyncRemotes {
|
||||
actionsDisabled: boolean;
|
||||
@@ -173,7 +173,6 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
|
||||
hasUncommittedChanges,
|
||||
postShipArchiveSuggested,
|
||||
isStatusLoading,
|
||||
baseRef,
|
||||
} = args;
|
||||
const actionsDisabled = !isGit || Boolean(status?.error) || isStatusLoading;
|
||||
const isPaseoOwnedWorktree = gitStatus?.isPaseoOwnedWorktree ?? false;
|
||||
@@ -185,8 +184,7 @@ function deriveGitActionsState(args: DeriveGitActionsStateArgs): DerivedGitActio
|
||||
...(gitStatus ? readSyncRemotes(gitStatus) : NO_SYNC_REMOTES),
|
||||
upstream: gitStatus ? readUpstreamState(gitStatus) : "unknown",
|
||||
isPaseoOwnedWorktree,
|
||||
isOnBaseBranch: isCurrentBranchBase(gitStatus?.currentBranch, baseRef),
|
||||
canMergeLocally: canMergeIntoLocalBase(gitStatus?.currentBranch, baseRef),
|
||||
...(gitStatus ? readBaseBranchRelation(gitStatus) : NOT_ON_A_BASE),
|
||||
shouldPromoteArchive: computeShouldPromoteArchive({
|
||||
hasUncommittedChanges,
|
||||
postShipArchiveSuggested,
|
||||
@@ -642,7 +640,6 @@ export function useGitActions({
|
||||
hasUncommittedChanges,
|
||||
postShipArchiveSuggested,
|
||||
isStatusLoading,
|
||||
baseRef,
|
||||
});
|
||||
const {
|
||||
actionsDisabled,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { workspaceBaseBranchLabel } from "./workspace-base-branch-label";
|
||||
|
||||
describe("workspaceBaseBranchLabel", () => {
|
||||
it("marks a pinned local base when origin has a branch it could be confused with", () => {
|
||||
expect(workspaceBaseBranchLabel("refs/heads/main", { hasRemote: true })).toBe("main (local)");
|
||||
expect(workspaceBaseBranchLabel("refs/remotes/origin/main", { hasRemote: true })).toBe("main");
|
||||
});
|
||||
|
||||
it("keeps a local base unmarked in a repository without origin", () => {
|
||||
expect(workspaceBaseBranchLabel("refs/heads/main", { hasRemote: false })).toBe("main");
|
||||
});
|
||||
|
||||
it("names the remote of a base on another remote", () => {
|
||||
expect(workspaceBaseBranchLabel("refs/remotes/upstream/main", { hasRemote: true })).toBe(
|
||||
"upstream/main",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a local branch whose name starts with origin slash intact", () => {
|
||||
expect(workspaceBaseBranchLabel("refs/heads/origin/release", { hasRemote: true })).toBe(
|
||||
"origin/release (local)",
|
||||
);
|
||||
});
|
||||
|
||||
it("reads a legacy bare base name as is", () => {
|
||||
expect(workspaceBaseBranchLabel("main", { hasRemote: true })).toBe("main");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* How the Changes toolbar names a worktree's base. Origin's branches drop the "origin/" prefix, so
|
||||
* a local base is marked "(local)" whenever the checkout has origin; otherwise a base pinned to
|
||||
* local `main` reads the same as `origin/main`. Other remotes keep their name.
|
||||
*/
|
||||
export function workspaceBaseBranchLabel(
|
||||
baseRef: string,
|
||||
checkout: { hasRemote: boolean },
|
||||
): string {
|
||||
if (baseRef.startsWith("refs/heads/")) {
|
||||
const name = baseRef.slice("refs/heads/".length);
|
||||
return checkout.hasRemote ? `${name} (local)` : name;
|
||||
}
|
||||
const name = baseRef.startsWith("refs/remotes/")
|
||||
? baseRef.slice("refs/remotes/".length)
|
||||
: baseRef;
|
||||
return name.startsWith("origin/") ? name.slice("origin/".length) : name;
|
||||
}
|
||||
@@ -14,12 +14,15 @@ import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { invalidateCheckoutGitQueriesForClient } from "./query-keys";
|
||||
import { workspaceBaseBranchLabel } from "./workspace-base-branch-label";
|
||||
|
||||
interface Props {
|
||||
serverId: string;
|
||||
workspaceId?: string | null;
|
||||
cwd: string;
|
||||
baseRef: string;
|
||||
/** The checkout has origin, so a local base needs telling apart from origin's branch. */
|
||||
hasRemote: boolean;
|
||||
}
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
@@ -30,7 +33,13 @@ function refLabel(ref: string): string {
|
||||
return ref.replace(/^refs\/(heads|remotes)\//, "");
|
||||
}
|
||||
|
||||
export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef }: Props) {
|
||||
export function WorkspaceBaseBranchPicker({
|
||||
serverId,
|
||||
workspaceId,
|
||||
cwd,
|
||||
baseRef,
|
||||
hasRemote,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const connected = useHostRuntimeIsConnected(serverId);
|
||||
@@ -77,7 +86,7 @@ export function WorkspaceBaseBranchPicker({ serverId, workspaceId, cwd, baseRef
|
||||
);
|
||||
const error = mutation.error ?? branches.error;
|
||||
const title = t("workspace.git.diff.baseBranch.title");
|
||||
const label = refLabel(baseRef).replace(/^origin\//, "");
|
||||
const label = workspaceBaseBranchLabel(baseRef, { hasRemote });
|
||||
|
||||
const { reset, mutate, isPending } = mutation;
|
||||
const { refetch, isError } = branches;
|
||||
|
||||
@@ -322,10 +322,10 @@ const mainRow: BranchPickerDetail = {
|
||||
|
||||
describe("buildPickerOptionData", () => {
|
||||
it("marks origin and keeps an ahead local main explicit", () => {
|
||||
const baseItem = defaultBasePickerItem({
|
||||
currentBranch: "main",
|
||||
upstreamRef: "refs/remotes/origin/main",
|
||||
});
|
||||
const baseItem = defaultBasePickerItem(
|
||||
{ currentBranch: "main", upstreamRef: "refs/remotes/origin/main" },
|
||||
"fresh",
|
||||
);
|
||||
const data = buildPickerOptionData({ branchDetails: [mainRow], prItems: [], baseItem });
|
||||
|
||||
expect(data.options.map((option) => option.label)).toEqual(["main", "main (local)"]);
|
||||
@@ -333,10 +333,10 @@ describe("buildPickerOptionData", () => {
|
||||
});
|
||||
|
||||
it("adds and disambiguates a fork upstream absent from branch suggestions", () => {
|
||||
const baseItem = defaultBasePickerItem({
|
||||
currentBranch: "main",
|
||||
upstreamRef: "refs/remotes/upstream/main",
|
||||
});
|
||||
const baseItem = defaultBasePickerItem(
|
||||
{ currentBranch: "main", upstreamRef: "refs/remotes/upstream/main" },
|
||||
"fresh",
|
||||
);
|
||||
const data = buildPickerOptionData({
|
||||
branchDetails: [{ ...mainRow, localAhead: 0, localBehind: 0 }],
|
||||
prItems: [],
|
||||
@@ -348,7 +348,7 @@ describe("buildPickerOptionData", () => {
|
||||
});
|
||||
|
||||
it("marks a visible row on an old daemon when local and origin are in sync", () => {
|
||||
const baseItem = defaultBasePickerItem({ currentBranch: "main" });
|
||||
const baseItem = defaultBasePickerItem({ currentBranch: "main" }, "fresh");
|
||||
const data = buildPickerOptionData({
|
||||
branchDetails: [{ ...mainRow, localAhead: 0, localBehind: 0 }],
|
||||
prItems: [],
|
||||
@@ -380,33 +380,76 @@ describe("buildPickerOptionData", () => {
|
||||
});
|
||||
|
||||
describe("defaultBasePickerItem", () => {
|
||||
it("uses origin when the current branch tracks origin", () => {
|
||||
it("starts a fresh workspace from the repository default while the checkout is on a feature branch", () => {
|
||||
expect(
|
||||
defaultBasePickerItem({
|
||||
currentBranch: "main",
|
||||
upstreamRef: "refs/remotes/origin/main",
|
||||
}),
|
||||
defaultBasePickerItem(
|
||||
{
|
||||
currentBranch: "feature/unrelated",
|
||||
upstreamRef: "refs/remotes/origin/feature/unrelated",
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
},
|
||||
"fresh",
|
||||
),
|
||||
).toMatchObject({ refName: "refs/remotes/origin/main", name: "main" });
|
||||
});
|
||||
|
||||
it("uses the exact non-origin upstream", () => {
|
||||
it("starts a fresh workspace from the repository default on a detached HEAD", () => {
|
||||
expect(
|
||||
defaultBasePickerItem({
|
||||
currentBranch: "main",
|
||||
upstreamRef: "refs/remotes/upstream/main",
|
||||
}),
|
||||
defaultBasePickerItem(
|
||||
{ currentBranch: null, defaultBaseRef: "refs/remotes/upstream/main" },
|
||||
"fresh",
|
||||
),
|
||||
).toMatchObject({ refName: "refs/remotes/upstream/main", name: "main" });
|
||||
});
|
||||
|
||||
it("keeps old-daemon behavior local", () => {
|
||||
expect(defaultBasePickerItem({ currentBranch: "main" })).toMatchObject({
|
||||
refName: "refs/heads/main",
|
||||
name: "main",
|
||||
});
|
||||
it("starts a fork from the source agent's local branch", () => {
|
||||
expect(
|
||||
defaultBasePickerItem(
|
||||
{
|
||||
currentBranch: "feature/agent",
|
||||
upstreamRef: "refs/remotes/origin/feature/agent",
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
},
|
||||
"fork",
|
||||
),
|
||||
).toMatchObject({ refName: "refs/heads/feature/agent", name: "feature/agent" });
|
||||
expect(
|
||||
defaultBasePickerItem(
|
||||
{ currentBranch: null, defaultBaseRef: "refs/remotes/origin/main" },
|
||||
"fork",
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("has no default for detached HEAD", () => {
|
||||
expect(defaultBasePickerItem({ currentBranch: null })).toBeNull();
|
||||
describe("on a daemon that predates the repository default", () => {
|
||||
it("uses origin when the current branch tracks origin", () => {
|
||||
expect(
|
||||
defaultBasePickerItem(
|
||||
{ currentBranch: "main", upstreamRef: "refs/remotes/origin/main" },
|
||||
"fresh",
|
||||
),
|
||||
).toMatchObject({ refName: "refs/remotes/origin/main", name: "main" });
|
||||
});
|
||||
|
||||
it("uses the exact non-origin upstream", () => {
|
||||
expect(
|
||||
defaultBasePickerItem(
|
||||
{ currentBranch: "main", upstreamRef: "refs/remotes/upstream/main" },
|
||||
"fresh",
|
||||
),
|
||||
).toMatchObject({ refName: "refs/remotes/upstream/main", name: "main" });
|
||||
});
|
||||
|
||||
it("keeps old-daemon behavior local", () => {
|
||||
expect(defaultBasePickerItem({ currentBranch: "main" }, "fresh")).toMatchObject({
|
||||
refName: "refs/heads/main",
|
||||
name: "main",
|
||||
});
|
||||
});
|
||||
|
||||
it("has no default for detached HEAD", () => {
|
||||
expect(defaultBasePickerItem({ currentBranch: null }, "fresh")).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -137,8 +137,12 @@ export function buildBranchPickerItems(details: readonly BranchPickerDetail[]):
|
||||
export interface BaseRefCheckoutStatus {
|
||||
currentBranch: string | null;
|
||||
upstreamRef?: string | null;
|
||||
defaultBaseRef?: string | null;
|
||||
}
|
||||
|
||||
/** A fresh workspace starts from the repository default; a fork continues the source agent's branch. */
|
||||
export type WorkspaceStart = "fresh" | "fork";
|
||||
|
||||
// Display only. The exact ref is what every request carries; this is just how a ref reads in
|
||||
// a row label, so "refs/remotes/origin/other-name" shows as "other-name".
|
||||
export function branchNameFromRef(refName: string): string {
|
||||
@@ -166,25 +170,41 @@ function refQualifier(refName: string): string | null {
|
||||
// row, the trigger label, and the created ref all read this; computing it twice is how the
|
||||
// picker once showed local main while branching off something else.
|
||||
//
|
||||
// The upstream wins when the branch has one, because branching off the local ref silently
|
||||
// carries unpushed commits into the new workspace. The daemon sends the resolved ref rather
|
||||
// than a remote name, so a fork tracking upstream/main branches from upstream/main.
|
||||
export function defaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
|
||||
// A fresh workspace starts from the base the daemon creates worktrees from when none is named,
|
||||
// whatever branch the checkout happens to be on, so the app and MCP, CLI, and schedules agree. A
|
||||
// fork starts from the source agent's local branch, so it keeps the agent's unpushed commits.
|
||||
export function defaultBasePickerItem(
|
||||
status: BaseRefCheckoutStatus,
|
||||
start: WorkspaceStart,
|
||||
): PickerItem | null {
|
||||
if (start === "fork") {
|
||||
if (!status.currentBranch) return null;
|
||||
return branchPickerItem(`refs/heads/${status.currentBranch}`, "local branch");
|
||||
}
|
||||
if (status.defaultBaseRef) {
|
||||
return branchPickerItem(status.defaultBaseRef, "default branch");
|
||||
}
|
||||
return legacyDefaultBasePickerItem(status);
|
||||
}
|
||||
|
||||
function branchPickerItem(refName: string, description: string): PickerItem {
|
||||
// The row reads the ref, which can name a different branch than the one checked out.
|
||||
const name = branchNameFromRef(refName);
|
||||
return { kind: "branch", name, refName, accessibilityLabel: `${name}, ${description}` };
|
||||
}
|
||||
|
||||
// COMPAT(checkoutDefaultBaseRef): added in v0.19.2, remove after 2027-06-05 once the daemon floor
|
||||
// sends defaultBaseRef. Older daemons report no default, so the base follows the current branch:
|
||||
// its upstream when it has one, because branching off the local ref silently carries unpushed
|
||||
// commits into the new workspace.
|
||||
function legacyDefaultBasePickerItem(status: BaseRefCheckoutStatus): PickerItem | null {
|
||||
const currentBranch = status.currentBranch;
|
||||
if (!currentBranch) return null;
|
||||
// COMPAT(checkoutUpstreamRef): added in v0.2.6, remove after 2027-02-01 once the daemon
|
||||
// floor sends upstreamRef. Daemons that predate it omit the field, which lands on the
|
||||
// local ref — the base those daemons always used.
|
||||
const refName = status.upstreamRef ?? `refs/heads/${currentBranch}`;
|
||||
// The upstream branch can be named differently from the local one, so the row reads the
|
||||
// ref rather than the branch the user happens to be on.
|
||||
const name = branchNameFromRef(refName);
|
||||
return {
|
||||
kind: "branch",
|
||||
name,
|
||||
refName,
|
||||
accessibilityLabel: status.upstreamRef ? `${name}, upstream branch` : `${name}, local branch`,
|
||||
};
|
||||
if (status.upstreamRef) return branchPickerItem(status.upstreamRef, "upstream branch");
|
||||
return branchPickerItem(`refs/heads/${currentBranch}`, "local branch");
|
||||
}
|
||||
|
||||
export function pickerItemToCheckoutRequest(
|
||||
|
||||
@@ -1194,9 +1194,12 @@ export function NewWorkspaceScreen({
|
||||
withConnectedClient,
|
||||
});
|
||||
|
||||
const workspaceStart = forkDraftSetup ? "fork" : "fresh";
|
||||
const baseItem = useMemo(
|
||||
() => selectedItem ?? (checkoutStatus ? defaultBasePickerItem(checkoutStatus) : null),
|
||||
[checkoutStatus, selectedItem],
|
||||
() =>
|
||||
selectedItem ??
|
||||
(checkoutStatus ? defaultBasePickerItem(checkoutStatus, workspaceStart) : null),
|
||||
[checkoutStatus, selectedItem, workspaceStart],
|
||||
);
|
||||
const { options, itemById, selectedOptionId }: PickerOptionData = useMemo(
|
||||
() =>
|
||||
@@ -1352,7 +1355,7 @@ export function NewWorkspaceScreen({
|
||||
? checkoutRequestOrExplain(
|
||||
() =>
|
||||
setup.checkoutRequestFor(
|
||||
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate),
|
||||
selectedItem ?? defaultBasePickerItem(checkoutStatusForCreate, workspaceStart),
|
||||
),
|
||||
t,
|
||||
)
|
||||
@@ -1396,6 +1399,7 @@ export function NewWorkspaceScreen({
|
||||
t,
|
||||
withConnectedClient,
|
||||
workingDirectory,
|
||||
workspaceStart,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -54,7 +54,10 @@ export function addRunOptions(cmd: Command): Command {
|
||||
)
|
||||
.option("--worktree-slug <slug>", "Managed worktree path slug")
|
||||
.option("--new-branch <name>", "New branch name for branch-off mode")
|
||||
.option("--base <ref>", "Base ref for branch-off mode")
|
||||
.option(
|
||||
"--base <ref>",
|
||||
"Base ref for branch-off mode. A bare branch resolves remote-first; use refs/heads/<name> for local commits",
|
||||
)
|
||||
.option("--branch <name>", "Existing branch for checkout-branch mode")
|
||||
.option("--pr-number <n>", "Pull request or change request number for checkout-pr mode")
|
||||
.option("--forge <forge>", "Forge for checkout-pr mode")
|
||||
|
||||
@@ -31,7 +31,10 @@ export function createWorkspaceCommand(): Command {
|
||||
)
|
||||
.option("--worktree-slug <slug>", "Managed worktree path slug")
|
||||
.option("--new-branch <name>", "New branch name (--mode branch-off)")
|
||||
.option("--base <ref>", "Base ref (--mode branch-off)")
|
||||
.option(
|
||||
"--base <ref>",
|
||||
"Base ref (--mode branch-off). A bare branch resolves remote-first; use refs/heads/<name> for local commits",
|
||||
)
|
||||
.option("--branch <name>", "Existing branch (--mode checkout-branch)")
|
||||
.option("--pr-number <n>", "Pull request or change request number (--mode checkout-pr)")
|
||||
.option("--forge <forge>", "Forge for --mode checkout-pr (default: source checkout)")
|
||||
|
||||
@@ -23,7 +23,7 @@ export function createWorktreeCommand(): Command {
|
||||
.option("--new-branch <name>", "New branch name (--mode branch-off)")
|
||||
.option(
|
||||
"--base <ref>",
|
||||
"Base ref for new branch (--mode branch-off, defaults to repo default)",
|
||||
"Base ref for new branch (--mode branch-off, defaults to repo default). A bare branch resolves remote-first; use refs/heads/<name> for local commits",
|
||||
)
|
||||
.option("--branch <name>", "Existing branch to check out (--mode checkout-branch)")
|
||||
.option("--pr-number <n>", "Pull request number (--mode checkout-pr)")
|
||||
|
||||
@@ -6269,6 +6269,23 @@ const CheckoutStatusCommonSchema = z.object({
|
||||
requestId: z.string(),
|
||||
baseRefExact: z.string().nullable().optional(),
|
||||
comparisonBaseRef: z.string().nullable().optional(),
|
||||
// The exact ref a worktree created from this repository starts from when no base is named:
|
||||
// "refs/remotes/origin/main", "refs/remotes/upstream/main" on a fork whose main tracks upstream,
|
||||
// or "refs/heads/main" without a remote. It does not follow currentBranch. Null when the
|
||||
// repository has no default. Absent from daemons that predate it.
|
||||
defaultBaseRef: z.string().nullable().optional(),
|
||||
// The branch baseRefExact stands for, as the daemon resolves it. `remote` is the remote whose
|
||||
// tracking ref the base is, or null for a local branch. `isCurrent` is true when currentBranch is
|
||||
// the base: the local branch the base names, or a branch whose upstream is the remote base. Null
|
||||
// for a tag or commit base. Absent from daemons that predate it.
|
||||
baseRefBranch: z
|
||||
.object({
|
||||
branch: z.string(),
|
||||
remote: z.string().nullable(),
|
||||
isCurrent: z.boolean(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
// The full ref currentBranch tracks, as git resolves `<branch>@{upstream}`:
|
||||
// "refs/remotes/origin/main", "refs/remotes/upstream/main" on a fork, or a
|
||||
// "refs/heads/..." ref for a branch tracking a local branch. Null when there is no
|
||||
|
||||
@@ -110,6 +110,70 @@ describe("wire schemas never reject unknown keys", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkout status base fields", () => {
|
||||
function checkoutStatus(fields: Record<string, unknown>) {
|
||||
return session({
|
||||
type: "checkout_status_response",
|
||||
payload: {
|
||||
cwd: "/repo/.paseo/worktrees/on-main",
|
||||
error: null,
|
||||
requestId: "request-1",
|
||||
isGit: true,
|
||||
isPaseoOwnedWorktree: true,
|
||||
repoRoot: "/repo/.paseo/worktrees/on-main",
|
||||
mainRepoRoot: "/repo",
|
||||
currentBranch: "main",
|
||||
isDirty: false,
|
||||
baseRef: "main",
|
||||
baseRefExact: "refs/remotes/origin/main",
|
||||
aheadBehind: null,
|
||||
aheadOfOrigin: 0,
|
||||
behindOfOrigin: 0,
|
||||
hasRemote: true,
|
||||
remoteUrl: "https://github.com/acme/repo.git",
|
||||
...fields,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function payloadOf(envelope: unknown): Record<string, unknown> {
|
||||
const parsed = WSOutboundMessageSchema.parse(envelope);
|
||||
if (parsed.type !== "session" || parsed.message.type !== "checkout_status_response") {
|
||||
throw new Error("expected a checkout status response");
|
||||
}
|
||||
return parsed.message.payload;
|
||||
}
|
||||
|
||||
it("reads the default base and base branch a newer daemon reports", () => {
|
||||
const envelope = checkoutStatus({
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
});
|
||||
|
||||
expect(validateWSOutboundMessage(envelope).success).toBe(true);
|
||||
expect(payloadOf(envelope)).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("reads a status from a daemon that predates them", () => {
|
||||
const envelope = checkoutStatus({});
|
||||
|
||||
expect(validateWSOutboundMessage(envelope).success).toBe(true);
|
||||
const payload = payloadOf(envelope);
|
||||
expect(payload.defaultBaseRef).toBeUndefined();
|
||||
expect(payload.baseRefBranch).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reads a repository without a default and a tag base", () => {
|
||||
const envelope = checkoutStatus({ defaultBaseRef: null, baseRefBranch: null });
|
||||
|
||||
expect(validateWSOutboundMessage(envelope).success).toBe(true);
|
||||
expect(payloadOf(envelope)).toMatchObject({ defaultBaseRef: null, baseRefBranch: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown list variants degrade to one skipped element", () => {
|
||||
it("keeps a timeline page when one entry has an unknown item type", () => {
|
||||
const result = validateWSOutboundMessage(
|
||||
|
||||
@@ -94,18 +94,14 @@ export class CreateAgentLifecycleDispatch {
|
||||
placement.githubPrNumber = target.prNumber;
|
||||
break;
|
||||
}
|
||||
const base = target.mode === "branch-off" ? target.base : undefined;
|
||||
return this.dependencies.createPaseoWorktreeWorkflow(
|
||||
{
|
||||
...placement,
|
||||
background: input.background,
|
||||
callerWorkspaceId: input.callerWorkspaceId,
|
||||
firstAgentContext: input.firstAgentContext,
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
worktreesRoot: this.dependencies.worktreesRoot,
|
||||
},
|
||||
base ? { resolveDefaultBranch: async () => base } : undefined,
|
||||
);
|
||||
return this.dependencies.createPaseoWorktreeWorkflow({
|
||||
...placement,
|
||||
background: input.background,
|
||||
callerWorkspaceId: input.callerWorkspaceId,
|
||||
firstAgentContext: input.firstAgentContext,
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
worktreesRoot: this.dependencies.worktreesRoot,
|
||||
});
|
||||
}
|
||||
|
||||
registerAutoArchiveIfRequested(input: {
|
||||
|
||||
@@ -527,7 +527,6 @@ function resolveChildAgentCwd(params: {
|
||||
interface CreateMcpWorktreeOptions {
|
||||
input: CreatePaseoWorktreeInput;
|
||||
createPaseoWorktree: CreatePaseoWorktreeWorkflowFn | undefined;
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
}
|
||||
|
||||
async function createMcpWorktree(
|
||||
@@ -537,10 +536,7 @@ async function createMcpWorktree(
|
||||
if (!options.createPaseoWorktree) {
|
||||
throw new Error("Paseo worktree service is not configured");
|
||||
}
|
||||
return await options.createPaseoWorktree(
|
||||
options.input,
|
||||
options.resolveDefaultBranch ? { resolveDefaultBranch: options.resolveDefaultBranch } : {},
|
||||
);
|
||||
return await options.createPaseoWorktree(options.input);
|
||||
} catch (error) {
|
||||
throw toWorktreeRequestError(error);
|
||||
}
|
||||
@@ -576,7 +572,6 @@ async function resolveMcpCwd(params: {
|
||||
) {
|
||||
throw new Error("baseBranch is required when creating a worktree");
|
||||
}
|
||||
const baseBranch = worktree.baseBranch;
|
||||
const createdWorktree = await createMcpWorktree({
|
||||
input: {
|
||||
cwd: params.cwd,
|
||||
@@ -584,6 +579,7 @@ async function resolveMcpCwd(params: {
|
||||
worktreeSlug: worktree.worktreeName,
|
||||
branchName: worktree.branchName,
|
||||
refName: worktree.refName,
|
||||
baseBranch: worktree.baseBranch,
|
||||
action: worktree.action,
|
||||
githubPrNumber: worktree.githubPrNumber,
|
||||
firstAgentContext: { prompt: params.initialPrompt },
|
||||
@@ -592,7 +588,6 @@ async function resolveMcpCwd(params: {
|
||||
worktreesRoot: dependencies.worktreesRoot,
|
||||
},
|
||||
createPaseoWorktree: dependencies.createPaseoWorktree,
|
||||
resolveDefaultBranch: baseBranch ? async () => baseBranch : undefined,
|
||||
});
|
||||
return {
|
||||
resolvedCwd: createdWorktree.workspace.cwd,
|
||||
|
||||
@@ -869,16 +869,13 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
generateWorkspaceName: options.generateWorkspaceName ?? (async () => null),
|
||||
});
|
||||
|
||||
return async (input, serviceOptions) => {
|
||||
return async (input) => {
|
||||
const result = await createPaseoWorktreeWorkflow(
|
||||
{
|
||||
paseoHome: options.paseoHome,
|
||||
createPaseoWorktree: (workflowInput, workflowOptions) =>
|
||||
createPaseoWorktree: (workflowInput) =>
|
||||
createPaseoWorktreeService(workflowInput, {
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: workflowOptions.resolveDefaultBranch }
|
||||
: {}),
|
||||
workspaceGitService,
|
||||
workspaceProvisioning,
|
||||
}),
|
||||
@@ -898,7 +895,6 @@ function createPaseoWorktreeForMcpTest(options: {
|
||||
onScriptsChanged: null,
|
||||
},
|
||||
input,
|
||||
serviceOptions,
|
||||
);
|
||||
options.broadcasts.push(result.workspace.workspaceId);
|
||||
options.createdWorkspaceIds?.push(result.workspace.workspaceId);
|
||||
|
||||
@@ -6263,7 +6263,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
|
||||
expect(pids).toEqual([firstPid]);
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6357,7 +6357,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
|
||||
).toBe(true);
|
||||
} finally {
|
||||
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -6405,7 +6405,7 @@ describe("ACPAgentSession interrupt settlement and hung-cancel retirement (#3256
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -6457,7 +6457,7 @@ lines.on("line", (line) => {
|
||||
await vi.waitFor(() => expect(isProcessAlive(pid)).toBe(false), { timeout: 3_000 });
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
@@ -6548,7 +6548,7 @@ lines.on("line", (line) => {
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
await rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 15_000);
|
||||
|
||||
|
||||
@@ -1637,7 +1637,14 @@ function createToolCatalog(
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("New branch name for branch-off mode."),
|
||||
baseBranch: z.string().trim().min(1).optional().describe("Base ref for branch-off mode."),
|
||||
baseBranch: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"Base ref for branch-off mode. Defaults to the repository default branch. A bare branch name resolves remote-first (origin/<name>); pass refs/heads/<name> to branch from local commits.",
|
||||
),
|
||||
branch: z
|
||||
.string()
|
||||
.trim()
|
||||
|
||||
@@ -1311,23 +1311,17 @@ async function assemblePaseoDaemon({
|
||||
|
||||
const createPaseoWorktreeForTools = async (
|
||||
input: Parameters<typeof createPaseoWorktreeWorkflow>[1],
|
||||
serviceOptions?: Parameters<typeof createPaseoWorktreeWorkflow>[2],
|
||||
) => {
|
||||
return createPaseoWorktreeWorkflow(
|
||||
{
|
||||
lifecycle: pluginRuntime,
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
createPaseoWorktree: async (workflowInput) => {
|
||||
return createRegisteredPaseoWorktree(workflowInput, {
|
||||
lifecycle: pluginRuntime,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? {
|
||||
resolveDefaultBranch: workflowOptions.resolveDefaultBranch,
|
||||
}
|
||||
: {}),
|
||||
workspaceGitService,
|
||||
workspaceProvisioning,
|
||||
});
|
||||
@@ -1358,7 +1352,6 @@ async function assemblePaseoDaemon({
|
||||
onScriptsChanged: null,
|
||||
},
|
||||
input,
|
||||
serviceOptions,
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -47,6 +47,45 @@ describe("checkout status projection", () => {
|
||||
).toMatchObject({ forgeWeb: payload.forgeWeb });
|
||||
});
|
||||
|
||||
test("publishes the repository default and the branch the worktree base stands for", () => {
|
||||
const snapshot: WorkspaceGitRuntimeSnapshot = {
|
||||
cwd: "/repo/.paseo/worktrees/on-main",
|
||||
git: {
|
||||
isGit: true,
|
||||
repoRoot: "/repo/.paseo/worktrees/on-main",
|
||||
mainRepoRoot: "/repo",
|
||||
currentBranch: "main",
|
||||
remoteUrl: "git@github.com:acme/repo.git",
|
||||
isPaseoOwnedWorktree: true,
|
||||
isDirty: false,
|
||||
baseRef: "main",
|
||||
baseRefExact: "refs/remotes/origin/main",
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
aheadBehind: null,
|
||||
upstreamRef: "refs/remotes/origin/main",
|
||||
aheadOfOrigin: 0,
|
||||
behindOfOrigin: 0,
|
||||
hasRemote: true,
|
||||
diffStat: null,
|
||||
},
|
||||
forge: { featuresEnabled: true, authState: "authenticated", pullRequest: null, error: null },
|
||||
};
|
||||
|
||||
const payload = buildCheckoutStatusPayloadFromSnapshot({
|
||||
cwd: snapshot.cwd,
|
||||
requestId: "req-1",
|
||||
snapshot,
|
||||
});
|
||||
|
||||
expect(
|
||||
CheckoutStatusResponseSchema.parse({ type: "checkout_status_response", payload }).payload,
|
||||
).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
});
|
||||
});
|
||||
|
||||
test("includes repository identity fields on the PR status wire payload", () => {
|
||||
const payload = normalizeCheckoutPrStatusPayload(
|
||||
{
|
||||
|
||||
@@ -63,6 +63,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
baseRef: snapshot.git.baseRef,
|
||||
baseRefExact: snapshot.git.baseRefExact,
|
||||
comparisonBaseRef: snapshot.git.comparisonBaseRef,
|
||||
defaultBaseRef: snapshot.git.defaultBaseRef,
|
||||
baseRefBranch: snapshot.git.baseRefBranch,
|
||||
aheadBehind: snapshot.git.aheadBehind ?? null,
|
||||
upstreamRef: snapshot.git.upstreamRef ?? null,
|
||||
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
|
||||
@@ -90,6 +92,8 @@ export function buildCheckoutStatusPayloadFromSnapshot({
|
||||
baseRef: snapshot.git.baseRef ?? null,
|
||||
baseRefExact: snapshot.git.baseRefExact,
|
||||
comparisonBaseRef: snapshot.git.comparisonBaseRef,
|
||||
defaultBaseRef: snapshot.git.defaultBaseRef,
|
||||
baseRefBranch: snapshot.git.baseRefBranch,
|
||||
aheadBehind: snapshot.git.aheadBehind ?? null,
|
||||
upstreamRef: snapshot.git.upstreamRef ?? null,
|
||||
aheadOfOrigin: snapshot.git.aheadOfOrigin ?? null,
|
||||
|
||||
@@ -832,8 +832,9 @@ test("does not mark checkout branch worktrees as eligible for first-agent rename
|
||||
expect(await readPaseoWorktreeMetadata(created.worktree.worktreePath)).toMatchObject({
|
||||
version: 1,
|
||||
baseRefName: "main",
|
||||
baseRef: "refs/heads/main",
|
||||
});
|
||||
expect(created.workspace.baseBranch).toBe("main");
|
||||
expect(created.workspace.baseBranch).toBe("refs/heads/main");
|
||||
await expect(
|
||||
attemptFirstAgentBranchAutoName({
|
||||
cwd: created.worktree.worktreePath,
|
||||
@@ -1397,7 +1398,6 @@ function createWorkspaceGitServiceStub(): WorkspaceGitService {
|
||||
throw new Error("Create worktree requires a git repository");
|
||||
}
|
||||
},
|
||||
resolveDefaultBranch: async () => "main",
|
||||
refresh: async () => {},
|
||||
requestWorkingTreeWatch: async (cwd) => ({
|
||||
repoRoot: cwd,
|
||||
|
||||
@@ -51,9 +51,6 @@ export interface CreatePaseoWorktreeResult {
|
||||
|
||||
export type CreatePaseoWorktreeFn = (
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
) => Promise<CreatePaseoWorktreeResult>;
|
||||
|
||||
export interface AttemptFirstAgentBranchAutoNameResult {
|
||||
|
||||
@@ -19,8 +19,10 @@ interface ResolverHarness {
|
||||
forge: string;
|
||||
forgeService: ForgeService;
|
||||
headRefLookups: GitHubHeadRefLookup[];
|
||||
resolveDefaultBranch: (repoRoot: string) => Promise<string>;
|
||||
resolveDefaultBaseRef: ResolveWorktreeCreationIntentDeps["resolveDefaultBaseRef"];
|
||||
resolveDefaultBranch: ResolveWorktreeCreationIntentDeps["resolveDefaultBranch"];
|
||||
fetchRef: ResolveWorktreeCreationIntentDeps["fetchRef"];
|
||||
resolveRemoteBranchBaseRef: ResolveWorktreeCreationIntentDeps["resolveRemoteBranchBaseRef"];
|
||||
}
|
||||
|
||||
function createResolverHarness(overrides?: {
|
||||
@@ -87,8 +89,11 @@ function createResolverHarness(overrides?: {
|
||||
forge,
|
||||
forgeService,
|
||||
headRefLookups,
|
||||
resolveDefaultBaseRef: async () => "refs/remotes/origin/main",
|
||||
resolveDefaultBranch: async () => "main",
|
||||
fetchRef: async () => "origin",
|
||||
resolveRemoteBranchBaseRef: async (_repoRoot, { remote, branch }) =>
|
||||
`refs/remotes/${remote}/${branch}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -102,7 +107,7 @@ describe("resolveWorktreeCreationIntent", () => {
|
||||
resolveWorktreeCreationIntent({ worktreeSlug: "generated-worktree" }, repoRoot, deps),
|
||||
).resolves.toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/remotes/origin/main",
|
||||
branchName: "generated-worktree",
|
||||
});
|
||||
expect(deps.headRefLookups).toEqual([]);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ForgeService, PullRequestCheckoutTarget } from "../services/forge-service.js";
|
||||
import type { WorktreeCheckoutRef, WorktreeSource } from "../utils/worktree.js";
|
||||
import type { RemoteBranch } from "../utils/worktree-base-ref.js";
|
||||
import type { UntrustedWorkspaceSource } from "./workspace-automation-gate.js";
|
||||
|
||||
export type WorktreeCreationIntent = Exclude<
|
||||
@@ -43,9 +44,13 @@ export interface ResolveWorktreeCreationIntentInput {
|
||||
export interface ResolveWorktreeCreationIntentDeps {
|
||||
forge: string;
|
||||
forgeService: ForgeService;
|
||||
resolveDefaultBranch: (repoRoot: string) => Promise<string>;
|
||||
/** The ref a new branch starts from when the request names none. */
|
||||
resolveDefaultBaseRef: (repoRoot: string) => Promise<string | null>;
|
||||
/** The name of the branch that ref stands for, for a change request that reports no base. */
|
||||
resolveDefaultBranch: (repoRoot: string) => Promise<string | null>;
|
||||
/** Fetches the first ref a remote serves into a local ref, and returns that remote's name. */
|
||||
fetchRef: (input: FetchRefInput) => Promise<string>;
|
||||
resolveRemoteBranchBaseRef: (repoRoot: string, branch: RemoteBranch) => Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface FetchRefInput {
|
||||
@@ -104,7 +109,8 @@ export async function resolveWorktreeCreationIntent(
|
||||
}
|
||||
return {
|
||||
kind: "branch-off",
|
||||
baseBranch: input.refName?.trim() || (await resolveDefaultBranch(repoRoot, deps)),
|
||||
// A supplied base, even a blank one, is validated by the caller; only an omitted one defaults.
|
||||
baseBranch: input.refName ?? (await resolveDefaultBaseRef(repoRoot, deps)),
|
||||
branchName,
|
||||
};
|
||||
}
|
||||
@@ -143,17 +149,17 @@ export async function resolveWorktreeCreationIntent(
|
||||
});
|
||||
}
|
||||
|
||||
if (input.refName?.trim()) {
|
||||
if (input.refName !== undefined) {
|
||||
return {
|
||||
kind: "branch-off",
|
||||
baseBranch: input.refName.trim(),
|
||||
baseBranch: input.refName,
|
||||
branchName: input.branchName ?? input.worktreeSlug ?? "worktree",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "branch-off",
|
||||
baseBranch: await resolveDefaultBranch(repoRoot, deps),
|
||||
baseBranch: await resolveDefaultBaseRef(repoRoot, deps),
|
||||
branchName: input.branchName ?? input.worktreeSlug ?? "worktree",
|
||||
};
|
||||
}
|
||||
@@ -192,19 +198,11 @@ async function fetchChangeRequestHead(params: {
|
||||
destination: startPoint,
|
||||
});
|
||||
const baseName = checkout.trackOriginHead ? checkout.headRef : checkout.baseRefName;
|
||||
const baseBranch = `refs/remotes/${remote}/${baseName}`;
|
||||
try {
|
||||
// Compared as the remote has it, not as a local branch last pulled.
|
||||
await deps.fetchRef({
|
||||
repoRoot,
|
||||
sources: [{ remoteName: remote, remoteRef: `refs/heads/${baseName}` }],
|
||||
destination: baseBranch,
|
||||
});
|
||||
return { baseBranch, startPoint, untrustedSource };
|
||||
} catch {
|
||||
// Without the remote's copy, the base resolves as any base branch name does.
|
||||
return { baseBranch: baseName, startPoint, untrustedSource };
|
||||
}
|
||||
// Compared as the remote has it, not as a local branch last pulled. Without a tracking ref of
|
||||
// its own on that remote, the base resolves as any base branch name does.
|
||||
const baseBranch =
|
||||
(await deps.resolveRemoteBranchBaseRef(repoRoot, { remote, branch: baseName })) ?? baseName;
|
||||
return { baseBranch, startPoint, untrustedSource };
|
||||
}
|
||||
|
||||
interface PrCheckoutIntentParams {
|
||||
@@ -333,15 +331,23 @@ async function resolvePrCheckoutTarget(params: {
|
||||
});
|
||||
}
|
||||
|
||||
async function resolveDefaultBaseRef(
|
||||
repoRoot: string,
|
||||
deps: ResolveWorktreeCreationIntentDeps,
|
||||
): Promise<string> {
|
||||
return requireDefault(await deps.resolveDefaultBaseRef(repoRoot));
|
||||
}
|
||||
|
||||
async function resolveDefaultBranch(
|
||||
repoRoot: string,
|
||||
deps: ResolveWorktreeCreationIntentDeps,
|
||||
): Promise<string> {
|
||||
const baseBranch = await deps.resolveDefaultBranch(repoRoot);
|
||||
if (!baseBranch) {
|
||||
throw new Error("Unable to resolve repository default branch");
|
||||
}
|
||||
return baseBranch;
|
||||
return requireDefault(await deps.resolveDefaultBranch(repoRoot));
|
||||
}
|
||||
|
||||
function requireDefault(value: string | null): string {
|
||||
if (!value) throw new Error("Unable to resolve repository default branch");
|
||||
return value;
|
||||
}
|
||||
|
||||
async function resolvePrHeadRef(params: {
|
||||
|
||||
@@ -1452,8 +1452,7 @@ export class Session {
|
||||
agentStorage: this.agentStorage,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
createPaseoWorktreeWorkflow: (input, workflowOptions) =>
|
||||
this.createPaseoWorktreeWorkflow(input, workflowOptions),
|
||||
createPaseoWorktreeWorkflow: (input) => this.createPaseoWorktreeWorkflow(input),
|
||||
archiveAgentForClose: (agentId) => this.archiveAgentForClose(agentId),
|
||||
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
|
||||
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
|
||||
@@ -7151,17 +7150,11 @@ export class Session {
|
||||
|
||||
private async createPaseoWorktree(
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
): Promise<CreatePaseoWorktreeResult> {
|
||||
const result = await createPaseoWorktree(input, {
|
||||
lifecycle: this.pluginRuntime,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
github: this.github,
|
||||
...(options?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: options.resolveDefaultBranch }
|
||||
: {}),
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
workspaceProvisioning: this.workspaceProvisioning,
|
||||
});
|
||||
@@ -8234,26 +8227,22 @@ export class Session {
|
||||
|
||||
const sourceCwd = await resolveWorktreeSourceCwd(source, this.projectRegistry);
|
||||
|
||||
const result = await this.createPaseoWorktreeWorkflow(
|
||||
{
|
||||
cwd: sourceCwd,
|
||||
workspaceId,
|
||||
projectId: source.projectId,
|
||||
worktreeSlug: source.worktreeSlug,
|
||||
action: source.action,
|
||||
refName: source.refName,
|
||||
branchName: source.branchName,
|
||||
checkoutSource: source.checkoutSource,
|
||||
githubPrNumber: source.githubPrNumber,
|
||||
firstAgentContext: request.firstAgentContext,
|
||||
title: request.title,
|
||||
metadata: request.metadata,
|
||||
...(await this.workspaceBackgroundIntent(request.background, request.callerAgentId)),
|
||||
},
|
||||
source.baseBranch
|
||||
? { resolveDefaultBranch: async () => source.baseBranch as string }
|
||||
: undefined,
|
||||
);
|
||||
const result = await this.createPaseoWorktreeWorkflow({
|
||||
cwd: sourceCwd,
|
||||
workspaceId,
|
||||
projectId: source.projectId,
|
||||
worktreeSlug: source.worktreeSlug,
|
||||
action: source.action,
|
||||
refName: source.refName,
|
||||
baseBranch: source.baseBranch,
|
||||
branchName: source.branchName,
|
||||
checkoutSource: source.checkoutSource,
|
||||
githubPrNumber: source.githubPrNumber,
|
||||
firstAgentContext: request.firstAgentContext,
|
||||
title: request.title,
|
||||
metadata: request.metadata,
|
||||
...(await this.workspaceBackgroundIntent(request.background, request.callerAgentId)),
|
||||
});
|
||||
|
||||
const descriptor = await this.describeCreatedWorktreeWorkspace(result);
|
||||
await this.emitCreatedWorkspaceUpdate(
|
||||
@@ -8826,17 +8815,13 @@ export class Session {
|
||||
|
||||
private async createPaseoWorktreeWorkflow(
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
): Promise<CreatePaseoWorktreeWorkflowResult> {
|
||||
return createWorktreeWorkflow(
|
||||
{
|
||||
lifecycle: this.commandLifecycle,
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
createPaseoWorktree: (workflowInput, serviceOptions) =>
|
||||
this.createPaseoWorktree(workflowInput, serviceOptions),
|
||||
createPaseoWorktree: (workflowInput) => this.createPaseoWorktree(workflowInput),
|
||||
warmWorkspaceGitData: (workspace) => this.warmWorkspaceGitDataForWorkspace(workspace),
|
||||
autoNameWorkspaceBranchForFirstAgent: (autoNameInput) =>
|
||||
this.workspaceAutoName.scheduleForWorktree(autoNameInput, {
|
||||
@@ -8862,7 +8847,6 @@ export class Session {
|
||||
},
|
||||
},
|
||||
input,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1152,7 +1152,6 @@ test("create_agent_request launches from an exact subdirectory in a created work
|
||||
mainRepoRoot: null,
|
||||
}),
|
||||
resolveRepoRoot: async () => parent,
|
||||
resolveDefaultBranch: async () => "main",
|
||||
});
|
||||
await projectRegistry.upsert(
|
||||
createPersistedProjectRecord({
|
||||
@@ -9394,7 +9393,6 @@ test("workspace.create worktree source checks out a GitHub PR from githubPrNumbe
|
||||
workspaceRegistry,
|
||||
workspaceGitService: createNoopWorkspaceGitService({
|
||||
resolveRepoRoot: async () => fixture.repoDir,
|
||||
resolveDefaultBranch: async () => "main",
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
+22
-9
@@ -1,7 +1,11 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { basename } from "node:path";
|
||||
|
||||
import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
|
||||
import {
|
||||
resolveRepositoryDefaultBaseRef,
|
||||
resolveBaseRefInput,
|
||||
refreshRemoteBaseRef,
|
||||
} from "../../../utils/worktree-base-ref.js";
|
||||
import { runWithRepositoryRoot } from "../../../utils/git-repository-discovery.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
@@ -199,7 +203,7 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
source = {
|
||||
kind: "restore",
|
||||
branchName: checkout.branch,
|
||||
baseRef: workspace.baseBranch,
|
||||
baseRef: await resolveRestoredBranchBase(sourceRepoRoot, workspace.baseBranch),
|
||||
};
|
||||
} else if (checkout.kind === "commit") {
|
||||
source = {
|
||||
@@ -323,17 +327,19 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesBaseRoot: deps.worktreesRoot,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
run: () =>
|
||||
deps.worktreeManagers!.restoreWorktree(
|
||||
run: async () => {
|
||||
if (source.kind !== "restore") await refreshRemoteBaseRef(sourceRepoRoot, source.baseRef);
|
||||
return deps.worktreeManagers!.restoreWorktree(
|
||||
{
|
||||
repoRoot: sourceRepoRoot,
|
||||
path: previousWorktreePath,
|
||||
target: restoreTargetFromWorktreeSource(source),
|
||||
baseRef: workspace.baseBranch,
|
||||
baseRef: source.baseRef ?? null,
|
||||
untrusted,
|
||||
},
|
||||
{ preferredPluginId: managerPluginId },
|
||||
),
|
||||
);
|
||||
},
|
||||
verifyValidatedPath: (validatedPath, pluginId) => {
|
||||
if (!createRealpathAwarePathMatcher(previousWorktreePath)(validatedPath)) {
|
||||
throw new WorktreeRequestError({
|
||||
@@ -377,16 +383,23 @@ function restoreTargetFromWorktreeSource(
|
||||
return { type: "from-base", branch: source.branchName, baseRef: source.baseRef };
|
||||
}
|
||||
|
||||
async function resolveRestoredBranchBase(
|
||||
repoRoot: string,
|
||||
recordedBase: string | null,
|
||||
): Promise<string | null> {
|
||||
if (!recordedBase || recordedBase.startsWith("refs/")) return recordedBase;
|
||||
return resolveBaseRefInput(repoRoot, recordedBase).catch(() => recordedBase);
|
||||
}
|
||||
|
||||
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
|
||||
if (recordedBase) {
|
||||
try {
|
||||
await runGitCommand(["rev-parse", "--verify", `${recordedBase}^{commit}`], { cwd: repoRoot });
|
||||
return recordedBase;
|
||||
return await resolveBaseRefInput(repoRoot, recordedBase);
|
||||
} catch {
|
||||
// The saved base was removed; use the repository default for continued work.
|
||||
}
|
||||
}
|
||||
const defaultBranch = await resolveRepositoryDefaultBranch(repoRoot);
|
||||
const defaultBranch = await resolveRepositoryDefaultBaseRef(repoRoot);
|
||||
if (!defaultBranch) {
|
||||
throw new WorktreeRequestError({
|
||||
code: "unknown",
|
||||
|
||||
@@ -62,7 +62,6 @@ export function createNoopWorkspaceGitService(
|
||||
},
|
||||
resolveForge: async () => null,
|
||||
resolveRepoRoot: async (cwd: string) => cwd,
|
||||
resolveDefaultBranch: async () => "main",
|
||||
resolveRepoRemoteUrl: async () => null,
|
||||
refresh: async () => {},
|
||||
requestWorkingTreeWatch: async () => ({
|
||||
|
||||
@@ -295,6 +295,8 @@ function createFallbackWorkspaceGitSnapshot(cwd: string): WorkspaceGitRuntimeSna
|
||||
isPaseoOwnedWorktree: false,
|
||||
isDirty: null,
|
||||
baseRef: null,
|
||||
defaultBaseRef: null,
|
||||
baseRefBranch: null,
|
||||
aheadBehind: null,
|
||||
upstreamRef: null,
|
||||
aheadOfOrigin: null,
|
||||
@@ -346,7 +348,6 @@ function createFallbackWorkspaceGitService(): WorkspaceGitService {
|
||||
return deriveProjectSlug(cwd, snapshot.git.isGit ? snapshot.git.remoteUrl : null);
|
||||
},
|
||||
resolveRepoRoot: async (cwd: string) => cwd,
|
||||
resolveDefaultBranch: async () => "main",
|
||||
resolveRepoRemoteUrl: async () => null,
|
||||
refresh: async () => {},
|
||||
requestWorkingTreeWatch: async () => ({
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
type WebSocketLike,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import { getCheckoutShortstat } from "../utils/checkout-git.js";
|
||||
import { readPaseoWorktreeMetadata } from "../utils/worktree-metadata.js";
|
||||
|
||||
// The reshaped workspace.create.request forwards its worktree `source`
|
||||
// (action/refName/branchName/githubPrNumber/worktreeSlug) into createWorktreeCore.
|
||||
@@ -558,7 +560,7 @@ async function createRestorableWorkspace(baseRef: string) {
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
});
|
||||
createDivergentBases(repoDir);
|
||||
createDivergentBases(repoDir, tempRoot);
|
||||
await client.connect();
|
||||
const created = await client.createWorkspace({
|
||||
source: {
|
||||
@@ -586,16 +588,19 @@ async function createRestorableWorkspace(baseRef: string) {
|
||||
|
||||
type RestorableWorkspace = Awaited<ReturnType<typeof createRestorableWorkspace>>;
|
||||
|
||||
function createDivergentBases(repoDir: string): void {
|
||||
function createDivergentBases(repoDir: string, tempRoot: string): void {
|
||||
const root = runGit(repoDir, "rev-parse", "HEAD");
|
||||
// Same displayed name, three different commit streams.
|
||||
commitFile(repoDir, "local.txt", "local base\n");
|
||||
runGit(repoDir, "switch", "--detach", root);
|
||||
commitFile(repoDir, "origin.txt", "origin base\n");
|
||||
runGit(repoDir, "update-ref", "refs/remotes/origin/main", "HEAD");
|
||||
runGit(repoDir, "switch", "--detach", root);
|
||||
commitFile(repoDir, "upstream.txt", "upstream base\n");
|
||||
runGit(repoDir, "update-ref", "refs/remotes/upstream/main", "HEAD");
|
||||
for (const remote of ["origin", "upstream"]) {
|
||||
const remoteDir = path.join(tempRoot, `${remote}.git`);
|
||||
runGit(tempRoot, "init", "--bare", "-b", "main", remoteDir);
|
||||
runGit(repoDir, "remote", "add", remote, remoteDir);
|
||||
runGit(repoDir, "switch", "--detach", root);
|
||||
commitFile(repoDir, `${remote}.txt`, `${remote} base\n`);
|
||||
runGit(repoDir, "push", remote, "HEAD:refs/heads/main");
|
||||
runGit(repoDir, "fetch", remote);
|
||||
}
|
||||
runGit(repoDir, "switch", "main");
|
||||
}
|
||||
|
||||
@@ -1012,3 +1017,107 @@ test("agent creation rejects legacy worktree intent without provisioning or exec
|
||||
await rm(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("worktree creation refreshes remote defaults and preserves explicit local bases", async () => {
|
||||
const daemon = await createTestPaseoDaemon({ mcpEnabled: true });
|
||||
const { repoDir, tempRoot } = createGitRepoWithBranch();
|
||||
const remote = path.join(tempRoot, "remote.git");
|
||||
const writer = path.join(tempRoot, "writer");
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
appVersion: "0.1.82",
|
||||
});
|
||||
const mcp = new Client({ name: "base-ref-test", version: "1.0.0" });
|
||||
try {
|
||||
git(tempRoot, "clone", "--bare", repoDir, remote);
|
||||
git(repoDir, "remote", "add", "origin", remote);
|
||||
git(repoDir, "fetch", "origin");
|
||||
git(tempRoot, "clone", remote, writer);
|
||||
git(writer, "config", "user.name", "Test");
|
||||
git(writer, "config", "user.email", "test@example.com");
|
||||
const advance = (name: string) => {
|
||||
writeFileSync(path.join(writer, name), `${name}\n`);
|
||||
git(writer, "add", name);
|
||||
git(writer, "-c", "commit.gpgsign=false", "commit", "-m", name);
|
||||
git(writer, "push", "origin", "main");
|
||||
return git(writer, "rev-parse", "HEAD");
|
||||
};
|
||||
await client.connect();
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${daemon.port}/mcp/agents`)),
|
||||
);
|
||||
const firstTip = advance("first.txt");
|
||||
const created = await mcp.callTool({
|
||||
name: "create_workspace",
|
||||
arguments: { isolation: "worktree", path: repoDir, worktreeSlug: "mcp-base" },
|
||||
});
|
||||
if (typeof created.structuredContent?.workspaceId !== "string")
|
||||
throw new Error(JSON.stringify(created));
|
||||
const mcpWorkspace = (await client.fetchWorkspaces()).entries.find(
|
||||
(entry) => entry.id === created.structuredContent?.workspaceId,
|
||||
);
|
||||
if (!mcpWorkspace?.workspaceDirectory) throw new Error("Missing MCP workspace path");
|
||||
const mcpPath = mcpWorkspace.workspaceDirectory;
|
||||
expect(git(mcpPath, "rev-parse", "HEAD")).toBe(firstTip);
|
||||
expect(await readPaseoWorktreeMetadata(mcpPath)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
const secondTip = advance("second.txt");
|
||||
const rpc = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repoDir, worktreeSlug: "rpc-base", baseBranch: "main" },
|
||||
});
|
||||
if (!rpc.workspace || rpc.error || !rpc.workspace.workspaceDirectory)
|
||||
throw new Error(rpc.error ?? "Missing RPC workspace path");
|
||||
expect(git(rpc.workspace.workspaceDirectory, "rev-parse", "HEAD")).toBe(secondTip);
|
||||
expect(await readPaseoWorktreeMetadata(rpc.workspace.workspaceDirectory)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
git(mcpPath, "rebase", "refs/remotes/origin/main");
|
||||
expect((await client.getCheckoutDiff(mcpPath, { mode: "base" })).files).toEqual([]);
|
||||
expect(await getCheckoutShortstat(mcpPath, undefined, { force: true })).toBeNull();
|
||||
const thirdTip = advance("third.txt");
|
||||
const local = await client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "local-base",
|
||||
refName: "refs/heads/main",
|
||||
},
|
||||
});
|
||||
if (!local.workspace || local.error || !local.workspace.workspaceDirectory)
|
||||
throw new Error(local.error ?? "Missing local workspace path");
|
||||
expect(git(local.workspace.workspaceDirectory, "rev-parse", "HEAD")).toBe(
|
||||
git(repoDir, "rev-parse", "refs/heads/main"),
|
||||
);
|
||||
expect(await readPaseoWorktreeMetadata(local.workspace.workspaceDirectory)).toMatchObject({
|
||||
baseRef: "refs/heads/main",
|
||||
});
|
||||
expect(git(repoDir, "rev-parse", "refs/remotes/origin/main")).toBe(secondTip);
|
||||
const bare = await mcp.callTool({
|
||||
name: "create_workspace",
|
||||
arguments: {
|
||||
isolation: "worktree",
|
||||
path: repoDir,
|
||||
worktreeSlug: "mcp-bare",
|
||||
baseBranch: "main",
|
||||
},
|
||||
});
|
||||
if (typeof bare.structuredContent?.workspaceId !== "string")
|
||||
throw new Error(JSON.stringify(bare));
|
||||
const bareWorkspace = (await client.fetchWorkspaces()).entries.find(
|
||||
(entry) => entry.id === bare.structuredContent?.workspaceId,
|
||||
);
|
||||
if (!bareWorkspace?.workspaceDirectory) throw new Error("Missing bare MCP workspace path");
|
||||
expect(git(bareWorkspace.workspaceDirectory, "rev-parse", "HEAD")).toBe(thirdTip);
|
||||
expect(await readPaseoWorktreeMetadata(bareWorkspace.workspaceDirectory)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
} finally {
|
||||
await mcp.close().catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await daemon.close();
|
||||
await rm(tempRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 180000);
|
||||
|
||||
@@ -329,7 +329,6 @@ interface CreateServiceOptions {
|
||||
getPullRequestStatus?: ReturnType<typeof vi.fn>;
|
||||
getCheckoutDiff?: ReturnType<typeof vi.fn>;
|
||||
resolveBranchCheckout?: ReturnType<typeof vi.fn>;
|
||||
resolveRepositoryDefaultBranch?: ReturnType<typeof vi.fn>;
|
||||
listBranchSuggestions?: ReturnType<typeof vi.fn>;
|
||||
listPaseoWorktrees?: ReturnType<typeof vi.fn>;
|
||||
github?: ForgeService;
|
||||
@@ -361,7 +360,6 @@ function buildDefaultServiceDeps() {
|
||||
getPullRequestStatus: vi.fn(async () => createPullRequestStatusResult()),
|
||||
getCheckoutDiff: vi.fn(async () => ({ diff: "", structured: [] })),
|
||||
resolveBranchCheckout: vi.fn(async () => ({ kind: "not-found" })),
|
||||
resolveRepositoryDefaultBranch: vi.fn(async () => "main"),
|
||||
listBranchSuggestions: vi.fn(async () => []),
|
||||
listPaseoWorktrees: vi.fn(async () => []),
|
||||
forgeOverrides: { github: createGitHubServiceStub() },
|
||||
@@ -2072,36 +2070,6 @@ describe("WorkspaceGitServiceImpl D2 read methods", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("resolveDefaultBranch cold-loads, warms, forces, and coalesces per cwd", async () => {
|
||||
let nowMs = 0;
|
||||
const defaultBranch = createDeferred<string | null>();
|
||||
const resolveRepositoryDefaultBranch = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(async () => defaultBranch.promise)
|
||||
.mockResolvedValue("trunk");
|
||||
const service = createService({
|
||||
resolveRepositoryDefaultBranch,
|
||||
now: () => new Date(nowMs),
|
||||
});
|
||||
|
||||
const first = service.resolveDefaultBranch(REPO_CWD);
|
||||
const second = service.resolveDefaultBranch(join(REPO_CWD, "."));
|
||||
await flushPromises();
|
||||
|
||||
expect(resolveRepositoryDefaultBranch).toHaveBeenCalledTimes(1);
|
||||
defaultBranch.resolve("main");
|
||||
await expect(Promise.all([first, second])).resolves.toEqual(["main", "main"]);
|
||||
|
||||
nowMs = 1_000;
|
||||
await service.resolveDefaultBranch(REPO_CWD);
|
||||
expect(resolveRepositoryDefaultBranch).toHaveBeenCalledTimes(1);
|
||||
|
||||
await service.resolveDefaultBranch(REPO_CWD, { force: true, reason: "test" });
|
||||
expect(resolveRepositoryDefaultBranch).toHaveBeenCalledTimes(2);
|
||||
|
||||
service.dispose();
|
||||
});
|
||||
|
||||
test("resolveRepoRoot cold-loads, warms, forces, and coalesces through snapshots", async () => {
|
||||
let nowMs = 0;
|
||||
const checkoutDeferred = createDeferred<CheckoutStatusGit>();
|
||||
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
projectUpstreamStatus,
|
||||
hasOriginRemote,
|
||||
listBranchSuggestions,
|
||||
resolveRepositoryDefaultBranch,
|
||||
resolveBranchCheckout,
|
||||
resolveAbsoluteGitDir,
|
||||
} from "../utils/checkout-git.js";
|
||||
@@ -59,6 +58,7 @@ import {
|
||||
import type { GitProcessPriority } from "../utils/git-process-scheduler.js";
|
||||
import { GitObservationPaths } from "./git-observation-paths.js";
|
||||
import { branchNameFromRef } from "../utils/worktree-metadata.js";
|
||||
import type { CheckoutBaseBranch } from "../utils/worktree-base-ref.js";
|
||||
import { listPaseoWorktrees, type PaseoWorktreeInfo } from "../utils/worktree.js";
|
||||
import { READ_ONLY_GIT_ENV } from "./checkout-git-utils.js";
|
||||
import { classifyGitMetadataPath, getPrunedGitMetadataPaths } from "./git-metadata-event-rules.js";
|
||||
@@ -200,6 +200,8 @@ export interface WorkspaceGitRuntimeSnapshot {
|
||||
baseRef: string | null;
|
||||
baseRefExact?: string | null;
|
||||
comparisonBaseRef?: string | null;
|
||||
defaultBaseRef: string | null;
|
||||
baseRefBranch: CheckoutBaseBranch | null;
|
||||
aheadBehind: { ahead: number; behind: number } | null;
|
||||
upstreamRef: string | null;
|
||||
aheadOfOrigin: number | null;
|
||||
@@ -290,7 +292,6 @@ export interface WorkspaceGitService {
|
||||
invalidateWorktrees(): void;
|
||||
getProjectSlug(cwd: string, options?: WorkspaceGitReadOptions): Promise<string>;
|
||||
resolveRepoRoot(cwd: string, options?: WorkspaceGitReadOptions): Promise<string>;
|
||||
resolveDefaultBranch(cwdOrRepoRoot: string, options?: WorkspaceGitReadOptions): Promise<string>;
|
||||
resolveRepoRemoteUrl(cwd: string, options?: WorkspaceGitReadOptions): Promise<string | null>;
|
||||
refresh(cwd: string, options?: { priority?: "normal" | "high" }): Promise<void>;
|
||||
requestWorkingTreeWatch(
|
||||
@@ -442,7 +443,6 @@ interface WorkspaceGitServiceDependencies {
|
||||
getCheckoutDiff: typeof getCheckoutDiff;
|
||||
getPullRequestStatus: typeof getPullRequestStatus;
|
||||
resolveBranchCheckout: typeof resolveBranchCheckout;
|
||||
resolveRepositoryDefaultBranch: typeof resolveRepositoryDefaultBranch;
|
||||
listBranchSuggestions: typeof listBranchSuggestions;
|
||||
listPaseoWorktrees: typeof listPaseoWorktrees;
|
||||
/**
|
||||
@@ -686,7 +686,6 @@ function buildDefaultWorkspaceGitServiceDeps(
|
||||
getCheckoutDiff,
|
||||
getPullRequestStatus,
|
||||
resolveBranchCheckout,
|
||||
resolveRepositoryDefaultBranch,
|
||||
listBranchSuggestions,
|
||||
listPaseoWorktrees,
|
||||
resolveAbsoluteGitDir,
|
||||
@@ -770,10 +769,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
string,
|
||||
WorkspaceGitAuxiliaryReadCacheEntry<WorkspaceGitWorktreeInfo[]>
|
||||
>({ max: WORKSPACE_GIT_AUXILIARY_CACHE_MAX });
|
||||
private readonly defaultBranchCache = new LRUCache<
|
||||
string,
|
||||
WorkspaceGitAuxiliaryReadCacheEntry<string>
|
||||
>({ max: WORKSPACE_GIT_AUXILIARY_CACHE_MAX });
|
||||
private readonly retainedSnapshots = new LRUCache<string, RetainedWorkspaceSnapshot>({
|
||||
max: WORKSPACE_GIT_RETAINED_SNAPSHOT_MAX,
|
||||
});
|
||||
@@ -1127,22 +1122,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
this.worktreeListCache.clear();
|
||||
}
|
||||
|
||||
async resolveDefaultBranch(
|
||||
cwdOrRepoRoot: string,
|
||||
options?: WorkspaceGitReadOptions,
|
||||
): Promise<string> {
|
||||
this.assertNotDisposed();
|
||||
const cwd = resolve(cwdOrRepoRoot);
|
||||
const key = JSON.stringify(["default-branch", cwd]);
|
||||
return this.readAuxiliaryCache(this.defaultBranchCache, key, options, async () => {
|
||||
const defaultBranch = await this.deps.resolveRepositoryDefaultBranch(cwd);
|
||||
if (!defaultBranch) {
|
||||
throw new Error("Unable to resolve repository default branch");
|
||||
}
|
||||
return defaultBranch;
|
||||
});
|
||||
}
|
||||
|
||||
async getProjectSlug(cwd: string, options?: WorkspaceGitReadOptions): Promise<string> {
|
||||
const snapshot = await this.getSnapshot(cwd, options);
|
||||
return deriveProjectSlug(resolve(cwd), snapshot.git.isGit ? snapshot.git.remoteUrl : null);
|
||||
@@ -3959,6 +3938,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
baseRef: checkoutStatus.baseRef,
|
||||
baseRefExact: checkoutStatus.baseRefExact,
|
||||
comparisonBaseRef: checkoutStatus.comparisonBaseRef,
|
||||
defaultBaseRef: checkoutStatus.defaultBaseRef,
|
||||
baseRefBranch: checkoutStatus.baseRefBranch,
|
||||
aheadBehind: checkoutStatus.aheadBehind,
|
||||
upstreamRef: checkoutStatus.upstreamRef,
|
||||
aheadOfOrigin: checkoutStatus.aheadOfOrigin,
|
||||
@@ -4849,6 +4830,8 @@ function buildNotGitSnapshot(cwd: string): WorkspaceGitRuntimeSnapshot {
|
||||
isPaseoOwnedWorktree: false,
|
||||
isDirty: null,
|
||||
baseRef: null,
|
||||
defaultBaseRef: null,
|
||||
baseRefBranch: null,
|
||||
aheadBehind: null,
|
||||
upstreamRef: null,
|
||||
aheadOfOrigin: null,
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
getCheckoutStatus,
|
||||
getMainRepoRoot,
|
||||
pushCurrentBranch,
|
||||
resolveRepositoryDefaultBranch,
|
||||
} from "../utils/checkout-git.js";
|
||||
import {
|
||||
getPaseoWorktreeMetadataPath,
|
||||
@@ -35,6 +34,7 @@ import {
|
||||
listPaseoWorktrees,
|
||||
UnknownBranchError,
|
||||
} from "../utils/worktree.js";
|
||||
import { MissingCheckoutTargetError } from "./resolve-worktree-creation-intent.js";
|
||||
import { createWorktreeCore as createCoreWorktree } from "./worktree-core.js";
|
||||
import { isPlatform } from "../test-utils/platform.js";
|
||||
import { createWithWorktrunk } from "../../../../plugin-examples/worktrunk/server/wt.js";
|
||||
@@ -92,7 +92,6 @@ function createGitHubServiceStub(): ForgeService {
|
||||
function createCoreDeps(options?: {
|
||||
github?: ForgeService;
|
||||
forge?: { forge: string; service: ForgeService };
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
resolveRepoRoot?: (cwd: string) => Promise<string>;
|
||||
}) {
|
||||
return {
|
||||
@@ -108,7 +107,6 @@ function createCoreDeps(options?: {
|
||||
}
|
||||
: null,
|
||||
},
|
||||
resolveDefaultBranch: options?.resolveDefaultBranch ?? (async () => "main"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -428,7 +426,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/heads/main",
|
||||
branchName: "legacy-rpc",
|
||||
});
|
||||
expect(result.created).toBe(true);
|
||||
@@ -436,6 +434,35 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
expect(existsSync(result.worktree.worktreePath)).toBe(true);
|
||||
});
|
||||
|
||||
test("refreshes the upstream of a custom default branch without a remote HEAD", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "branch", "-m", "dev");
|
||||
const remote = path.join(tempDir, "remote.git");
|
||||
git(tempDir, "clone", "--bare", repoDir, remote);
|
||||
git(repoDir, "remote", "add", "origin", remote);
|
||||
git(repoDir, "fetch", "origin");
|
||||
git(repoDir, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/dev");
|
||||
git(repoDir, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD");
|
||||
git(repoDir, "branch", "--set-upstream-to=origin/dev", "dev");
|
||||
const writer = path.join(tempDir, "writer");
|
||||
git(tempDir, "clone", remote, writer);
|
||||
git(writer, "config", "user.name", "Test");
|
||||
git(writer, "config", "user.email", "test@example.com");
|
||||
writeFileSync(path.join(writer, "fresh.txt"), "fresh");
|
||||
git(writer, "add", "fresh.txt");
|
||||
git(writer, "-c", "commit.gpgsign=false", "commit", "-m", "fresh");
|
||||
git(writer, "push", "origin", "dev");
|
||||
const result = await createCoreWorktree(
|
||||
{ cwd: repoDir, worktreeSlug: "custom-default", paseoHome },
|
||||
createCoreDeps(),
|
||||
);
|
||||
expect(git(result.worktree.worktreePath, "rev-parse", "HEAD")).toBe(
|
||||
git(writer, "rev-parse", "HEAD"),
|
||||
);
|
||||
expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/origin/dev");
|
||||
});
|
||||
|
||||
test("keeps default placement suffixes when the default destination already exists", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
@@ -468,15 +495,13 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
{ cwd: first.worktreePath, worktreeSlug: "second", paseoHome },
|
||||
createCoreDeps({
|
||||
resolveRepoRoot: (cwd) => getMainRepoRoot(cwd, { paseoHome }),
|
||||
resolveDefaultBranch: async (root) =>
|
||||
(await resolveRepositoryDefaultBranch(root)) ?? "unresolved",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.repoRoot).toBe(bareRepo);
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/heads/main",
|
||||
branchName: "second",
|
||||
});
|
||||
expect(readFileSync(path.join(result.worktree.worktreePath, "README.md"), "utf8")).toBe(
|
||||
@@ -501,7 +526,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/remotes/origin/main",
|
||||
branchName: "no-upstream-feature",
|
||||
});
|
||||
expect(getBranchUpstream(result.worktree.worktreePath)).toBeNull();
|
||||
@@ -622,7 +647,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/heads/main",
|
||||
branchName: "mcp-standalone",
|
||||
});
|
||||
expect(result.worktree.branchName).toBe("mcp-standalone");
|
||||
@@ -654,7 +679,7 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
.trim();
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "dev",
|
||||
baseBranch: "refs/heads/dev",
|
||||
branchName: "from-dev",
|
||||
});
|
||||
expect(mergeBase).toBe(devTip);
|
||||
@@ -743,6 +768,40 @@ describe.skipIf(isPlatform("win32"))("worktree-core POSIX-only", () => {
|
||||
expect(result.worktree.branchName).toBe("pr-123");
|
||||
});
|
||||
|
||||
test("fetches a change request base that is missing from a single-branch clone", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "checkout", "-b", "unrelated");
|
||||
git(repoDir, "branch", "-D", "main");
|
||||
git(repoDir, "update-ref", "-d", "refs/remotes/origin/main");
|
||||
const result = await createCoreWorktree(
|
||||
{ cwd: repoDir, action: "checkout", githubPrNumber: 123, paseoHome },
|
||||
createCoreDeps(),
|
||||
);
|
||||
expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/origin/main");
|
||||
expect(await readPaseoWorktreeMetadata(result.worktree.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
});
|
||||
|
||||
test("checks out a change request when its deleted base cannot be fetched", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "checkout", "-b", "unrelated");
|
||||
git(repoDir, "branch", "-D", "main");
|
||||
git(repoDir, "update-ref", "-d", "refs/remotes/origin/main");
|
||||
const remote = git(repoDir, "remote", "get-url", "origin");
|
||||
git(repoDir, `--git-dir=${remote}`, "update-ref", "-d", "refs/heads/main");
|
||||
const result = await createCoreWorktree(
|
||||
{ cwd: repoDir, action: "checkout", githubPrNumber: 123, paseoHome },
|
||||
createCoreDeps(),
|
||||
);
|
||||
expect(result.worktree.comparisonBaseRef).toBe("main");
|
||||
expect(await readPaseoWorktreeMetadata(result.worktree.worktreePath)).toMatchObject({
|
||||
baseRefName: "main",
|
||||
});
|
||||
});
|
||||
|
||||
test("tracks a same-repo PR branch from a single-branch clone", async () => {
|
||||
const { tempDir, repoDir, remoteDir, paseoHome } = createSameRepoGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
@@ -2041,6 +2100,68 @@ exit 1
|
||||
}
|
||||
});
|
||||
|
||||
test("refuses to guess a base when the repository has no default branch", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "branch", "-m", "release");
|
||||
git(repoDir, "branch", "other");
|
||||
git(repoDir, "checkout", "--detach");
|
||||
|
||||
await expect(
|
||||
createCoreWorktree(
|
||||
{ cwd: repoDir, worktreeSlug: "no-default", paseoHome },
|
||||
createCoreDeps(),
|
||||
),
|
||||
).rejects.toThrow("Unable to resolve repository default branch");
|
||||
});
|
||||
|
||||
test("branches off from baseBranch only when the request names no other target", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "branch", "release");
|
||||
|
||||
const branchOff = await createCoreWorktree(
|
||||
{ cwd: repoDir, worktreeSlug: "from-release", baseBranch: "release", paseoHome },
|
||||
createCoreDeps(),
|
||||
);
|
||||
expect(branchOff.intent).toMatchObject({
|
||||
kind: "branch-off",
|
||||
baseBranch: "refs/heads/release",
|
||||
});
|
||||
|
||||
const checkout = await createCoreWorktree(
|
||||
{ cwd: repoDir, githubPrNumber: 123, baseBranch: "release", paseoHome },
|
||||
createCoreDeps(),
|
||||
);
|
||||
expect(checkout.intent).toMatchObject({
|
||||
kind: "checkout-change-request",
|
||||
headRef: "pr-123",
|
||||
baseRefName: "main",
|
||||
});
|
||||
|
||||
await expect(
|
||||
createCoreWorktree(
|
||||
{ cwd: repoDir, action: "checkout", baseBranch: "release", paseoHome },
|
||||
createCoreDeps(),
|
||||
),
|
||||
).rejects.toBeInstanceOf(MissingCheckoutTargetError);
|
||||
});
|
||||
|
||||
test("rejects a blank base instead of branching from the default", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
|
||||
for (const input of [
|
||||
{ baseBranch: " " },
|
||||
{ action: "branch-off" as const, refName: " " },
|
||||
{ refName: " " },
|
||||
]) {
|
||||
await expect(
|
||||
createCoreWorktree({ cwd: repoDir, paseoHome, ...input }, createCoreDeps()),
|
||||
).rejects.toThrow("Base branch is required");
|
||||
}
|
||||
});
|
||||
|
||||
test("throws a typed error for an unknown checkout branch", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
@@ -2394,6 +2515,43 @@ exit 1
|
||||
expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/upstream/main");
|
||||
});
|
||||
|
||||
test("pins a checked-out change request to the remote that served it", async () => {
|
||||
const { tempDir, repoDir, headRemoteDir, paseoHome } = createForkGitHubPrRemoteRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
git(repoDir, "remote", "rename", "origin", "upstream");
|
||||
git(repoDir, "remote", "add", "origin", headRemoteDir);
|
||||
git(repoDir, "fetch", "origin");
|
||||
const github = {
|
||||
...createGitHubServiceStub(),
|
||||
getPullRequestCheckoutTarget: async () => ({
|
||||
number: 526,
|
||||
baseRefName: "main",
|
||||
headRefName: "main",
|
||||
headOwnerLogin: "therainisme",
|
||||
headRepositorySshUrl: headRemoteDir,
|
||||
headRepositoryUrl: headRemoteDir,
|
||||
isCrossRepository: true,
|
||||
checkoutRefs: [
|
||||
{ remoteName: "origin", remoteRef: "refs/pull/526/head" },
|
||||
{ remoteName: "upstream", remoteRef: "refs/pull/526/head" },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const result = await createCoreWorktree(
|
||||
{
|
||||
cwd: repoDir,
|
||||
action: "checkout",
|
||||
checkoutSource: { kind: "change_request", forge: "github", number: 526 },
|
||||
paseoHome,
|
||||
},
|
||||
createCoreDeps({ github }),
|
||||
);
|
||||
expect(result.worktree.comparisonBaseRef).toBe("refs/remotes/upstream/main");
|
||||
expect(await readPaseoWorktreeMetadata(result.worktree.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/remotes/upstream/main",
|
||||
});
|
||||
});
|
||||
|
||||
test("creates the agent-create worktree input shape", async () => {
|
||||
const { tempDir, repoDir, paseoHome } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
@@ -2409,7 +2567,7 @@ exit 1
|
||||
|
||||
expect(result.intent).toEqual({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
baseBranch: "refs/heads/main",
|
||||
branchName: "agent-worktree",
|
||||
});
|
||||
expect(result.worktree.branchName).toBe("agent-worktree");
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
resolveBaseRefInput,
|
||||
resolveRemoteBranchBaseRef,
|
||||
resolveRepositoryDefaultBaseRef,
|
||||
resolveRepositoryDefaultBranch,
|
||||
} from "../utils/worktree-base-ref.js";
|
||||
import type {
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateRequest,
|
||||
@@ -38,6 +44,11 @@ export interface CreateWorktreeCoreInput {
|
||||
worktreeSlug?: string;
|
||||
branchName?: string;
|
||||
refName?: string;
|
||||
/**
|
||||
* Where a new branch starts when the request names no `refName`. Only a branch-off without a
|
||||
* change request reads it: a checkout or a change request names its own target.
|
||||
*/
|
||||
baseBranch?: string;
|
||||
action?: "branch-off" | "checkout";
|
||||
checkoutSource?: ChangeRequestCheckoutSource;
|
||||
githubPrNumber?: number;
|
||||
@@ -53,11 +64,7 @@ export interface CreateWorktreeCoreDeps {
|
||||
"hasWorktreeManager" | "createWorktree" | "removeWorktree"
|
||||
>;
|
||||
github: ForgeService;
|
||||
workspaceGitService?: Pick<
|
||||
WorkspaceGitService,
|
||||
"resolveRepoRoot" | "resolveDefaultBranch" | "resolveForge"
|
||||
>;
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
workspaceGitService?: Pick<WorkspaceGitService, "resolveRepoRoot" | "resolveForge">;
|
||||
}
|
||||
|
||||
export interface CreateWorktreeCoreResult {
|
||||
@@ -95,46 +102,19 @@ async function createWorktreeAtRepositoryRoot(
|
||||
: undefined;
|
||||
const requestedBranchName = input.branchName?.trim();
|
||||
|
||||
let intentInput: ResolveWorktreeCreationIntentInput;
|
||||
if (input.action === "checkout") {
|
||||
intentInput = {
|
||||
action: "checkout",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
} else if (
|
||||
input.action !== "branch-off" &&
|
||||
(input.checkoutSource !== undefined || input.githubPrNumber !== undefined)
|
||||
) {
|
||||
// A change request with no action is checked out, as clients did before `action` existed.
|
||||
intentInput = {
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
refName: input.refName,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
} else {
|
||||
const worktreeSlug = requestedWorktreeSlug ?? normalizeWorktreeSlug(createNameId());
|
||||
intentInput = {
|
||||
action: "branch-off",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
branchName: requestedBranchName,
|
||||
worktreeSlug,
|
||||
};
|
||||
}
|
||||
const intentInput = toIntentInput(input, requestedWorktreeSlug, requestedBranchName);
|
||||
|
||||
const forge = await resolveForge(repoRoot, deps, intentInput);
|
||||
let intent = await resolveWorktreeCreationIntent(intentInput, repoRoot, {
|
||||
forge: forge.forge,
|
||||
forgeService: forge.service,
|
||||
resolveDefaultBranch: (root) => resolveDefaultBranch(root, deps),
|
||||
resolveDefaultBaseRef: resolveRepositoryDefaultBaseRef,
|
||||
resolveDefaultBranch: resolveRepositoryDefaultBranch,
|
||||
fetchRef: ({ repoRoot: cwd, sources, destination }) =>
|
||||
fetchFirstAvailableRef({ cwd, sources, destination }),
|
||||
resolveRemoteBranchBaseRef,
|
||||
});
|
||||
intent = await normalizeIntentBase(repoRoot, intent);
|
||||
let normalizedSlug: string;
|
||||
|
||||
switch (intent.kind) {
|
||||
@@ -209,6 +189,49 @@ async function createWorktreeAtRepositoryRoot(
|
||||
};
|
||||
}
|
||||
|
||||
function toIntentInput(
|
||||
input: CreateWorktreeCoreInput,
|
||||
requestedWorktreeSlug: string | undefined,
|
||||
requestedBranchName: string | undefined,
|
||||
): ResolveWorktreeCreationIntentInput {
|
||||
const changeRequest = input.checkoutSource !== undefined || input.githubPrNumber !== undefined;
|
||||
if (input.action === "checkout") {
|
||||
return {
|
||||
action: "checkout",
|
||||
refName: input.refName,
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
}
|
||||
if (input.action !== "branch-off" && changeRequest) {
|
||||
// A change request with no action is checked out, as clients did before `action` existed.
|
||||
return {
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
refName: input.refName,
|
||||
worktreeSlug: requestedWorktreeSlug,
|
||||
};
|
||||
}
|
||||
return {
|
||||
action: "branch-off",
|
||||
refName: input.refName ?? (changeRequest ? undefined : input.baseBranch),
|
||||
checkoutSource: input.checkoutSource,
|
||||
githubPrNumber: input.githubPrNumber,
|
||||
branchName: requestedBranchName,
|
||||
worktreeSlug: requestedWorktreeSlug ?? normalizeWorktreeSlug(createNameId()),
|
||||
};
|
||||
}
|
||||
|
||||
async function normalizeIntentBase(
|
||||
repoRoot: string,
|
||||
intent: WorktreeCreationIntent,
|
||||
): Promise<WorktreeCreationIntent> {
|
||||
return intent.kind === "branch-off"
|
||||
? { ...intent, baseBranch: await resolveBaseRefInput(repoRoot, intent.baseBranch) }
|
||||
: intent;
|
||||
}
|
||||
|
||||
async function tryCreateWithWorktreeManager(options: {
|
||||
repoRoot: string;
|
||||
transformed: PluginWorktreeCreateRequest;
|
||||
@@ -322,19 +345,6 @@ async function resolveForge(
|
||||
return { forge: resolution.forge, service: resolution.service };
|
||||
}
|
||||
|
||||
async function resolveDefaultBranch(
|
||||
repoRoot: string,
|
||||
deps: CreateWorktreeCoreDeps,
|
||||
): Promise<string> {
|
||||
const baseBranch = deps.resolveDefaultBranch
|
||||
? await deps.resolveDefaultBranch(repoRoot)
|
||||
: await deps.workspaceGitService?.resolveDefaultBranch(repoRoot);
|
||||
if (!baseBranch) {
|
||||
throw new Error("Unable to resolve repository default branch");
|
||||
}
|
||||
return baseBranch;
|
||||
}
|
||||
|
||||
export async function resolveWorktreeRepoRoot(
|
||||
input: Pick<CreateWorktreeCoreInput, "cwd" | "paseoHome">,
|
||||
workspaceGitService?: Pick<WorkspaceGitService, "resolveRepoRoot">,
|
||||
|
||||
@@ -361,12 +361,9 @@ function createPaseoWorktreeForTest(options: {
|
||||
logger: createLogger(),
|
||||
});
|
||||
|
||||
return (input, serviceOptions) => {
|
||||
return (input) => {
|
||||
return createPaseoWorktreeService(input, {
|
||||
github: createGitHubServiceStub(),
|
||||
...(serviceOptions?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: serviceOptions.resolveDefaultBranch }
|
||||
: {}),
|
||||
workspaceGitService,
|
||||
workspaceProvisioning,
|
||||
});
|
||||
@@ -1437,33 +1434,6 @@ describe("handleCreatePaseoWorktreeRequest", () => {
|
||||
const readme = readFileSync(path.join(worktreePath, "README.md"), "utf8");
|
||||
expect(readme).toContain("review branch");
|
||||
});
|
||||
|
||||
test("createPaseoWorktreeForTest forwards the default branch resolver for branch-off intents", async () => {
|
||||
const { tempDir, repoDir } = createGitRepo();
|
||||
cleanupPaths.push(tempDir);
|
||||
const paseoHome = path.join(tempDir, ".paseo");
|
||||
const resolveDefaultBranch = vi.fn(async () => "main");
|
||||
|
||||
const result = await createPaseoWorktreeForTest({ paseoHome })(
|
||||
{
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "resolver-feature",
|
||||
action: "branch-off",
|
||||
|
||||
paseoHome,
|
||||
},
|
||||
{ resolveDefaultBranch },
|
||||
);
|
||||
|
||||
expect(result.intent).toMatchObject({
|
||||
kind: "branch-off",
|
||||
baseBranch: "main",
|
||||
branchName: "resolver-feature",
|
||||
});
|
||||
const resolvedCwd = resolveDefaultBranch.mock.calls[0]?.[0];
|
||||
expect(resolvedCwd).toBeDefined();
|
||||
expect(realpathSync.native(resolvedCwd ?? "")).toBe(realpathSync.native(repoDir));
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleCreatePaseoWorktreeRequest", () => {
|
||||
|
||||
@@ -67,12 +67,7 @@ interface CreatePaseoWorktreeInBackgroundDependencies {
|
||||
}
|
||||
|
||||
interface CreatePaseoWorktreeWorkflowDependencies extends CreatePaseoWorktreeInBackgroundDependencies {
|
||||
createPaseoWorktree: (
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
) => Promise<CreatePaseoWorktreeResult>;
|
||||
createPaseoWorktree: (input: CreatePaseoWorktreeInput) => Promise<CreatePaseoWorktreeResult>;
|
||||
warmWorkspaceGitData: (workspace: PersistedWorkspaceRecord) => Promise<void>;
|
||||
autoNameWorkspaceBranchForFirstAgent: (input: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
@@ -86,9 +81,6 @@ export type CreatePaseoWorktreeWorkflowResult = CreatePaseoWorktreeResult;
|
||||
|
||||
export type CreatePaseoWorktreeWorkflowFn = (
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
) => Promise<CreatePaseoWorktreeWorkflowResult>;
|
||||
|
||||
interface HandleWorkspaceSetupStatusRequestDependencies {
|
||||
@@ -345,21 +337,13 @@ export async function handleCreatePaseoWorktreeRequest(
|
||||
export async function createPaseoWorktreeWorkflow(
|
||||
dependencies: CreatePaseoWorktreeWorkflowDependencies,
|
||||
input: CreatePaseoWorktreeInput,
|
||||
options?: {
|
||||
resolveDefaultBranch?: (repoRoot: string) => Promise<string>;
|
||||
},
|
||||
): Promise<CreatePaseoWorktreeWorkflowResult> {
|
||||
const createdWorktree = await dependencies.createPaseoWorktree(
|
||||
{
|
||||
...input,
|
||||
const createdWorktree = await dependencies.createPaseoWorktree({
|
||||
...input,
|
||||
|
||||
paseoHome: input.paseoHome ?? dependencies.paseoHome,
|
||||
worktreesRoot: input.worktreesRoot ?? dependencies.worktreesRoot,
|
||||
},
|
||||
options?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: options.resolveDefaultBranch }
|
||||
: undefined,
|
||||
);
|
||||
paseoHome: input.paseoHome ?? dependencies.paseoHome,
|
||||
worktreesRoot: input.worktreesRoot ?? dependencies.worktreesRoot,
|
||||
});
|
||||
const slug = basename(createdWorktree.worktree.worktreePath);
|
||||
const workspace = createdWorktree.workspace;
|
||||
|
||||
|
||||
@@ -4,7 +4,11 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
import { type CheckoutSnapshotFacts, getCheckoutRefDerivedState } from "./checkout-git.js";
|
||||
import {
|
||||
type CheckoutSnapshotFacts,
|
||||
getCheckoutRefDerivedState,
|
||||
getCheckoutSnapshotFacts,
|
||||
} from "./checkout-git.js";
|
||||
import {
|
||||
startGitCommandMetrics,
|
||||
stopGitCommandMetrics,
|
||||
@@ -189,3 +193,31 @@ test("an origin move refreshes an untracked main checkout shortstat", async () =
|
||||
),
|
||||
).toEqual({ aheadBehind: null, diffStat: null, upstreamStatus: { state: "none" } });
|
||||
});
|
||||
|
||||
test("a fetch that moves the tracked default branch ahead makes the main checkout behind", async () => {
|
||||
const { cwd } = seedMainCheckout();
|
||||
git(cwd, ["reset", "--quiet", "--hard", "origin/main"]);
|
||||
git(cwd, ["config", "branch.main.remote", "origin"]);
|
||||
git(cwd, ["config", "branch.main.merge", "refs/heads/main"]);
|
||||
const facts = await getCheckoutSnapshotFacts(cwd);
|
||||
if (!facts.isGit) throw new Error("expected a Git checkout");
|
||||
git(cwd, [
|
||||
"update-ref",
|
||||
"refs/remotes/origin/main",
|
||||
git(cwd, ["commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "remote"]),
|
||||
]);
|
||||
|
||||
const result = await getCheckoutRefDerivedState(
|
||||
cwd,
|
||||
facts,
|
||||
{ aheadBehind: null, diffStat: null },
|
||||
new Set(["origin/main"]),
|
||||
);
|
||||
|
||||
expect(result.aheadBehind).toBeNull();
|
||||
expect(result.upstreamStatus).toEqual({
|
||||
state: "tracked",
|
||||
ref: "refs/remotes/origin/main",
|
||||
aheadBehind: { ahead: 0, behind: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ import {
|
||||
pullCurrentBranch,
|
||||
pushCurrentBranch,
|
||||
resolveBranchCheckout,
|
||||
resolveRepositoryDefaultBranch,
|
||||
parseWorktreeList,
|
||||
renameCurrentBranch,
|
||||
isPaseoWorktreePath,
|
||||
@@ -51,6 +50,7 @@ import {
|
||||
warmCheckoutShortstatInBackground,
|
||||
} from "./checkout-git.js";
|
||||
import { startGitCommandMetrics, stopGitCommandMetrics } from "./run-git-command.js";
|
||||
import { resolveRepositoryDefaultBranch } from "./worktree-base-ref.js";
|
||||
import { createForgeResolver } from "../services/forge-resolver.js";
|
||||
import { GitHubCommandError, GitHubCliMissingError } from "../services/github-service.js";
|
||||
import type { CurrentPullRequestStatus, ForgeService } from "../services/forge-service.js";
|
||||
@@ -321,6 +321,31 @@ describe("checkout git utilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves bare base changes to the remote and preserves explicit local choices", async () => {
|
||||
setupRemoteTrackingMain(repoDir, tempDir);
|
||||
const worktree = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
branchName: "feature/change-base",
|
||||
baseBranch: "refs/heads/main",
|
||||
worktreeSlug: "change-base",
|
||||
paseoHome,
|
||||
runSetup: false,
|
||||
});
|
||||
const context = { paseoHome };
|
||||
await expect(
|
||||
setCheckoutBaseBranch({ cwd: worktree.worktreePath, baseRef: "main", context }),
|
||||
).resolves.toBe("refs/remotes/origin/main");
|
||||
expect(await readPaseoWorktreeMetadata(worktree.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
await expect(
|
||||
setCheckoutBaseBranch({ cwd: worktree.worktreePath, baseRef: "refs/heads/main", context }),
|
||||
).resolves.toBe("refs/heads/main");
|
||||
expect(await readPaseoWorktreeMetadata(worktree.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/heads/main",
|
||||
});
|
||||
});
|
||||
|
||||
it("lists exact local and all remote refs separately for the base picker", async () => {
|
||||
execFileSync("git", ["branch", "release"], { cwd: repoDir });
|
||||
execFileSync("git", ["update-ref", "refs/remotes/origin/release", "HEAD"], { cwd: repoDir });
|
||||
@@ -371,6 +396,36 @@ describe("checkout git utilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("targets the branch of a base on a remote whose name contains a slash", async () => {
|
||||
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir);
|
||||
execFileSync("git", ["remote", "add", "team/company", remoteDir], { cwd: repoDir });
|
||||
execFileSync("git", ["fetch", "team/company"], { cwd: repoDir });
|
||||
const worktree = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
branchName: "feature/team-pr",
|
||||
baseBranch: "team/company/main",
|
||||
worktreeSlug: "team-pr",
|
||||
paseoHome,
|
||||
runSetup: false,
|
||||
});
|
||||
expect(await readPaseoWorktreeMetadata(worktree.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/remotes/team/company/main",
|
||||
});
|
||||
commitFile(worktree.worktreePath, "change.txt", "feature work\n", "feature");
|
||||
const targets: string[] = [];
|
||||
const adapter = createGitHubServiceForStatus(null);
|
||||
adapter.createPullRequest = async ({ base }) => {
|
||||
targets.push(base);
|
||||
return { url: "https://github.com/getpaseo/paseo/pull/2", number: 2 };
|
||||
};
|
||||
|
||||
await createPullRequest(worktree.worktreePath, { title: "Add thing", body: "desc" }, adapter, {
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
expect(targets).toEqual(["main"]);
|
||||
});
|
||||
|
||||
it("resolves a gitlab remote through the resolver and creates via the gitlab adapter", async () => {
|
||||
// origin is a real local bare repo so the push succeeds; the resolver reads a
|
||||
// gitlab remote URL (injected) so it selects the gitlab adapter from the host.
|
||||
@@ -983,7 +1038,7 @@ const x = 1;
|
||||
const metrics = stopGitCommandMetrics();
|
||||
const upstreamCountCommands = metrics.commands.filter(
|
||||
(command) =>
|
||||
command.args[0] === "for-each-ref" && command.args.join(" ").includes("%(upstream)"),
|
||||
command.args[0] === "for-each-ref" && command.args.join(" ").includes("%(upstream:track"),
|
||||
);
|
||||
|
||||
expect(divergedStatus.isGit).toBe(true);
|
||||
@@ -1310,6 +1365,19 @@ const x = 1;
|
||||
execFileSync("git", ["push"], { cwd: cloneDir });
|
||||
}
|
||||
|
||||
it("compares a feature branch against the remote default when no local default exists", async () => {
|
||||
setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
execFileSync("git", ["branch", "-D", "main"], { cwd: repoDir });
|
||||
commitFile(repoDir, "feature.txt", "feature\n", "feature");
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
baseRef: "main",
|
||||
aheadBehind: { ahead: 1, behind: 0 },
|
||||
});
|
||||
expect((await getCheckoutDiff(repoDir, { mode: "base" })).diff).toContain("feature.txt");
|
||||
});
|
||||
|
||||
it("pushes a branch that is ahead to its upstream", async () => {
|
||||
const { remoteDir } = setupRemoteTrackingMain(repoDir, tempDir, "doras-mono");
|
||||
commitFile(repoDir, "local.txt", "local\n", "local commit");
|
||||
@@ -2536,6 +2604,9 @@ const x = 1;
|
||||
});
|
||||
|
||||
it("rejects merging a branch into its own same-named remote base", async () => {
|
||||
execFileSync("git", ["remote", "add", "origin", "https://example.invalid/repo.git"], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
execFileSync("git", ["update-ref", "refs/remotes/origin/main", "HEAD"], { cwd: repoDir });
|
||||
await expect(mergeToBase(repoDir, { baseRef: "refs/remotes/origin/main" })).rejects.toThrow(
|
||||
"Cannot merge a branch into itself",
|
||||
@@ -4558,6 +4629,203 @@ const x = 1;
|
||||
await expect(resolveRepositoryDefaultBranch(repoDir)).resolves.toBe("main");
|
||||
});
|
||||
|
||||
it("compares a local checkout against the default branch new worktrees start from", async () => {
|
||||
execFileSync("git", ["branch", "-m", "main", "trunk"], { cwd: repoDir });
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
commitFile(repoDir, "feature.txt", "feature\n", "feature");
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
baseRef: "trunk",
|
||||
aheadBehind: { ahead: 1, behind: 0 },
|
||||
});
|
||||
|
||||
execFileSync("git", ["checkout", "trunk"], { cwd: repoDir });
|
||||
__resetCheckoutShortstatCacheForTests();
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
baseRef: "trunk",
|
||||
aheadBehind: null,
|
||||
});
|
||||
});
|
||||
|
||||
// New Workspace preselects the default the daemon reports, and Git actions read whether the
|
||||
// checkout is on its base from the daemon instead of parsing refs.
|
||||
describe("the base a checkout reports", () => {
|
||||
it("reports the repository default while the checkout sits on a feature branch", async () => {
|
||||
setupRemoteTrackingMain(repoDir, tempDir);
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
currentBranch: "feature",
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: null, isCurrent: false },
|
||||
});
|
||||
|
||||
execFileSync("git", ["checkout", "main"], { cwd: repoDir });
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: null, isCurrent: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("recognizes a worktree checked out on the default branch as on its base", async () => {
|
||||
setupRemoteTrackingMain(repoDir, tempDir);
|
||||
execFileSync("git", ["checkout", "-b", "unrelated"], { cwd: repoDir });
|
||||
const onMain = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "on-main",
|
||||
source: { kind: "checkout-branch", branchName: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
const feature = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
branchName: "feature",
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "feature",
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
expect(await getCheckoutStatus(onMain.worktreePath, { paseoHome })).toMatchObject({
|
||||
currentBranch: "main",
|
||||
baseRefExact: "refs/remotes/origin/main",
|
||||
defaultBaseRef: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: true },
|
||||
});
|
||||
expect(await getCheckoutStatus(feature.worktreePath, { paseoHome })).toMatchObject({
|
||||
currentBranch: "feature",
|
||||
baseRefExact: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a branch that only shares its name with a remote base as off base", async () => {
|
||||
setupRemoteTrackingMain(repoDir, tempDir);
|
||||
execFileSync("git", ["checkout", "-b", "unrelated"], { cwd: repoDir });
|
||||
execFileSync("git", ["branch", "--unset-upstream", "main"], { cwd: repoDir });
|
||||
const onMain = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "untracked-main",
|
||||
source: { kind: "checkout-branch", branchName: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
|
||||
expect(await getCheckoutStatus(onMain.worktreePath, { paseoHome })).toMatchObject({
|
||||
currentBranch: "main",
|
||||
baseRefExact: "refs/remotes/origin/main",
|
||||
baseRefBranch: { branch: "main", remote: "origin", isCurrent: false },
|
||||
});
|
||||
});
|
||||
|
||||
// A fork whose local main tracks upstream/main. Origin holds main as it was when the fork
|
||||
// was made, and upstream has moved on. The checkout sits on a feature branch off old main.
|
||||
function setupForkOnFeatureBranch(): void {
|
||||
const { cloneDir } = setupRemoteTrackingMain(repoDir, tempDir, "upstream");
|
||||
execFileSync("git", ["remote", "add", "origin", join(tempDir, "fork.git")], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
execFileSync("git", ["update-ref", "refs/remotes/origin/main", "refs/heads/main"], {
|
||||
cwd: repoDir,
|
||||
});
|
||||
commitFile(cloneDir, "upstream.txt", "upstream\n", "upstream moved on");
|
||||
execFileSync("git", ["push"], { cwd: cloneDir });
|
||||
execFileSync("git", ["fetch", "upstream"], { cwd: repoDir });
|
||||
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repoDir });
|
||||
commitFile(repoDir, "feature.txt", "feature\n", "feature");
|
||||
}
|
||||
|
||||
it("compares a fork's checkout against the upstream its default branch tracks", async () => {
|
||||
setupForkOnFeatureBranch();
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/upstream/main",
|
||||
comparisonBaseRef: "refs/remotes/upstream/main",
|
||||
aheadBehind: { ahead: 1, behind: 1 },
|
||||
baseRefBranch: { branch: "main", remote: null, isCurrent: false },
|
||||
});
|
||||
|
||||
const onMain = await createLegacyWorktreeForTest({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "fork-main",
|
||||
source: { kind: "checkout-branch", branchName: "main" },
|
||||
paseoHome,
|
||||
});
|
||||
expect(await getCheckoutStatus(onMain.worktreePath, { paseoHome })).toMatchObject({
|
||||
baseRefExact: "refs/remotes/upstream/main",
|
||||
baseRefBranch: { branch: "main", remote: "upstream", isCurrent: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("updates a fork's checkout from the upstream it compares against", async () => {
|
||||
setupForkOnFeatureBranch();
|
||||
|
||||
await mergeFromBase(repoDir, { baseRef: "main", requireCleanTarget: true });
|
||||
|
||||
expect(existsSync(join(repoDir, "upstream.txt"))).toBe(true);
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
aheadBehind: { ahead: 2, behind: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("compares and updates against the default it selected when main tracks another remote", async () => {
|
||||
setupForkOnFeatureBranch();
|
||||
// Only upstream advertises a default branch, while local main tracks origin.
|
||||
execFileSync("git", ["remote", "set-head", "upstream", "main"], { cwd: repoDir });
|
||||
execFileSync("git", ["branch", "--set-upstream-to=origin/main", "main"], { cwd: repoDir });
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
baseRef: "main",
|
||||
defaultBaseRef: "refs/remotes/upstream/main",
|
||||
comparisonBaseRef: "refs/remotes/upstream/main",
|
||||
aheadBehind: { ahead: 1, behind: 1 },
|
||||
});
|
||||
|
||||
await mergeFromBase(repoDir, { baseRef: "main", requireCleanTarget: true });
|
||||
|
||||
expect(existsSync(join(repoDir, "upstream.txt"))).toBe(true);
|
||||
const diff = await getCheckoutDiff(repoDir, { mode: "base", baseRef: "main" });
|
||||
expect(diff.diff).not.toContain("upstream.txt");
|
||||
expect(diff.diff).toContain("feature.txt");
|
||||
});
|
||||
|
||||
it("compares the default branch and a detached checkout against the default it selected", async () => {
|
||||
setupForkOnFeatureBranch();
|
||||
execFileSync("git", ["remote", "set-head", "upstream", "main"], { cwd: repoDir });
|
||||
execFileSync("git", ["branch", "--set-upstream-to=origin/main", "main"], { cwd: repoDir });
|
||||
execFileSync("git", ["checkout", "main"], { cwd: repoDir });
|
||||
execFileSync("git", ["merge", "--ff-only", "upstream/main"], { cwd: repoDir });
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/upstream/main",
|
||||
comparisonBaseRef: "refs/remotes/upstream/main",
|
||||
});
|
||||
expect((await getCheckoutDiff(repoDir, { mode: "base" })).diff).not.toContain("upstream.txt");
|
||||
const facts = await getCheckoutSnapshotFacts(repoDir, { paseoHome });
|
||||
expect(await getCheckoutShortstat(repoDir, { paseoHome, facts }, { force: true })).toBeNull();
|
||||
|
||||
execFileSync("git", ["checkout", "--detach"], { cwd: repoDir });
|
||||
|
||||
expect(await getCheckoutStatus(repoDir, { paseoHome })).toMatchObject({
|
||||
defaultBaseRef: "refs/remotes/upstream/main",
|
||||
comparisonBaseRef: "refs/remotes/upstream/main",
|
||||
});
|
||||
expect((await getCheckoutDiff(repoDir, { mode: "base" })).diff).not.toContain("upstream.txt");
|
||||
});
|
||||
|
||||
it("keeps origin when a fork's diff names origin/main", async () => {
|
||||
setupForkOnFeatureBranch();
|
||||
execFileSync("git", ["merge", "--no-edit", "upstream/main"], { cwd: repoDir });
|
||||
|
||||
const againstOrigin = await getCheckoutDiff(repoDir, {
|
||||
mode: "base",
|
||||
baseRef: "origin/main",
|
||||
});
|
||||
const againstMain = await getCheckoutDiff(repoDir, { mode: "base", baseRef: "main" });
|
||||
|
||||
expect(againstOrigin.diff).toContain("upstream.txt");
|
||||
expect(againstMain.diff).not.toContain("upstream.txt");
|
||||
expect(againstMain.diff).toContain("feature.txt");
|
||||
});
|
||||
});
|
||||
|
||||
it("merges to stored baseRefName when baseRef is not provided", async () => {
|
||||
// Create a non-default base branch with a unique commit.
|
||||
execFileSync("git", ["checkout", "-b", "develop"], { cwd: repoDir });
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
import {
|
||||
resolveBaseRefBranch,
|
||||
resolveBaseRefInput,
|
||||
resolveCheckoutBase,
|
||||
resolveRepositoryDefaultBranch,
|
||||
resolveTrackedBaseRef,
|
||||
type BaseBranch,
|
||||
type CheckoutBaseBranch,
|
||||
} from "./worktree-base-ref.js";
|
||||
import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
|
||||
import { resolve, dirname, basename } from "path";
|
||||
import {
|
||||
@@ -879,6 +888,9 @@ export interface CheckoutStatusGitNonPaseo {
|
||||
baseRef: string | null;
|
||||
baseRefExact?: string | null;
|
||||
comparisonBaseRef?: string | null;
|
||||
// What a worktree created from this repository starts from when no base is named.
|
||||
defaultBaseRef: string | null;
|
||||
baseRefBranch: CheckoutBaseBranch | null;
|
||||
aheadBehind: AheadBehind | null;
|
||||
// Remote-tracking ref for currentBranch, e.g. "refs/remotes/origin/main". Null when the
|
||||
// branch has no upstream or git could not resolve it. aheadOfOrigin/behindOfOrigin are
|
||||
@@ -909,6 +921,8 @@ export interface CheckoutStatusGitPaseo {
|
||||
baseRef: string;
|
||||
baseRefExact?: string | null;
|
||||
comparisonBaseRef?: string | null;
|
||||
defaultBaseRef: string | null;
|
||||
baseRefBranch: CheckoutBaseBranch | null;
|
||||
aheadBehind: AheadBehind | null;
|
||||
upstreamRef: string | null;
|
||||
aheadOfOrigin: number | null;
|
||||
@@ -974,6 +988,8 @@ export type CheckoutSnapshotFacts =
|
||||
paseoWorktree: PaseoWorktreeForCwd;
|
||||
storedBaseRef: string | null;
|
||||
resolvedBaseRef: string | null;
|
||||
defaultBaseRef: string | null;
|
||||
baseRefBranch: CheckoutBaseBranch | null;
|
||||
mainRepoRoot: string | null;
|
||||
comparisonBaseRef: string | null;
|
||||
branchRemoteName: string | null;
|
||||
@@ -1356,24 +1372,11 @@ export async function setCheckoutBaseBranch(input: {
|
||||
await requireGitRepo(input.cwd);
|
||||
const ownership = await getPaseoWorktreeForCwd(input.cwd, { context: input.context });
|
||||
if (!ownership.isPaseoOwnedWorktree) throw new Error("Workspace is not a Paseo worktree");
|
||||
const requested = input.baseRef.trim();
|
||||
const qualified = requested.startsWith("refs/");
|
||||
const candidates = qualified
|
||||
? [requested]
|
||||
: [`refs/heads/${requested}`, `refs/remotes/${requested}`, `refs/remotes/origin/${requested}`];
|
||||
for (const candidate of candidates) {
|
||||
if (!isQualifiedBranchRef(candidate) || candidate.endsWith("/HEAD")) continue;
|
||||
const valid = await runGitCommand(["check-ref-format", candidate], {
|
||||
cwd: input.cwd,
|
||||
acceptExitCodes: [0, 1],
|
||||
});
|
||||
if (valid.exitCode !== 0 || !(await doesGitRefExist(input.cwd, candidate))) continue;
|
||||
const worktreeRoot = await getWorktreeRoot(input.cwd);
|
||||
if (!worktreeRoot) throw new NotGitRepoError(input.cwd);
|
||||
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate });
|
||||
return candidate;
|
||||
}
|
||||
throw new Error(`Base branch not found: ${requested}`);
|
||||
const candidate = await resolveBaseRefInput(input.cwd, input.baseRef);
|
||||
const worktreeRoot = await getWorktreeRoot(input.cwd);
|
||||
if (!worktreeRoot) throw new NotGitRepoError(input.cwd);
|
||||
await setPaseoWorktreeBaseRef({ worktreeRoot, baseRef: candidate });
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function getResolvedBaseRefForCwd(
|
||||
@@ -1389,7 +1392,10 @@ async function getResolvedBaseRefForCwd(
|
||||
|
||||
interface BaseRefResolution {
|
||||
storedBaseRef: string | null;
|
||||
/** The base's name: the stored base, or the default branch's name when none is stored. */
|
||||
resolvedBaseRef: string | null;
|
||||
/** The exact ref the default branch name stands for, when no base is stored. */
|
||||
defaultBaseRef: string | null;
|
||||
}
|
||||
|
||||
async function resolveBaseRefForCwd(
|
||||
@@ -1400,13 +1406,30 @@ async function resolveBaseRefForCwd(
|
||||
return {
|
||||
storedBaseRef: context.facts.storedBaseRef,
|
||||
resolvedBaseRef: context.facts.resolvedBaseRef,
|
||||
defaultBaseRef: context.facts.defaultBaseRef,
|
||||
};
|
||||
}
|
||||
const storedBaseRef = await getStoredBaseRefForCwd(cwd, context);
|
||||
return {
|
||||
storedBaseRef,
|
||||
resolvedBaseRef: storedBaseRef ?? (await resolveBaseRef(cwd, context)),
|
||||
};
|
||||
if (storedBaseRef) {
|
||||
return { storedBaseRef, resolvedBaseRef: storedBaseRef, defaultBaseRef: null };
|
||||
}
|
||||
const { defaultBaseRef, baseRef } = await resolveCheckoutBase(
|
||||
cwd,
|
||||
{ storedBaseRef: null, currentBranch: null },
|
||||
getRunGitCommand(context),
|
||||
);
|
||||
return { storedBaseRef: null, resolvedBaseRef: baseRef, defaultBaseRef };
|
||||
}
|
||||
|
||||
// With no stored base, the base is the default ref the checkout selected, and callers echo it by
|
||||
// its display name. Resolving that name again can pick another remote, so comparisons and
|
||||
// updates use the selected ref. Merging into the base and opening a PR target the branch name.
|
||||
function exactComparisonBaseRef(resolution: BaseRefResolution, baseRef: string): string {
|
||||
return resolution.storedBaseRef === null &&
|
||||
resolution.defaultBaseRef !== null &&
|
||||
baseRef === resolution.resolvedBaseRef
|
||||
? resolution.defaultBaseRef
|
||||
: baseRef;
|
||||
}
|
||||
|
||||
// The worktree stores the exact ref it was cut from ("refs/remotes/upstream/main") while
|
||||
@@ -1440,6 +1463,13 @@ function resolveOperationBaseRef(input: {
|
||||
return input.storedBaseRef ?? input.requestedBaseRef ?? input.resolvedBaseRef;
|
||||
}
|
||||
|
||||
// Updating from origin's default keeps merging whichever of local and origin's branch is further
|
||||
// ahead. A default on another remote is the branch the comparison measures, so it merges that.
|
||||
function updateBaseRef(resolution: BaseRefResolution, baseRef: string): string {
|
||||
const exact = exactComparisonBaseRef(resolution, baseRef);
|
||||
return exact === `refs/remotes/origin/${branchNameFromRef(exact)}` ? baseRef : exact;
|
||||
}
|
||||
|
||||
// Untracked files count whatever `status.showUntrackedFiles` says: archive warns from this before
|
||||
// it removes a worktree, and a file nobody added yet is still work to lose.
|
||||
async function isWorkingTreeDirty(cwd: string, context?: CheckoutContext): Promise<boolean> {
|
||||
@@ -1676,72 +1706,6 @@ async function abortGitPullConflictState(cwd: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveRepositoryDefaultBranch(
|
||||
repoRoot: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await getRunGitCommand(context)(
|
||||
["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
},
|
||||
);
|
||||
const ref = stdout.trim();
|
||||
if (ref) {
|
||||
// Prefer a local branch name (e.g. "main") over the remote-tracking ref (e.g. "origin/main")
|
||||
// so that status/diff/merge all operate against the same base ref.
|
||||
const remoteShort = ref.replace(/^refs\/remotes\//, "");
|
||||
const localName = remoteShort.startsWith("origin/")
|
||||
? remoteShort.slice("origin/".length)
|
||||
: remoteShort;
|
||||
try {
|
||||
await getRunGitCommand(context)(
|
||||
["show-ref", "--verify", "--quiet", `refs/heads/${localName}`],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
},
|
||||
);
|
||||
return localName;
|
||||
} catch {
|
||||
await getRunGitCommand(context)(["show-ref", "--verify", "--quiet", ref], {
|
||||
cwd: repoRoot,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
return remoteShort;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A stale origin/HEAD must fall through to the available local branches.
|
||||
}
|
||||
|
||||
const { stdout } = await getRunGitCommand(context)(
|
||||
["branch", "--list", "--format=%(refname:short)", "main", "master"],
|
||||
{ cwd: repoRoot, envOverlay: READ_ONLY_GIT_ENV },
|
||||
);
|
||||
const branches = new Set(
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
);
|
||||
|
||||
if (branches.has("main")) {
|
||||
return "main";
|
||||
}
|
||||
if (branches.has("master")) {
|
||||
return "master";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolveBaseRef(repoRoot: string, context?: CheckoutContext): Promise<string | null> {
|
||||
return resolveRepositoryDefaultBranch(repoRoot, context);
|
||||
}
|
||||
|
||||
interface ComparisonBaseRefName {
|
||||
localName: string;
|
||||
originRef: string;
|
||||
@@ -1752,13 +1716,19 @@ function normalizeComparisonBaseRefName(input: string): ComparisonBaseRefName {
|
||||
return { localName, originRef: `origin/${localName}` };
|
||||
}
|
||||
|
||||
function resolveMergeTargetBranch(baseRef: string): string {
|
||||
const remotePrefix = "refs/remotes/";
|
||||
const originPrefix = `${remotePrefix}origin/`;
|
||||
if (baseRef.startsWith(remotePrefix) && !baseRef.startsWith(originPrefix)) {
|
||||
// Tags and commits stand for no branch. Legacy metadata and callers name a branch bare.
|
||||
async function resolveBaseBranch(cwd: string, baseRef: string): Promise<BaseBranch | null> {
|
||||
if (isExactCommitBaseRef(baseRef)) return null;
|
||||
if (isQualifiedBranchRef(baseRef)) return resolveBaseRefBranch(cwd, baseRef);
|
||||
return { remote: null, branch: branchNameFromRef(baseRef) };
|
||||
}
|
||||
|
||||
async function resolveMergeTargetBranch(cwd: string, baseRef: string): Promise<string> {
|
||||
const target = await resolveBaseBranch(cwd, baseRef);
|
||||
if (!target || (target.remote !== null && target.remote !== "origin")) {
|
||||
throw new Error(`No local merge target is recorded for base ref ${baseRef}`);
|
||||
}
|
||||
return branchNameFromRef(baseRef);
|
||||
return target.branch;
|
||||
}
|
||||
|
||||
async function doesGitRefExist(
|
||||
@@ -1779,6 +1749,10 @@ function isQualifiedBranchRef(ref: string): boolean {
|
||||
return ref.startsWith("refs/heads/") || ref.startsWith("refs/remotes/");
|
||||
}
|
||||
|
||||
function isExactCommitBaseRef(ref: string): boolean {
|
||||
return ref.startsWith("refs/tags/") || /^[0-9a-f]{40,64}$/i.test(ref);
|
||||
}
|
||||
|
||||
async function resolveCommitComparisonRef(
|
||||
cwd: string,
|
||||
name: string,
|
||||
@@ -1802,6 +1776,7 @@ async function resolveBestComparisonBaseRef(
|
||||
baseRef: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<string> {
|
||||
if (isExactCommitBaseRef(baseRef)) return resolveCommitComparisonRef(cwd, baseRef, context);
|
||||
// A fully qualified branch ref names the exact commit stream to compare against. Bare names
|
||||
// keep going through the local-vs-origin heuristic below for legacy worktree metadata.
|
||||
if (isQualifiedBranchRef(baseRef)) {
|
||||
@@ -1811,11 +1786,14 @@ async function resolveBestComparisonBaseRef(
|
||||
throw new Error(`Base ref not found: ${baseRef}`);
|
||||
}
|
||||
const normalized = normalizeComparisonBaseRefName(baseRef);
|
||||
const [hasLocal, hasOrigin] = await Promise.all([
|
||||
const [tracked, hasLocal, hasOrigin] = await Promise.all([
|
||||
resolveBareBaseTrackedRef(cwd, baseRef, context),
|
||||
doesGitRefExist(cwd, `refs/heads/${normalized.localName}`, context),
|
||||
doesGitRefExist(cwd, `refs/remotes/origin/${normalized.localName}`, context),
|
||||
]);
|
||||
|
||||
if (tracked) {
|
||||
return tracked;
|
||||
}
|
||||
if (hasOrigin) {
|
||||
return normalized.originRef;
|
||||
}
|
||||
@@ -1823,7 +1801,35 @@ async function resolveBestComparisonBaseRef(
|
||||
return normalized.localName;
|
||||
}
|
||||
|
||||
return resolveCommitComparisonRef(cwd, baseRef, context);
|
||||
return resolveUnmatchedBareBaseRef(cwd, baseRef, context);
|
||||
}
|
||||
|
||||
// A bare name stands for the remote branch its local branch tracks, as it does when a worktree
|
||||
// is created, so a fork's `main` tracking `upstream/main` compares against and updates from
|
||||
// upstream rather than origin. A short `origin/main` names its remote and keeps it.
|
||||
async function resolveBareBaseTrackedRef(
|
||||
cwd: string,
|
||||
baseRef: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<string | null> {
|
||||
const branch = branchNameFromRef(baseRef);
|
||||
if (branch !== baseRef.trim()) return null;
|
||||
const tracked = await resolveTrackedBaseRef(cwd, branch, getRunGitCommand(context));
|
||||
return tracked && (await doesGitRefExist(cwd, tracked, context)) ? tracked : null;
|
||||
}
|
||||
|
||||
// A bare name with no local or origin branch resolves the way a new worktree base does, so a
|
||||
// checkout whose only remote is not origin compares against that remote's branch.
|
||||
async function resolveUnmatchedBareBaseRef(
|
||||
cwd: string,
|
||||
baseRef: string,
|
||||
context?: CheckoutContext,
|
||||
): Promise<string> {
|
||||
return resolveCommitComparisonRef(
|
||||
cwd,
|
||||
await resolveBaseRefInput(cwd, baseRef, getRunGitCommand(context)),
|
||||
context,
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveQualifiedComparisonBaseRef(
|
||||
@@ -1837,6 +1843,7 @@ async function resolveQualifiedComparisonBaseRef(
|
||||
}
|
||||
|
||||
async function resolveMostAheadBaseRef(cwd: string, baseRef: string): Promise<string> {
|
||||
if (isExactCommitBaseRef(baseRef)) return resolveCommitComparisonRef(cwd, baseRef);
|
||||
if (isQualifiedBranchRef(baseRef)) {
|
||||
if (await doesGitRefExist(cwd, baseRef)) {
|
||||
return baseRef;
|
||||
@@ -1844,10 +1851,15 @@ async function resolveMostAheadBaseRef(cwd: string, baseRef: string): Promise<st
|
||||
throw new Error(`Base ref not found: ${baseRef}`);
|
||||
}
|
||||
const normalizedBaseRef = branchNameFromRef(baseRef);
|
||||
const [hasLocal, hasOrigin] = await Promise.all([
|
||||
const [tracked, hasLocal, hasOrigin] = await Promise.all([
|
||||
resolveBareBaseTrackedRef(cwd, baseRef),
|
||||
doesGitRefExist(cwd, `refs/heads/${normalizedBaseRef}`),
|
||||
doesGitRefExist(cwd, `refs/remotes/origin/${normalizedBaseRef}`),
|
||||
]);
|
||||
// Origin keeps the local-vs-origin choice below; another remote is the base the user tracks.
|
||||
if (tracked && tracked !== `refs/remotes/origin/${normalizedBaseRef}`) {
|
||||
return tracked;
|
||||
}
|
||||
|
||||
if (hasLocal && !hasOrigin) {
|
||||
return normalizedBaseRef;
|
||||
@@ -1856,7 +1868,7 @@ async function resolveMostAheadBaseRef(cwd: string, baseRef: string): Promise<st
|
||||
return `origin/${normalizedBaseRef}`;
|
||||
}
|
||||
if (!hasLocal && !hasOrigin) {
|
||||
return resolveCommitComparisonRef(cwd, baseRef);
|
||||
return resolveUnmatchedBareBaseRef(cwd, baseRef);
|
||||
}
|
||||
|
||||
const { stdout } = await runGitCommand(
|
||||
@@ -2323,23 +2335,27 @@ async function collectCheckoutSnapshotFacts(
|
||||
? await readPaseoWorktreeMetadata(inspected.paseoWorktree.worktreeRoot)
|
||||
: null;
|
||||
const storedBaseRef = storedBaseRefFromMetadata(paseoWorktreeMetadata);
|
||||
const resolvedBaseRef = storedBaseRef ?? (await resolveBaseRef(cwd, context));
|
||||
const {
|
||||
defaultBaseRef,
|
||||
baseRef: resolvedBaseRef,
|
||||
baseRefBranch,
|
||||
} = await resolveCheckoutBase(
|
||||
cwd,
|
||||
{ storedBaseRef, currentBranch: inspected.currentBranch },
|
||||
getRunGitCommand(context),
|
||||
);
|
||||
const mainRepoRoot = await getMainRepoRootFromCommonDir(
|
||||
cwd,
|
||||
inspected.gitCommonDir,
|
||||
context,
|
||||
).catch(() => null);
|
||||
let comparisonBaseRef: string | null = null;
|
||||
if (
|
||||
resolvedBaseRef &&
|
||||
inspected.currentBranch &&
|
||||
(isQualifiedBranchRef(resolvedBaseRef) ||
|
||||
branchNameFromRef(resolvedBaseRef) !== inspected.currentBranch)
|
||||
) {
|
||||
comparisonBaseRef = await resolveBestComparisonBaseRef(cwd, resolvedBaseRef, context).catch(
|
||||
() => null,
|
||||
);
|
||||
}
|
||||
const comparisonBaseRef = resolvedBaseRef
|
||||
? await resolveBestComparisonBaseRef(
|
||||
cwd,
|
||||
exactComparisonBaseRef({ storedBaseRef, resolvedBaseRef, defaultBaseRef }, resolvedBaseRef),
|
||||
context,
|
||||
).catch(() => null)
|
||||
: null;
|
||||
|
||||
let branchRemoteName: string | null = null;
|
||||
let branchMergeRef: string | null = null;
|
||||
@@ -2397,6 +2413,8 @@ async function collectCheckoutSnapshotFacts(
|
||||
paseoWorktree: inspected.paseoWorktree,
|
||||
storedBaseRef,
|
||||
resolvedBaseRef,
|
||||
defaultBaseRef,
|
||||
baseRefBranch,
|
||||
mainRepoRoot,
|
||||
comparisonBaseRef,
|
||||
branchRemoteName,
|
||||
@@ -2584,7 +2602,7 @@ export async function getCheckoutIdentity(
|
||||
paseoWorktree.isPaseoOwnedWorktree &&
|
||||
Boolean(
|
||||
storedBaseRefFromMetadata(await readPaseoWorktreeMetadata(worktreeRoot)) ??
|
||||
(await resolveBaseRef(cwd, context)),
|
||||
(await resolveRepositoryDefaultBranch(cwd, getRunGitCommand(context))),
|
||||
);
|
||||
const isLinkedCheckout = mainRepoRoot !== null && !areEquivalentPaths(mainRepoRoot, worktreeRoot);
|
||||
let reportedMainRepoRoot: string | null = null;
|
||||
@@ -2655,6 +2673,8 @@ export async function getCheckoutStatus(
|
||||
baseRef: displayBaseRef ?? baseRef,
|
||||
baseRefExact: baseRef,
|
||||
comparisonBaseRef,
|
||||
defaultBaseRef: facts.defaultBaseRef,
|
||||
baseRefBranch: facts.baseRefBranch,
|
||||
aheadBehind,
|
||||
...upstream,
|
||||
...remotes,
|
||||
@@ -2673,6 +2693,8 @@ export async function getCheckoutStatus(
|
||||
baseRef: displayBaseRef,
|
||||
baseRefExact: baseRef,
|
||||
comparisonBaseRef,
|
||||
defaultBaseRef: facts.defaultBaseRef,
|
||||
baseRefBranch: facts.baseRefBranch,
|
||||
aheadBehind,
|
||||
...upstream,
|
||||
...remotes,
|
||||
@@ -2871,7 +2893,7 @@ export async function listCheckoutCommits({
|
||||
// Saved worktree metadata can outlive a renamed or deleted base branch.
|
||||
comparisonBaseRef = await tryResolveCheckoutCommitsBaseRef(
|
||||
cwd,
|
||||
await resolveBaseRef(cwd),
|
||||
await resolveRepositoryDefaultBranch(cwd, getRunGitCommand(context)),
|
||||
currentBranch,
|
||||
);
|
||||
}
|
||||
@@ -3208,6 +3230,15 @@ async function resolveShortstatComparisonRef(input: {
|
||||
}
|
||||
}
|
||||
|
||||
// On the base branch, count against the remote branch Changes compares with.
|
||||
const selected = facts?.isGit ? facts.comparisonBaseRef : null;
|
||||
if (
|
||||
selected &&
|
||||
branchNameFromRef(selected) === currentBranch &&
|
||||
(selected.startsWith("refs/remotes/") || selected.startsWith("origin/"))
|
||||
) {
|
||||
return selected;
|
||||
}
|
||||
const hasOrigin = await doesGitRefExist(cwd, `refs/remotes/origin/${currentBranch}`, context);
|
||||
return hasOrigin ? `origin/${currentBranch}` : null;
|
||||
}
|
||||
@@ -3348,8 +3379,10 @@ export async function getCheckoutRefDerivedState(
|
||||
if (upstreamMoved && currentBranch && upstreamRef) {
|
||||
const normalizedUpstream = normalizeRemoteTrackingRef(upstreamRef);
|
||||
const normalizedComparison = comparisonRef ? normalizeRemoteTrackingRef(comparisonRef) : null;
|
||||
// The base count is null on the base branch itself, so it can only stand in for the
|
||||
// upstream count when the refresh produced one.
|
||||
const upstreamAheadBehind =
|
||||
baseMoved && normalizedComparison === normalizedUpstream
|
||||
baseMoved && aheadBehind && normalizedComparison === normalizedUpstream
|
||||
? aheadBehind
|
||||
: await getAheadBehindForComparisonRef(cwd, upstreamRef, currentBranch, context);
|
||||
upstreamStatus = upstreamAheadBehind
|
||||
@@ -3766,16 +3799,16 @@ export async function resolveCheckoutDiffBase(
|
||||
context?: CheckoutContext,
|
||||
): Promise<string | null> {
|
||||
if (compare.mode === "uncommitted") return "HEAD";
|
||||
const { storedBaseRef, resolvedBaseRef } = await resolveBaseRefForCwd(cwd, context);
|
||||
const resolution = await resolveBaseRefForCwd(cwd, context);
|
||||
const baseRef = resolveOperationBaseRef({
|
||||
storedBaseRef,
|
||||
resolvedBaseRef,
|
||||
storedBaseRef: resolution.storedBaseRef,
|
||||
resolvedBaseRef: resolution.resolvedBaseRef,
|
||||
requestedBaseRef: compare.baseRef,
|
||||
});
|
||||
if (!baseRef) {
|
||||
return null;
|
||||
}
|
||||
return resolveBestComparisonBaseRef(cwd, baseRef);
|
||||
return resolveBestComparisonBaseRef(cwd, exactComparisonBaseRef(resolution, baseRef));
|
||||
}
|
||||
|
||||
// Git's working-tree diff ignores files absent from the index, even when they
|
||||
@@ -4158,7 +4191,7 @@ export async function mergeToBase(
|
||||
if (!currentBranch) {
|
||||
throw new Error("Unable to determine current branch for merge");
|
||||
}
|
||||
const normalizedBaseRef = resolveMergeTargetBranch(baseRef);
|
||||
const normalizedBaseRef = await resolveMergeTargetBranch(cwd, baseRef);
|
||||
const currentWorktreeRoot = (await getWorktreeRoot(cwd, context)) ?? cwd;
|
||||
if (normalizedBaseRef === currentBranch) {
|
||||
throw new Error("Cannot merge a branch into itself");
|
||||
@@ -4222,10 +4255,10 @@ export async function mergeFromBase(
|
||||
throw new Error("Unable to determine current branch for merge");
|
||||
}
|
||||
|
||||
const { storedBaseRef, resolvedBaseRef } = await resolveBaseRefForCwd(cwd, context);
|
||||
const resolution = await resolveBaseRefForCwd(cwd, context);
|
||||
const baseRef = resolveOperationBaseRef({
|
||||
storedBaseRef,
|
||||
resolvedBaseRef,
|
||||
storedBaseRef: resolution.storedBaseRef,
|
||||
resolvedBaseRef: resolution.resolvedBaseRef,
|
||||
requestedBaseRef: options.baseRef,
|
||||
});
|
||||
if (!baseRef) {
|
||||
@@ -4243,7 +4276,7 @@ export async function mergeFromBase(
|
||||
}
|
||||
}
|
||||
|
||||
const bestBaseRef = await resolveMostAheadBaseRef(cwd, baseRef);
|
||||
const bestBaseRef = await resolveMostAheadBaseRef(cwd, updateBaseRef(resolution, baseRef));
|
||||
if (bestBaseRef === currentBranch) {
|
||||
return;
|
||||
}
|
||||
@@ -4736,7 +4769,10 @@ export async function createPullRequest(
|
||||
if (!base) {
|
||||
throw new Error("Unable to determine base branch for PR");
|
||||
}
|
||||
const normalizedBase = branchNameFromRef(base);
|
||||
const target = await resolveBaseBranch(cwd, base);
|
||||
if (!target) {
|
||||
throw new Error(`No target branch is recorded for base ref ${base}`);
|
||||
}
|
||||
|
||||
// The push deliberately happens before the adapter resolves the target
|
||||
// repository: slug resolution is adapter-internal (e.g. `gh repo view`, which
|
||||
@@ -4751,7 +4787,7 @@ export async function createPullRequest(
|
||||
title: options.title,
|
||||
body: options.body,
|
||||
head,
|
||||
base: normalizedBase,
|
||||
base: target.branch,
|
||||
});
|
||||
forgeService.invalidate({ cwd });
|
||||
return result;
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createServer, type Socket } from "node:net";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
refreshRemoteBaseRef,
|
||||
resolveBaseRefInput,
|
||||
resolveRepositoryDefaultBaseRef,
|
||||
} from "./worktree-base-ref.js";
|
||||
|
||||
describe("worktree base refs", () => {
|
||||
let dir: string;
|
||||
let repo: string;
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "base-ref-"));
|
||||
repo = join(dir, "repo");
|
||||
mkdirSync(repo);
|
||||
git(repo, "init", "-b", "main");
|
||||
git(repo, "config", "user.name", "Test");
|
||||
git(repo, "config", "user.email", "test@example.com");
|
||||
writeFileSync(join(repo, "file"), "initial");
|
||||
git(repo, "add", "file");
|
||||
git(repo, "-c", "commit.gpgsign=false", "commit", "-m", "initial");
|
||||
});
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
it("uses local refs without a remote and rejects invalid inputs", async () => {
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/heads/main");
|
||||
expect(await resolveBaseRefInput(repo, "main")).toBe("refs/heads/main");
|
||||
git(repo, "branch", "wip");
|
||||
expect(await resolveBaseRefInput(repo, "wip")).toBe("refs/heads/wip");
|
||||
for (const input of [
|
||||
"HEAD",
|
||||
"origin/HEAD",
|
||||
"main..wip",
|
||||
"main@{1}",
|
||||
"missing",
|
||||
"refs/heads/missing",
|
||||
]) {
|
||||
await expect(resolveBaseRefInput(repo, input)).rejects.toThrow("Base branch not found");
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts tags and commit IDs after branch resolution", async () => {
|
||||
git(repo, "tag", "-a", "v1", "-m", "version one");
|
||||
const commit = git(repo, "rev-parse", "HEAD");
|
||||
expect(await resolveBaseRefInput(repo, "v1")).toBe("refs/tags/v1");
|
||||
expect(await resolveBaseRefInput(repo, "refs/tags/v1")).toBe("refs/tags/v1");
|
||||
expect(await resolveBaseRefInput(repo, commit.slice(0, 12))).toBe(commit);
|
||||
git(repo, "branch", "v1");
|
||||
expect(await resolveBaseRefInput(repo, "v1")).toBe("refs/heads/v1");
|
||||
});
|
||||
|
||||
it("requires a base instead of choosing one", async () => {
|
||||
for (const input of ["", " "]) {
|
||||
await expect(resolveBaseRefInput(repo, input)).rejects.toThrow("Base branch is required");
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects ref expressions instead of freezing them to a commit", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
|
||||
for (const input of ["@", "origin", "heads/main", "remotes/origin/main", "main~0", "main^"]) {
|
||||
await expect(resolveBaseRefInput(repo, input)).rejects.toThrow("Base branch not found");
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves a bare branch name remote-first even when the local branch is ahead", async () => {
|
||||
git(repo, "branch", "feature");
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
git(repo, "checkout", "feature");
|
||||
writeFileSync(join(repo, "local"), "unpushed");
|
||||
git(repo, "add", "local");
|
||||
git(repo, "-c", "commit.gpgsign=false", "commit", "-m", "unpushed");
|
||||
expect(await resolveBaseRefInput(repo, "feature")).toBe("refs/remotes/origin/feature");
|
||||
expect(await resolveBaseRefInput(repo, "refs/heads/feature")).toBe("refs/heads/feature");
|
||||
});
|
||||
|
||||
it("uses configured tracking before origin, and preserves explicit local refs", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "remote", "add", "upstream", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
git(repo, "fetch", "upstream");
|
||||
git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
|
||||
git(repo, "branch", "--set-upstream-to=upstream/main", "main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/upstream/main");
|
||||
expect(await resolveBaseRefInput(repo, "main")).toBe("refs/remotes/upstream/main");
|
||||
expect(await resolveBaseRefInput(repo, "origin/main")).toBe("refs/remotes/origin/main");
|
||||
expect(await resolveBaseRefInput(repo, "refs/heads/main")).toBe("refs/heads/main");
|
||||
git(repo, "checkout", "-b", "feature/unrelated");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/upstream/main");
|
||||
git(repo, "checkout", "--detach");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/upstream/main");
|
||||
});
|
||||
|
||||
it("keeps a local branch whose upstream is a differently named remote branch", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
git(repo, "checkout", "-b", "feature", "origin/main");
|
||||
writeFileSync(join(repo, "feature"), "feature work");
|
||||
git(repo, "add", "feature");
|
||||
git(repo, "-c", "commit.gpgsign=false", "commit", "-m", "feature");
|
||||
git(repo, "checkout", "-b", "dev", "origin/main");
|
||||
git(repo, "branch", "-D", "main");
|
||||
expect(await resolveBaseRefInput(repo, "feature")).toBe("refs/heads/feature");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/origin/main");
|
||||
});
|
||||
|
||||
it("fetches the longest matching remote and leaves local and offline refs alone", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "team/company", remote);
|
||||
git(repo, "fetch", "team/company");
|
||||
const writer = join(dir, "writer");
|
||||
git(dir, "clone", remote, writer);
|
||||
git(writer, "config", "user.name", "Test");
|
||||
git(writer, "config", "user.email", "test@example.com");
|
||||
writeFileSync(join(writer, "new"), "new");
|
||||
git(writer, "add", "new");
|
||||
git(writer, "-c", "commit.gpgsign=false", "commit", "-m", "new");
|
||||
git(writer, "push", "origin", "main");
|
||||
const old = git(repo, "rev-parse", "refs/remotes/team/company/main");
|
||||
await refreshRemoteBaseRef(repo, "refs/heads/main");
|
||||
expect(git(repo, "rev-parse", "refs/remotes/team/company/main")).toBe(old);
|
||||
expect(await resolveBaseRefInput(repo, "team/company/main")).toBe(
|
||||
"refs/remotes/team/company/main",
|
||||
);
|
||||
await refreshRemoteBaseRef(repo, "refs/remotes/team/company/main");
|
||||
expect(git(repo, "rev-parse", "refs/remotes/team/company/main")).toBe(
|
||||
git(writer, "rev-parse", "HEAD"),
|
||||
);
|
||||
git(repo, "remote", "set-url", "team/company", join(dir, "missing"));
|
||||
await refreshRemoteBaseRef(repo, "refs/remotes/team/company/main");
|
||||
expect(git(repo, "rev-parse", "refs/remotes/team/company/main")).toBe(
|
||||
git(writer, "rev-parse", "HEAD"),
|
||||
);
|
||||
});
|
||||
it("uses the upstream of a sole custom branch without a remote HEAD", async () => {
|
||||
git(repo, "branch", "-m", "dev");
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
try {
|
||||
git(repo, "symbolic-ref", "--delete", "refs/remotes/origin/HEAD");
|
||||
} catch {
|
||||
/* No remote HEAD was created. */
|
||||
}
|
||||
git(repo, "branch", "--set-upstream-to=origin/dev", "dev");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/origin/dev");
|
||||
});
|
||||
|
||||
it("falls back through custom branches in detached and unborn repositories", async () => {
|
||||
git(repo, "branch", "-m", "release");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/heads/release");
|
||||
git(repo, "branch", "other");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/heads/release");
|
||||
git(repo, "checkout", "--detach");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBeNull();
|
||||
const empty = join(dir, "empty");
|
||||
mkdirSync(empty);
|
||||
git(empty, "init", "-b", "main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(empty)).toBeNull();
|
||||
await expect(resolveBaseRefInput(empty, "main")).rejects.toThrow("Base branch not found");
|
||||
});
|
||||
|
||||
it("chooses valid remote HEADs deterministically and ignores stale ones", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
for (const name of ["alpha", "upstream"]) {
|
||||
git(repo, "remote", "add", name, remote);
|
||||
git(repo, "fetch", name);
|
||||
git(repo, "symbolic-ref", `refs/remotes/${name}/HEAD`, `refs/remotes/${name}/main`);
|
||||
}
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/upstream/main");
|
||||
git(repo, "branch", "--set-upstream-to=alpha/main", "main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/alpha/main");
|
||||
git(repo, "symbolic-ref", "refs/remotes/alpha/HEAD", "refs/remotes/alpha/missing");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/upstream/main");
|
||||
git(repo, "symbolic-ref", "refs/remotes/upstream/HEAD", "refs/remotes/upstream/missing");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/alpha/main");
|
||||
});
|
||||
|
||||
it("uses a cached origin ref even after its remote configuration is absent", async () => {
|
||||
git(repo, "update-ref", "refs/remotes/origin/main", "HEAD");
|
||||
expect(await resolveBaseRefInput(repo, "main")).toBe("refs/remotes/origin/main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/origin/main");
|
||||
git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/origin/main");
|
||||
});
|
||||
|
||||
it("uses conventional remote branches when no remote HEAD exists", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "company", remote);
|
||||
git(repo, "fetch", "company");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/company/main");
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/origin/main");
|
||||
git(repo, "branch", "--set-upstream-to=company/main", "main");
|
||||
expect(await resolveRepositoryDefaultBaseRef(repo)).toBe("refs/remotes/company/main");
|
||||
});
|
||||
|
||||
it("falls back to a unique remote, or the local branch when remotes are ambiguous", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "branch", "release/v2");
|
||||
git(repo, "push", remote, "release/v2");
|
||||
git(repo, "remote", "add", "one", remote);
|
||||
git(repo, "fetch", "one");
|
||||
expect(await resolveBaseRefInput(repo, "release/v2")).toBe("refs/remotes/one/release/v2");
|
||||
git(repo, "remote", "add", "two", remote);
|
||||
git(repo, "fetch", "two");
|
||||
expect(await resolveBaseRefInput(repo, "release/v2")).toBe("refs/heads/release/v2");
|
||||
git(repo, "branch", "-D", "release/v2");
|
||||
await expect(resolveBaseRefInput(repo, "release/v2")).rejects.toThrow("Base branch not found");
|
||||
});
|
||||
it("falls back to the cached ref when a remote accepts a connection but never answers", async () => {
|
||||
const remote = join(dir, "remote.git");
|
||||
git(dir, "clone", "--bare", repo, remote);
|
||||
git(repo, "remote", "add", "origin", remote);
|
||||
git(repo, "fetch", "origin");
|
||||
const cached = git(repo, "rev-parse", "refs/remotes/origin/main");
|
||||
const sockets: Socket[] = [];
|
||||
const server = createServer((socket) => {
|
||||
sockets.push(socket);
|
||||
socket.resume();
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing test port");
|
||||
git(repo, "remote", "set-url", "origin", `ssh://127.0.0.1:${address.port}/repo`);
|
||||
try {
|
||||
const started = Date.now();
|
||||
await refreshRemoteBaseRef(repo, "refs/remotes/origin/main");
|
||||
expect(sockets).toHaveLength(1);
|
||||
expect(Date.now() - started).toBeGreaterThanOrEqual(14000);
|
||||
expect(Date.now() - started).toBeLessThan(22000);
|
||||
expect(git(repo, "rev-parse", "refs/remotes/origin/main")).toBe(cached);
|
||||
} finally {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}, 25000);
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
import { runGitCommand, type RunGitCommand } from "./run-git-command.js";
|
||||
import { buildBackgroundFetchEnvOverlay } from "../server/workspace-git-fetch.js";
|
||||
import { branchNameFromRef } from "./worktree-metadata.js";
|
||||
|
||||
const conventional = ["main", "master", "trunk", "develop"];
|
||||
interface Snapshot {
|
||||
refs: Set<string>;
|
||||
upstreams: Map<string, string>;
|
||||
heads: Map<string, string>;
|
||||
remotes: string[];
|
||||
}
|
||||
|
||||
// Longest names first, so `team/company` claims `refs/remotes/team/company/main` before `team`.
|
||||
async function readRemotes(cwd: string, git: RunGitCommand): Promise<string[]> {
|
||||
const { stdout } = await git(["remote"], { cwd });
|
||||
return stdout
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.length - a.length || a.localeCompare(b));
|
||||
}
|
||||
|
||||
async function readRefs(cwd: string, git: RunGitCommand): Promise<Snapshot> {
|
||||
const [refsResult, remotes] = await Promise.all([
|
||||
git(
|
||||
[
|
||||
"for-each-ref",
|
||||
"--format=%(refname)%00%(symref)%00%(upstream)%00%(upstream:remoteref)",
|
||||
"refs/heads/",
|
||||
"refs/remotes/",
|
||||
],
|
||||
{ cwd },
|
||||
),
|
||||
readRemotes(cwd, git),
|
||||
]);
|
||||
const refs = new Set<string>();
|
||||
const upstreams = new Map<string, string>();
|
||||
const symrefs = new Map<string, string>();
|
||||
for (const line of refsResult.stdout.split("\n")) {
|
||||
if (!line) continue;
|
||||
const [ref, symref, upstream, upstreamSource] = line.split("\0");
|
||||
refs.add(ref);
|
||||
if (symref) symrefs.set(ref, symref);
|
||||
// A branch stands for its upstream only when the remote branch carries the same name. Git
|
||||
// also tracks the start point (`git switch -c feature origin/main`), which says nothing about
|
||||
// which branch the user means.
|
||||
if (upstream && upstreamSource === ref) upstreams.set(ref, upstream);
|
||||
}
|
||||
const heads = new Map<string, string>();
|
||||
for (const [ref, target] of symrefs) {
|
||||
if (!ref.startsWith("refs/remotes/") || !ref.endsWith("/HEAD")) continue;
|
||||
if (target.startsWith("refs/remotes/") && refs.has(target)) {
|
||||
heads.set(ref.slice("refs/remotes/".length, -"/HEAD".length), target);
|
||||
}
|
||||
}
|
||||
return { refs, upstreams, heads, remotes };
|
||||
}
|
||||
function tracked(s: Snapshot, branch: string): string | undefined {
|
||||
const upstream = s.upstreams.get(`refs/heads/${branch}`);
|
||||
return upstream?.startsWith("refs/remotes/") && s.refs.has(upstream) ? upstream : undefined;
|
||||
}
|
||||
function remoteForBranch(s: Snapshot, branch: string): string | undefined {
|
||||
const cached = (remote: string) => {
|
||||
const ref = `refs/remotes/${remote}/${branch}`;
|
||||
return s.refs.has(ref) ? ref : undefined;
|
||||
};
|
||||
const origin = cached("origin");
|
||||
if (origin) return origin;
|
||||
const matches = s.remotes.map(cached).filter((ref): ref is string => !!ref);
|
||||
return matches.length === 1 ? matches[0] : undefined;
|
||||
}
|
||||
async function currentBranch(cwd: string, git: RunGitCommand): Promise<string | null> {
|
||||
const result = await git(["symbolic-ref", "--quiet", "--short", "HEAD"], {
|
||||
cwd,
|
||||
acceptExitCodes: [0, 1, 128],
|
||||
});
|
||||
return result.exitCode === 0 ? result.stdout.trim() : null;
|
||||
}
|
||||
async function defaultRef(cwd: string, s: Snapshot, git: RunGitCommand): Promise<string | null> {
|
||||
const origin = s.heads.get("origin");
|
||||
if (origin) return tracked(s, origin.slice("refs/remotes/origin/".length)) ?? origin;
|
||||
if (s.heads.size === 1) return [...s.heads.values()][0];
|
||||
if (s.heads.size > 1) {
|
||||
const current = await currentBranch(cwd, git);
|
||||
const preferred = new Set(
|
||||
[...conventional, ...(current ? [current] : [])]
|
||||
.map((branch) => tracked(s, branch))
|
||||
.map(
|
||||
(ref) =>
|
||||
[...s.heads.entries()].find(([remote]) =>
|
||||
ref?.startsWith(`refs/remotes/${remote}/`),
|
||||
)?.[1],
|
||||
)
|
||||
.filter((ref): ref is string => !!ref),
|
||||
);
|
||||
if (preferred.size === 1) return [...preferred][0];
|
||||
return (
|
||||
s.heads.get("upstream") ?? [...s.heads.entries()].sort(([a], [b]) => a.localeCompare(b))[0][1]
|
||||
);
|
||||
}
|
||||
for (const branch of conventional) {
|
||||
const ref = tracked(s, branch) ?? remoteForBranch(s, branch);
|
||||
if (ref) return ref;
|
||||
}
|
||||
const locals = [...s.refs].filter((ref) => ref.startsWith("refs/heads/"));
|
||||
const conventionalLocal = conventional.find((branch) => s.refs.has(`refs/heads/${branch}`));
|
||||
let selected: string | null = null;
|
||||
if (conventionalLocal) selected = `refs/heads/${conventionalLocal}`;
|
||||
else if (locals.length === 1) selected = locals[0];
|
||||
else {
|
||||
const current = await currentBranch(cwd, git);
|
||||
if (current && s.refs.has(`refs/heads/${current}`)) selected = `refs/heads/${current}`;
|
||||
}
|
||||
return selected ? (tracked(s, selected.slice("refs/heads/".length)) ?? selected) : null;
|
||||
}
|
||||
/** `git` runs the reads, so a caller in a background lane keeps them there. */
|
||||
export async function resolveRepositoryDefaultBaseRef(
|
||||
cwd: string,
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<string | null> {
|
||||
return defaultRef(cwd, await readRefs(cwd, git), git);
|
||||
}
|
||||
function isInvalidBaseInput(input: string): boolean {
|
||||
return (
|
||||
input === "HEAD" || input.endsWith("/HEAD") || input.includes("..") || input.includes("@{")
|
||||
);
|
||||
}
|
||||
|
||||
function baseNotFound(requested: string): Error {
|
||||
return new Error(`Base branch not found: ${requested}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a requested base to the exact ref a worktree is cut from and compared against. A bare
|
||||
* branch name resolves remote-first; `refs/heads/<name>` selects the local branch. Tags and commit
|
||||
* IDs are accepted after branch lookup misses. Other ref expressions (`@`, `origin`, `main~1`) are
|
||||
* refused, so a base is never frozen to whatever commit an expression happened to name.
|
||||
*/
|
||||
export async function resolveBaseRefInput(
|
||||
cwd: string,
|
||||
input: string,
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<string> {
|
||||
const requested = input.trim();
|
||||
if (!requested) throw new Error("Base branch is required");
|
||||
if (isInvalidBaseInput(requested)) throw baseNotFound(requested);
|
||||
const s = await readRefs(cwd, git);
|
||||
if (requested.startsWith("refs/heads/") || requested.startsWith("refs/remotes/")) {
|
||||
if (s.refs.has(requested)) return requested;
|
||||
throw baseNotFound(requested);
|
||||
}
|
||||
if (requested.startsWith("refs/tags/")) {
|
||||
if (await isCommit(cwd, requested, git)) return requested;
|
||||
throw baseNotFound(requested);
|
||||
}
|
||||
if (requested.startsWith("refs/")) throw baseNotFound(requested);
|
||||
|
||||
for (const remote of s.remotes) {
|
||||
const ref = `refs/remotes/${requested}`;
|
||||
if (requested.startsWith(`${remote}/`) && s.refs.has(ref)) return ref;
|
||||
}
|
||||
const ref =
|
||||
tracked(s, requested) ??
|
||||
remoteForBranch(s, requested) ??
|
||||
(s.refs.has(`refs/heads/${requested}`) ? `refs/heads/${requested}` : undefined);
|
||||
if (ref) return ref;
|
||||
const tag = `refs/tags/${requested}`;
|
||||
if (await isCommit(cwd, tag, git)) return tag;
|
||||
if (/^[0-9a-f]{4,64}$/i.test(requested)) {
|
||||
const commit = await readCommit(cwd, requested, git);
|
||||
if (commit) return commit;
|
||||
}
|
||||
throw baseNotFound(requested);
|
||||
}
|
||||
|
||||
async function readCommit(cwd: string, ref: string, git: RunGitCommand): Promise<string | null> {
|
||||
const result = await git(
|
||||
["rev-parse", "--verify", "--quiet", "--end-of-options", `${ref}^{commit}`],
|
||||
{ cwd, acceptExitCodes: [0, 1, 128] },
|
||||
);
|
||||
return result.exitCode === 0 ? result.stdout.trim() : null;
|
||||
}
|
||||
|
||||
async function isCommit(cwd: string, ref: string, git: RunGitCommand): Promise<boolean> {
|
||||
return (await readCommit(cwd, ref, git)) !== null;
|
||||
}
|
||||
|
||||
export interface RemoteBranch {
|
||||
remote: string;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
/** The branch a base ref stands for. A local branch has no remote; tags and commits have no branch. */
|
||||
export interface BaseBranch {
|
||||
remote: string | null;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
// `remotes` is sorted longest first, so `team/company` claims its refs before `team`.
|
||||
function branchOfQualifiedRef(remotes: string[], baseRef: string): BaseBranch | null {
|
||||
if (baseRef.startsWith("refs/heads/")) {
|
||||
return { remote: null, branch: baseRef.slice("refs/heads/".length) };
|
||||
}
|
||||
if (!baseRef.startsWith("refs/remotes/")) return null;
|
||||
const remote = remotes.find((name) => baseRef.startsWith(`refs/remotes/${name}/`));
|
||||
return remote ? { remote, branch: baseRef.slice(`refs/remotes/${remote}/`.length) } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the branch a base ref stands for from its conventional spelling: `refs/heads/<branch>`, or
|
||||
* `refs/remotes/<remote>/<branch>` for the longest configured remote name. Returns null for tags,
|
||||
* commits, and tracking refs of remotes that are no longer configured.
|
||||
*/
|
||||
export async function resolveBaseRefBranch(
|
||||
cwd: string,
|
||||
baseRef: string,
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<BaseBranch | null> {
|
||||
if (!baseRef.startsWith("refs/remotes/")) return branchOfQualifiedRef([], baseRef);
|
||||
return branchOfQualifiedRef(await readRemotes(cwd, git), baseRef);
|
||||
}
|
||||
|
||||
// A cached tracking ref whose remote is no longer configured still names its branch after the
|
||||
// remote's segment.
|
||||
function defaultBranchName(s: Snapshot, defaultBaseRef: string): string {
|
||||
return (
|
||||
branchOfQualifiedRef(s.remotes, defaultBaseRef)?.branch ?? branchNameFromRef(defaultBaseRef)
|
||||
);
|
||||
}
|
||||
|
||||
/** The name of the branch the repository's default base ref stands for. */
|
||||
export async function resolveRepositoryDefaultBranch(
|
||||
cwd: string,
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<string | null> {
|
||||
const s = await readRefs(cwd, git);
|
||||
const ref = await defaultRef(cwd, s, git);
|
||||
return ref ? defaultBranchName(s, ref) : null;
|
||||
}
|
||||
|
||||
/** The branch a checkout's base stands for, and whether the checkout is on it. */
|
||||
export interface CheckoutBaseBranch extends BaseBranch {
|
||||
/**
|
||||
* The current branch is the base: the local branch the base names, or a branch whose upstream is
|
||||
* the remote base. A branch that only shares the remote base's name is not on it.
|
||||
*/
|
||||
isCurrent: boolean;
|
||||
}
|
||||
|
||||
export interface CheckoutBase {
|
||||
/** What a worktree created from this repository starts from when no base is named. */
|
||||
defaultBaseRef: string | null;
|
||||
/**
|
||||
* What the checkout compares against: its stored base, else the default branch by name, so a
|
||||
* checkout on that branch is on its base whichever remote it tracks.
|
||||
*/
|
||||
baseRef: string | null;
|
||||
/** Null for a tag or commit base, and for a tracking ref of a remote that is gone. */
|
||||
baseRefBranch: CheckoutBaseBranch | null;
|
||||
}
|
||||
|
||||
function isCommitBaseRef(ref: string): boolean {
|
||||
return ref.startsWith("refs/tags/") || /^[0-9a-f]{40,64}$/i.test(ref);
|
||||
}
|
||||
|
||||
function checkoutBaseBranch(
|
||||
s: Snapshot,
|
||||
baseRef: string,
|
||||
checkedOut: string | null,
|
||||
): CheckoutBaseBranch | null {
|
||||
if (isCommitBaseRef(baseRef)) return null;
|
||||
// Legacy metadata and the default name a bare branch, which stands for the local branch.
|
||||
const branch = baseRef.startsWith("refs/")
|
||||
? branchOfQualifiedRef(s.remotes, baseRef)
|
||||
: { remote: null, branch: baseRef };
|
||||
if (!branch) return null;
|
||||
const isCurrent =
|
||||
checkedOut !== null &&
|
||||
(branch.remote === null ? branch.branch === checkedOut : tracked(s, checkedOut) === baseRef);
|
||||
return { ...branch, isCurrent };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the base a checkout reports in one read of the refs: the repository default and the
|
||||
* branch the checkout's base stands for. `git` runs the reads, so a background refresh keeps them in
|
||||
* its lane.
|
||||
*/
|
||||
export async function resolveCheckoutBase(
|
||||
cwd: string,
|
||||
checkout: { storedBaseRef: string | null; currentBranch: string | null },
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<CheckoutBase> {
|
||||
const s = await readRefs(cwd, git);
|
||||
const defaultBaseRef = await defaultRef(cwd, s, git);
|
||||
const baseRef =
|
||||
checkout.storedBaseRef ?? (defaultBaseRef ? defaultBranchName(s, defaultBaseRef) : null);
|
||||
return {
|
||||
defaultBaseRef,
|
||||
baseRef,
|
||||
baseRefBranch: baseRef ? checkoutBaseBranch(s, baseRef, checkout.currentBranch) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote branch a local branch stands for: its upstream when the upstream carries the same
|
||||
* branch name. Reads only that branch's config, not its ahead/behind counts; the caller confirms
|
||||
* the tracking ref exists.
|
||||
*/
|
||||
export async function resolveTrackedBaseRef(
|
||||
cwd: string,
|
||||
branch: string,
|
||||
git: RunGitCommand = runGitCommand,
|
||||
): Promise<string | null> {
|
||||
const local = `refs/heads/${branch}`;
|
||||
const { stdout } = await git(
|
||||
["for-each-ref", "--format=%(refname)%00%(upstream)%00%(upstream:remoteref)", local],
|
||||
{ cwd },
|
||||
);
|
||||
for (const line of stdout.split("\n")) {
|
||||
const [ref, upstream, upstreamSource] = line.split("\0");
|
||||
if (ref === local && upstreamSource === local && upstream?.startsWith("refs/remotes/")) {
|
||||
return upstream;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches a remote branch into `refs/remotes/<remote>/<branch>` and returns that ref. Returns null
|
||||
* when neither the fetch nor the cache provides it.
|
||||
*/
|
||||
export async function resolveRemoteBranchBaseRef(
|
||||
cwd: string,
|
||||
{ remote, branch }: RemoteBranch,
|
||||
): Promise<string | null> {
|
||||
if (isInvalidBaseInput(branch)) return null;
|
||||
const ref = `refs/remotes/${remote}/${branch}`;
|
||||
await fetchRemoteRef(cwd, { remote, branch }, ref);
|
||||
const result = await runGitCommand(["show-ref", "--verify", "--quiet", ref], {
|
||||
cwd,
|
||||
acceptExitCodes: [0, 1, 128],
|
||||
});
|
||||
return result.exitCode === 0 ? ref : null;
|
||||
}
|
||||
|
||||
async function fetchRemoteRef(
|
||||
cwd: string,
|
||||
{ remote, branch }: RemoteBranch,
|
||||
destination: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await runGitCommand(["fetch", remote, `+refs/heads/${branch}:${destination}`], {
|
||||
cwd,
|
||||
envOverlay: await buildBackgroundFetchEnvOverlay(),
|
||||
timeout: 15_000,
|
||||
});
|
||||
} catch {
|
||||
// Offline and authentication failures leave the cached ref usable.
|
||||
}
|
||||
}
|
||||
|
||||
/** Fetches a remote tracking base ref from its remote. Local branches, tags, and commits are left alone. */
|
||||
export async function refreshRemoteBaseRef(cwd: string, baseRef: string): Promise<void> {
|
||||
const target = await resolveBaseRefBranch(cwd, baseRef);
|
||||
if (!target?.remote) return;
|
||||
await fetchRemoteRef(cwd, { remote: target.remote, branch: target.branch }, baseRef);
|
||||
}
|
||||
@@ -120,6 +120,64 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("branches from the fresh remote tip for a bare base name", async () => {
|
||||
const remote = join(tempDir, "remote.git");
|
||||
execFileSync("git", ["clone", "--bare", repoDir, remote]);
|
||||
execFileSync("git", ["remote", "add", "origin", remote], { cwd: repoDir });
|
||||
execFileSync("git", ["fetch", "origin"], { cwd: repoDir });
|
||||
const writer = join(tempDir, "writer");
|
||||
execFileSync("git", ["clone", remote, writer]);
|
||||
execFileSync("git", ["config", "user.email", "test@test.com"], { cwd: writer });
|
||||
execFileSync("git", ["config", "user.name", "Test"], { cwd: writer });
|
||||
writeFileSync(join(writer, "new.txt"), "fresh\n");
|
||||
execFileSync("git", ["add", "new.txt"], { cwd: writer });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "remote tip"], {
|
||||
cwd: writer,
|
||||
});
|
||||
execFileSync("git", ["push", "origin", "main"], { cwd: writer });
|
||||
|
||||
const result = await createLegacyWorktreeForTest({
|
||||
branchName: "fresh-base",
|
||||
cwd: repoDir,
|
||||
baseBranch: "main",
|
||||
worktreeSlug: "fresh-base",
|
||||
paseoHome,
|
||||
});
|
||||
expect(existsSync(join(result.worktreePath, "new.txt"))).toBe(true);
|
||||
expect(await readPaseoWorktreeMetadata(result.worktreePath)).toMatchObject({
|
||||
baseRef: "refs/remotes/origin/main",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["tag", "commit"])("creates and compares a worktree from a %s base", async (kind) => {
|
||||
execFileSync("git", ["tag", "-a", "v1", "-m", "version one"], { cwd: repoDir });
|
||||
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
cwd: repoDir,
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
const requested = kind === "tag" ? "v1" : commit.slice(0, 12);
|
||||
const expected = kind === "tag" ? "refs/tags/v1" : commit;
|
||||
const result = await createWorktreePrimitive({
|
||||
cwd: repoDir,
|
||||
worktreeSlug: "ref-base",
|
||||
paseoHome,
|
||||
source: { kind: "branch-off", baseBranch: requested, branchName: "feature/ref-base" },
|
||||
});
|
||||
expect(await readPaseoWorktreeMetadata(result.worktreePath)).toMatchObject({
|
||||
baseRef: expected,
|
||||
});
|
||||
writeFileSync(join(result.worktreePath, "change.txt"), "feature work\n");
|
||||
execFileSync("git", ["add", "change.txt"], { cwd: result.worktreePath });
|
||||
execFileSync("git", ["-c", "commit.gpgsign=false", "commit", "-m", "feature"], {
|
||||
cwd: result.worktreePath,
|
||||
});
|
||||
const diff = await getCheckoutDiff(result.worktreePath, { mode: "base" }, { paseoHome });
|
||||
expect(diff.diff).toContain("+feature work");
|
||||
await expect(mergeToBase(result.worktreePath, {}, { paseoHome })).rejects.toThrow(
|
||||
"No local merge target is recorded",
|
||||
);
|
||||
});
|
||||
|
||||
it("creates a worktree for the current branch (main)", async () => {
|
||||
const projectHash = await deriveWorktreeProjectHash(repoDir);
|
||||
const result = await createLegacyWorktreeForTest({
|
||||
@@ -301,7 +359,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
baseRef: "main",
|
||||
aheadBehind: { ahead: 1, behind: 0 },
|
||||
});
|
||||
expect(result.comparisonBaseRef).toBe("main");
|
||||
expect(result.comparisonBaseRef).toBe("refs/heads/main");
|
||||
},
|
||||
);
|
||||
|
||||
@@ -359,7 +417,7 @@ describe.skipIf(isPlatform("win32"))("worktree POSIX-only", () => {
|
||||
});
|
||||
const diff = await getCheckoutDiff(created.worktreePath, { mode: "base" }, { paseoHome });
|
||||
expect(diff.diff).toContain("+feature change");
|
||||
expect(created.comparisonBaseRef).toBe("master");
|
||||
expect(created.comparisonBaseRef).toBe("refs/heads/master");
|
||||
});
|
||||
|
||||
it("falls back to the currently checked out branch when no default branch can be resolved", async () => {
|
||||
|
||||
@@ -37,7 +37,13 @@ import {
|
||||
} from "./worktree-metadata.js";
|
||||
import { runWithRepositoryRoot } from "./git-repository-discovery.js";
|
||||
import { runGitCommand, type RunGitCommand } from "./run-git-command.js";
|
||||
import { getCurrentBranch, resolveRepositoryDefaultBranch } from "./checkout-git.js";
|
||||
import { getCurrentBranch } from "./checkout-git.js";
|
||||
import {
|
||||
resolveBaseRefInput,
|
||||
resolveRepositoryDefaultBaseRef,
|
||||
refreshRemoteBaseRef,
|
||||
resolveRemoteBranchBaseRef,
|
||||
} from "./worktree-base-ref.js";
|
||||
import { spawnProcess } from "./spawn.js";
|
||||
import { applyLaunchWrap } from "./launch-wrap.js";
|
||||
import { resolvePaseoHome } from "../server/paseo-home.js";
|
||||
@@ -2011,6 +2017,7 @@ interface AdoptPluginWorktreeOptions {
|
||||
existingWorktreePaths?: ReadonlySet<string>;
|
||||
/** Remote head commit resolved before invoking the manager for change-request checkouts (`null` if unresolvable). */
|
||||
expectedChangeRequestHeadSha?: string | null;
|
||||
changeRequestRemote?: string;
|
||||
}
|
||||
|
||||
export interface RunPluginWorktreeManagerCheckoutOptions<
|
||||
@@ -2075,11 +2082,12 @@ async function runPluginWorktreeManagerCheckoutAtRepositoryRoot(
|
||||
if (!existingWorktreePaths) {
|
||||
return null;
|
||||
}
|
||||
const expectedChangeRequestHeadSha =
|
||||
const changeRequestHead =
|
||||
operation === "create" &&
|
||||
(source.kind === "checkout-change-request" || source.kind === "checkout-github-pr")
|
||||
? await fetchChangeRequestHeadSha(cwd, source)
|
||||
: undefined;
|
||||
const expectedChangeRequestHeadSha = changeRequestHead?.sha;
|
||||
const managed = await run(
|
||||
expectedChangeRequestHeadSha ? { changeRequestHeadSha: expectedChangeRequestHeadSha } : {},
|
||||
);
|
||||
@@ -2103,6 +2111,7 @@ async function runPluginWorktreeManagerCheckoutAtRepositoryRoot(
|
||||
worktreeManagerPluginId: managed.pluginId,
|
||||
existingWorktreePaths,
|
||||
expectedChangeRequestHeadSha,
|
||||
changeRequestRemote: changeRequestHead?.remote,
|
||||
});
|
||||
} catch (error) {
|
||||
return cleanupFailedPluginWorktree(
|
||||
@@ -2242,6 +2251,7 @@ async function adoptPluginWorktree(
|
||||
worktreeManagerPluginId,
|
||||
existingWorktreePaths,
|
||||
expectedChangeRequestHeadSha,
|
||||
changeRequestRemote,
|
||||
} = options;
|
||||
const normalizedPath = await normalizePathForOwnership(worktreePath);
|
||||
const normalizedIdentity = normalizePathForIdentity(normalizedPath);
|
||||
@@ -2307,7 +2317,15 @@ async function adoptPluginWorktree(
|
||||
await applyWorktreeRemotePlan(cwd, branchName, remotePlan);
|
||||
}
|
||||
|
||||
const metadata = await resolveWorktreeMetadata({ cwd, source, branchName });
|
||||
const resolvedBaseRef =
|
||||
changeRequestRemote &&
|
||||
(source.kind === "checkout-change-request" || source.kind === "checkout-github-pr")
|
||||
? ((await resolveRemoteBranchBaseRef(cwd, {
|
||||
remote: changeRequestRemote,
|
||||
branch: source.baseRefName,
|
||||
})) ?? undefined)
|
||||
: undefined;
|
||||
const metadata = await resolveWorktreeMetadata({ cwd, source, branchName, resolvedBaseRef });
|
||||
await writePaseoWorktreeMetadata(normalizedPath, {
|
||||
baseRefName: metadata.metadataBaseRefName,
|
||||
...(metadata.metadataBaseRef ? { baseRef: metadata.metadataBaseRef } : {}),
|
||||
@@ -2333,11 +2351,11 @@ async function adoptPluginWorktree(
|
||||
async function fetchChangeRequestHeadSha(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "checkout-change-request" | "checkout-github-pr" }>,
|
||||
): Promise<string> {
|
||||
): Promise<{ sha: string; remote: string }> {
|
||||
const changeRequestNumber =
|
||||
source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber;
|
||||
const destination = `refs/paseo/change-requests/${changeRequestNumber}`;
|
||||
await fetchFirstAvailableRef({
|
||||
const remote = await fetchFirstAvailableRef({
|
||||
cwd,
|
||||
destination,
|
||||
sources: source.checkoutRefs ?? [
|
||||
@@ -2347,7 +2365,7 @@ async function fetchChangeRequestHeadSha(
|
||||
const { stdout } = await runGitCommand(["rev-parse", "--verify", `${destination}^{commit}`], {
|
||||
cwd,
|
||||
});
|
||||
return stdout.trim();
|
||||
return { sha: stdout.trim(), remote };
|
||||
}
|
||||
|
||||
async function verifyPluginChangeRequestHead(options: {
|
||||
@@ -2360,7 +2378,7 @@ async function verifyPluginChangeRequestHead(options: {
|
||||
const { cwd, source, worktreePath, worktreeManagerPluginId, expectedChangeRequestHeadSha } =
|
||||
options;
|
||||
const expectedHead =
|
||||
expectedChangeRequestHeadSha ?? (await fetchChangeRequestHeadSha(cwd, source));
|
||||
expectedChangeRequestHeadSha ?? (await fetchChangeRequestHeadSha(cwd, source)).sha;
|
||||
const { stdout: headStdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], {
|
||||
cwd: worktreePath,
|
||||
});
|
||||
@@ -2408,7 +2426,7 @@ async function verifyPluginCheckoutTarget(options: {
|
||||
const target =
|
||||
source.kind === "restore-commit"
|
||||
? source.commit
|
||||
: await resolveBaseBranchForWorktree(cwd, source.baseRef);
|
||||
: await resolveBaseRefInput(cwd, source.baseRef);
|
||||
const [head, expected] = await Promise.all([
|
||||
runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], { cwd: worktreePath }),
|
||||
runGitCommand(["rev-parse", "--verify", `${target}^{commit}`], { cwd }),
|
||||
@@ -2427,7 +2445,7 @@ async function verifyPluginCheckoutTarget(options: {
|
||||
|
||||
async function tryResolveExactBaseRef(cwd: string, ref: string): Promise<string | undefined> {
|
||||
try {
|
||||
return await resolveBaseBranchForWorktree(cwd, ref);
|
||||
return await resolveBaseRefInput(cwd, ref);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -2480,13 +2498,18 @@ async function resolveWorktreeMetadata(options: {
|
||||
}): Promise<ResolvedWorktreeMetadata> {
|
||||
const { cwd, source, branchName, resolvedBaseRef } = options;
|
||||
if (source.kind === "checkout-change-request" || source.kind === "checkout-github-pr") {
|
||||
return resolveChangeRequestMetadata(source, branchName);
|
||||
const metadata = resolveChangeRequestMetadata(source, branchName);
|
||||
return { ...metadata, ...(resolvedBaseRef ? { metadataBaseRef: resolvedBaseRef } : {}) };
|
||||
}
|
||||
if (source.kind === "checkout-branch") {
|
||||
const resolvedBranch = branchName ?? source.branchName;
|
||||
const metadataBaseRefName =
|
||||
const metadataBaseRef =
|
||||
resolvedBaseRef ?? (await resolveCheckoutBranchBaseRef(cwd, resolvedBranch));
|
||||
return { metadataBaseRefName, ...branchChangeRequestHint(resolvedBranch) };
|
||||
return {
|
||||
metadataBaseRefName: normalizeRequiredBaseBranch(metadataBaseRef),
|
||||
metadataBaseRef,
|
||||
...branchChangeRequestHint(resolvedBranch),
|
||||
};
|
||||
}
|
||||
if (source.kind === "branch-off") {
|
||||
const metadataBaseRefName = normalizeRequiredBaseBranch(source.baseBranch);
|
||||
@@ -2504,9 +2527,7 @@ async function resolveWorktreeMetadata(options: {
|
||||
);
|
||||
const metadataBaseRef =
|
||||
resolvedBaseRef ??
|
||||
(source.baseRef && isQualifiedRef(source.baseRef)
|
||||
? await tryResolveExactBaseRef(cwd, source.baseRef)
|
||||
: undefined);
|
||||
(source.baseRef ? await tryResolveExactBaseRef(cwd, source.baseRef) : undefined);
|
||||
return {
|
||||
metadataBaseRefName,
|
||||
...(metadataBaseRef ? { metadataBaseRef } : {}),
|
||||
@@ -2571,7 +2592,14 @@ async function resolveRestoredCommitSourcePlan(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "restore-commit" }>,
|
||||
): Promise<WorktreeSourcePlan> {
|
||||
const metadata = await resolveWorktreeMetadata({ cwd, source, branchName: null });
|
||||
const baseRef = await resolveBaseRefInput(cwd, source.baseRef);
|
||||
await refreshRemoteBaseRef(cwd, baseRef);
|
||||
const metadata = await resolveWorktreeMetadata({
|
||||
cwd,
|
||||
source,
|
||||
branchName: null,
|
||||
resolvedBaseRef: baseRef,
|
||||
});
|
||||
return {
|
||||
branchName: null,
|
||||
...metadata,
|
||||
@@ -2584,7 +2612,8 @@ async function resolveRestoredWorktreeFromBasePlan(
|
||||
source: Extract<WorktreeSource, { kind: "restore-from-base" }>,
|
||||
): Promise<WorktreeSourcePlan> {
|
||||
await validateGitBranchName(cwd, source.branchName);
|
||||
const baseRef = await resolveBaseBranchForWorktree(cwd, source.baseRef);
|
||||
const baseRef = await resolveBaseRefInput(cwd, source.baseRef);
|
||||
await refreshRemoteBaseRef(cwd, baseRef);
|
||||
const branchName = await resolveUniqueLocalBranchName(cwd, source.branchName);
|
||||
const metadata = await resolveWorktreeMetadata({
|
||||
cwd,
|
||||
@@ -2614,11 +2643,12 @@ async function prepareWorktreeBranchOffAtRepositoryRoot(
|
||||
source: Extract<WorktreeSource, { kind: "branch-off" }>,
|
||||
previous?: PreparedWorktreeBranchOff,
|
||||
): Promise<PreparedWorktreeBranchOff> {
|
||||
const baseRef = previous?.baseRef ?? (await resolveBaseBranchForWorktree(cwd, source.baseBranch));
|
||||
const baseRef = previous?.baseRef ?? (await resolveBaseRefInput(cwd, source.baseBranch));
|
||||
const branchExists = await localBranchExists(cwd, source.branchName);
|
||||
const checkoutRef = branchExists ? source.branchName : (source.startPoint ?? baseRef);
|
||||
if (checkoutRef !== previous?.checkoutRef) {
|
||||
await refreshRemoteTrackingBaseRef(cwd, checkoutRef);
|
||||
if (!previous) {
|
||||
await refreshRemoteBaseRef(cwd, baseRef);
|
||||
if (checkoutRef !== baseRef) await refreshRemoteBaseRef(cwd, checkoutRef);
|
||||
}
|
||||
return { baseRef, branchExists, checkoutRef };
|
||||
}
|
||||
@@ -2705,26 +2735,38 @@ async function resolveWorktreeSourcePlan({
|
||||
const localBranchName = await resolveUniqueLocalBranchName(cwd, localBranchCandidate);
|
||||
const changeRequestNumber =
|
||||
source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber;
|
||||
await fetchFirstAvailableRef({
|
||||
const servingRemote = await fetchFirstAvailableRef({
|
||||
cwd,
|
||||
destination: `refs/heads/${localBranchName}`,
|
||||
sources: source.checkoutRefs ?? [
|
||||
{ remoteName: "origin", remoteRef: `refs/pull/${changeRequestNumber}/head` },
|
||||
],
|
||||
});
|
||||
const remotePlan = await resolveChangeRequestRemotePlan(cwd, source, localBranchName);
|
||||
|
||||
const metadata = await resolveWorktreeMetadata({
|
||||
cwd,
|
||||
source,
|
||||
branchName: localBranchName,
|
||||
});
|
||||
return {
|
||||
branchName: localBranchName,
|
||||
...metadata,
|
||||
addArguments: [localBranchName],
|
||||
...remotePlan,
|
||||
};
|
||||
const fetchedTip = await readLocalBranchTip(cwd, localBranchName);
|
||||
try {
|
||||
const remotePlan = await resolveChangeRequestRemotePlan(cwd, source, localBranchName);
|
||||
const metadata = await resolveWorktreeMetadata({
|
||||
cwd,
|
||||
source,
|
||||
branchName: localBranchName,
|
||||
resolvedBaseRef:
|
||||
(await resolveRemoteBranchBaseRef(cwd, {
|
||||
remote: servingRemote,
|
||||
branch: source.baseRefName,
|
||||
})) ?? undefined,
|
||||
});
|
||||
return {
|
||||
branchName: localBranchName,
|
||||
...metadata,
|
||||
addArguments: [localBranchName],
|
||||
...remotePlan,
|
||||
};
|
||||
} catch (error) {
|
||||
if (fetchedTip && (await readLocalBranchTip(cwd, localBranchName)) === fetchedTip) {
|
||||
await runGitCommand(["branch", "-D", localBranchName], { cwd }).catch(() => {});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2987,81 +3029,12 @@ function normalizeRequiredBaseBranch(baseBranch: string): string {
|
||||
// whichever branch is currently checked out in the main repo, since that's
|
||||
// almost always the branch this one was intended to be compared against.
|
||||
async function resolveCheckoutBranchBaseRef(cwd: string, branchName: string): Promise<string> {
|
||||
const defaultBranch = await resolveRepositoryDefaultBranch(cwd);
|
||||
const defaultBranch = await resolveRepositoryDefaultBaseRef(cwd);
|
||||
if (defaultBranch) {
|
||||
return defaultBranch;
|
||||
}
|
||||
const currentBranch = await getCurrentBranch(cwd);
|
||||
return currentBranch && currentBranch !== branchName ? currentBranch : branchName;
|
||||
}
|
||||
|
||||
async function resolveBaseBranchForWorktree(
|
||||
cwd: string,
|
||||
requestedBaseBranch: string,
|
||||
): Promise<string> {
|
||||
const requested = requestedBaseBranch.trim();
|
||||
const normalized = normalizeRequiredBaseBranch(requested);
|
||||
let exactRef: string | null = null;
|
||||
if (isQualifiedRef(requested)) {
|
||||
exactRef = requested;
|
||||
} else if (requested.startsWith("origin/")) {
|
||||
exactRef = `refs/remotes/${requested}`;
|
||||
}
|
||||
|
||||
if (exactRef) {
|
||||
try {
|
||||
await runGitCommand(["rev-parse", "--verify", exactRef], { cwd });
|
||||
return exactRef;
|
||||
} catch {
|
||||
throw new Error(`Base branch not found: ${exactRef}`);
|
||||
}
|
||||
}
|
||||
|
||||
const candidates = [`refs/heads/${requested}`, `refs/remotes/origin/${requested}`, requested];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await runGitCommand(["rev-parse", "--verify", candidate], { cwd });
|
||||
return candidate;
|
||||
} catch {
|
||||
// Try the next unambiguous local, remote, or legacy ref candidate.
|
||||
}
|
||||
}
|
||||
throw new Error(`Base branch not found: ${normalized}`);
|
||||
}
|
||||
|
||||
// Clients give up on a create request after 60s. A remote that accepts the connection and never
|
||||
// answers (a VPN-only host while off the VPN) must fall back to the cached ref well before that.
|
||||
const REMOTE_BASE_REFRESH_TIMEOUT_MS = 15_000;
|
||||
|
||||
// A remote-tracking base is only as fresh as the last fetch, and the background fetch only runs
|
||||
// while a workspace of the repository is observed. Refresh the one base branch so the new branch
|
||||
// starts at the remote tip; when the fetch fails (offline, auth) the cached ref is still usable.
|
||||
async function refreshRemoteTrackingBaseRef(cwd: string, baseRef: string): Promise<void> {
|
||||
if (!baseRef.startsWith("refs/remotes/")) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Remote names may contain slashes, so the owning remote is looked up rather than parsed.
|
||||
const { stdout } = await runGitCommand(["remote"], { cwd });
|
||||
const remoteName = stdout
|
||||
.split("\n")
|
||||
.map((name) => name.trim())
|
||||
.find((name) => name.length > 0 && baseRef.startsWith(`refs/remotes/${name}/`));
|
||||
if (!remoteName) {
|
||||
return;
|
||||
}
|
||||
const remoteBranch = baseRef.slice(`refs/remotes/${remoteName}/`.length);
|
||||
// No refspec is added to remote.<name>.fetch: one left behind breaks later fetches once the
|
||||
// branch is deleted on the remote.
|
||||
await runGitCommand(["fetch", remoteName, `+refs/heads/${remoteBranch}:${baseRef}`], {
|
||||
cwd,
|
||||
envOverlay: { GIT_TERMINAL_PROMPT: "0" },
|
||||
timeout: REMOTE_BASE_REFRESH_TIMEOUT_MS,
|
||||
acceptExitCodes: [0, 1, 128],
|
||||
});
|
||||
} catch {
|
||||
// The fetch timed out; branch from the cached ref.
|
||||
}
|
||||
return `refs/heads/${currentBranch && currentBranch !== branchName ? currentBranch : branchName}`;
|
||||
}
|
||||
|
||||
async function ensureLocalBranch(cwd: string, branchName: string): Promise<void> {
|
||||
|
||||
Reference in New Issue
Block a user