Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 90 additions & 1 deletion packages/host-service/src/runtime/git/refs.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { describe, expect, mock, test } from "bun:test";
import { asLocalRef, asRemoteRef, resolveRef } from "./refs";
import {
asLocalRef,
asRemoteRef,
resolveRef,
resolveRefCaseInsensitive,
} from "./refs";

/**
* Mock git that knows about a fixed set of FULL refnames. Mirrors how
Expand Down Expand Up @@ -131,3 +136,87 @@ describe("resolveRef — input shape contract", () => {
}
});
});

/**
* `resolveRefCaseInsensitive` calls `for-each-ref` rather than probing
* single refs, so it needs a different mock — one that returns the full
* stored refnames as a newline-separated list.
*/
function createForEachRefMock(refnames: string[]) {
return {
raw: mock(async (args: string[]) => {
if (args[0] === "for-each-ref") {
return `${refnames.join("\n")}\n`;
}
throw new Error(`Unexpected raw args: ${args.join(" ")}`);
}),
} as never;
}

describe("resolveRefCaseInsensitive", () => {
test("returns canonical-case local ref when input differs only by case", async () => {
const git = createForEachRefMock(["refs/heads/Claude/Auto-Balance-1UFT7"]);
const r = await resolveRefCaseInsensitive(git, "claude/auto-balance-1uft7");
expect(r?.kind).toBe("local");
if (r?.kind === "local") {
expect(r.shortName).toBe("Claude/Auto-Balance-1UFT7");
expect(r.fullRef).toBe("refs/heads/Claude/Auto-Balance-1UFT7");
}
});

test("returns remote-tracking ref when only the remote ref matches case-insensitively", async () => {
const git = createForEachRefMock([
"refs/remotes/origin/claude/Auto-Balance-1UFT7",
]);
const r = await resolveRefCaseInsensitive(git, "claude/auto-balance-1uft7");
expect(r?.kind).toBe("remote-tracking");
if (r?.kind === "remote-tracking") {
expect(r.shortName).toBe("claude/Auto-Balance-1UFT7");
expect(r.remoteShortName).toBe("origin/claude/Auto-Balance-1UFT7");
}
});

test("local match wins when both local and remote-tracking match", async () => {
const git = createForEachRefMock([
"refs/remotes/origin/Foo-Bar",
"refs/heads/foo-BAR",
]);
const r = await resolveRefCaseInsensitive(git, "FOO-bar");
expect(r?.kind).toBe("local");
if (r?.kind === "local") {
expect(r.shortName).toBe("foo-BAR");
}
});

test("returns null when nothing matches case-insensitively", async () => {
const git = createForEachRefMock([
"refs/heads/main",
"refs/remotes/origin/main",
]);
expect(await resolveRefCaseInsensitive(git, "totally-other")).toBeNull();
});

test("strips a leading `<remote>/` prefix before matching", async () => {
const git = createForEachRefMock(["refs/remotes/origin/Feature-X"]);
const r = await resolveRefCaseInsensitive(git, "origin/feature-x");
expect(r?.kind).toBe("remote-tracking");
if (r?.kind === "remote-tracking") {
expect(r.shortName).toBe("Feature-X");
}
});

test("ignores `refs/remotes/<remote>/HEAD`", async () => {
const git = createForEachRefMock([
"refs/remotes/origin/HEAD",
"refs/heads/main",
]);
// `head` should NOT case-insensitive-match `HEAD`.
expect(await resolveRefCaseInsensitive(git, "head")).toBeNull();
});

test("empty/whitespace input → null", async () => {
const git = createForEachRefMock(["refs/heads/foo"]);
expect(await resolveRefCaseInsensitive(git, "")).toBeNull();
expect(await resolveRefCaseInsensitive(git, " ")).toBeNull();
});
});
71 changes: 71 additions & 0 deletions packages/host-service/src/runtime/git/refs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,77 @@ export async function resolveRef(
return options.headFallback ? { kind: "head" } : null;
}

/**
* Case-insensitive fallback for `resolveRef`. Branch names ARE
* case-sensitive in git, but humans aren't — pickers and clipboards
* routinely flatten case (cmdk's selected value, MS Word autocaps,
* a teammate retyping a generated `claude/...-1UFT7` from memory).
* Without this fallback the typed casing misses the existing ref and
* `workspaces.create` silently forks a fresh branch from base, which
* then opens a *new* PR on push.
*
* Returns a ref with the **canonical case** from git's storage, not the
* user's input. Local matches win over remote-tracking when both exist.
* Returns `null` if no case-insensitive match exists — the caller is
* expected to fall through to fresh-branch creation in that case.
*/
export async function resolveRefCaseInsensitive(
git: SimpleGit,
input: string,
options: ResolveRefOptions = {},
): Promise<ResolvedRef | null> {
const remote = options.remote ?? "origin";
const trimmed = input.trim();
if (!trimmed) return null;

const remotePrefix = `${remote}/`;
const normalized = trimmed.startsWith(remotePrefix)
? trimmed.slice(remotePrefix.length)
: trimmed;
const lowered = normalized.toLowerCase();

let raw: string;
try {
raw = await git.raw([
"for-each-ref",
"--format=%(refname)",
"refs/heads/",
`refs/remotes/${remote}/`,
]);
} catch {
return null;
}

let remoteMatch: ResolvedRef | null = null;
for (const line of raw.split("\n")) {
const refname = line.trim();
if (!refname) continue;
if (refname.startsWith("refs/heads/")) {
const name = refname.slice("refs/heads/".length);
if (name.toLowerCase() === lowered) {
return {
kind: "local",
fullRef: refname as `refs/heads/${string}`,
shortName: name,
};
}
} else if (refname.startsWith(`refs/remotes/${remote}/`)) {
const name = refname.slice(`refs/remotes/${remote}/`.length);
if (name === "HEAD") continue;
if (remoteMatch === null && name.toLowerCase() === lowered) {
remoteMatch = {
kind: "remote-tracking",
fullRef: refname as `refs/remotes/${string}/${string}`,
shortName: name,
remote,
remoteShortName: `${remote}/${name}`,
};
}
}
}
return remoteMatch;
}

/**
* Resolve the repo's default branch name (typically `main`) from
* `origin/HEAD`. Falls back to `"main"` if symbolic-ref isn't set.
Expand Down
19 changes: 19 additions & 0 deletions packages/host-service/src/trpc/router/workspaces/workspaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type ResolvedRef,
resolveDefaultBranchName,
resolveRef,
resolveRefCaseInsensitive,
resolveUpstream,
} from "../../../runtime/git/refs";
import type { HostServiceContext } from "../../../types";
Expand Down Expand Up @@ -273,6 +274,24 @@ async function planBranchSource(
});
}

// Case-insensitive fallback: branch names ARE case-sensitive in git, but
// the picker can show a remote-only branch like `claude/...-1UFT7` and
// the user's input pathway (cmdk's lowercased selected value, autocaps,
// retyping from memory) routinely flattens the casing. Without this
// fallback we silently fork a fresh branch from base and the next push
// opens a new PR instead of continuing the existing one.
const fuzzy = await resolveRefCaseInsensitive(git, branch);
if (
fuzzy &&
(fuzzy.kind === "local" || fuzzy.kind === "remote-tracking")
) {
return {
branch: fuzzy.shortName,
startPoint: fuzzy,
usedExistingBranch: true,
};
}

const startPoint = await resolveNewBranchStartPoint(git, baseBranch);
return { branch, startPoint, usedExistingBranch: false };
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { afterEach, describe, expect, test } from "bun:test";
import { randomUUID } from "node:crypto";
import { existsSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { TRPCClientError } from "@trpc/client";
import { eq } from "drizzle-orm";
import simpleGit from "simple-git";
import { workspaces } from "../../src/db/schema";
import { cloudFlows, cloudOk } from "../helpers/cloud-fakes";
import {
Expand Down Expand Up @@ -253,6 +255,139 @@ describe("workspace.create + workspace.delete integration", () => {
expect(rows).toHaveLength(0);
});

test("create() with an existing remote-only branch checks out the remote tip, not a fresh fork from base (regress #4364)", async () => {
// Regress: when the user picks an existing remote branch in the
// workspace-create flow, `workspaces.create` must check it out into
// a worktree that tracks the remote — not silently create a new
// branch from the default base. The bug surfaced as "the worktree
// for `claude/...-1UFT7` opens at main's HEAD" instead of the
// remote branch's tip, leading the next push to open a *new* PR
// instead of continuing the existing one.
const scenario = await createProjectScenario({
hostOptions: { apiOverrides: cloudFlows.workspaceCreateOk() },
});
dispose = scenario.dispose;

const bareRepoPath = realpathSync(
mkdtempSync(join(tmpdir(), "host-service-test-bare-")),
);
try {
await simpleGit().init(["--bare", "--initial-branch=main", bareRepoPath]);
await scenario.repo.git.addRemote("origin", bareRepoPath);
await scenario.repo.git.push("origin", "main", ["--set-upstream"]);

// Mixed-case branch name copied from the linked issue. Push it
// to origin, capture the tip, then delete it locally so only the
// remote-tracking ref remains — this is the state the user is in
// when they open the picker fresh on a different machine.
const remoteBranch = "claude/auto-balance-logo-sizing-1UFT7";
await scenario.repo.git.checkoutBranch(remoteBranch, "main");
const remoteTipOid = await scenario.repo.commit("remote work", {
"feature.txt": "remote feature work",
});
await scenario.repo.git.push("origin", remoteBranch);
await scenario.repo.git.checkout("main");
await scenario.repo.git.deleteLocalBranch(remoteBranch, true);
await scenario.repo.git.fetch(["origin", "--prune"]);

const result = await scenario.host.trpc.workspaces.create.mutate({
projectId: scenario.projectId,
name: "continue remote work",
branch: remoteBranch,
});

expect(result?.workspace?.branch).toBe(remoteBranch);

const persisted = scenario.host.db
.select()
.from(workspaces)
.where(eq(workspaces.id, result?.workspace?.id ?? ""))
.get();
expect(persisted?.worktreePath).toBeTruthy();
expect(existsSync(persisted?.worktreePath ?? "")).toBe(true);

// The worktree's HEAD must equal the remote branch tip — not
// main. If `workspaces.create` forked from main instead of
// checking out the remote, this is what would catch it.
const worktreeGit = simpleGit(persisted?.worktreePath ?? "");
const worktreeHead = (
await worktreeGit.raw(["rev-parse", "HEAD"])
).trim();
expect(worktreeHead).toBe(remoteTipOid);

// And the local branch must track origin/<branch> so subsequent
// pushes/pulls land on the same remote ref the picker pointed at.
const upstream = (
await worktreeGit.raw([
"rev-parse",
"--abbrev-ref",
`${remoteBranch}@{upstream}`,
])
).trim();
expect(upstream).toBe(`origin/${remoteBranch}`);
} finally {
rmSync(bareRepoPath, { recursive: true, force: true });
}
});

test("create() with a remote branch typed in a different case checks out the existing remote branch (regress #4364)", async () => {
// Regress: the user's exact #4364 scenario. The picker showed a
// remote branch `claude/auto-balance-logo-sizing-1UFT7`, the user
// pasted `claude/auto-balance-logo-sizing-1uft7` (case-folded by
// the cmdk Mod+Enter pathway and/or the OS), and the server
// silently created a *new* branch with the typed casing instead
// of opening a worktree on the remote tip. The next push then
// opened a brand-new PR.
const scenario = await createProjectScenario({
hostOptions: { apiOverrides: cloudFlows.workspaceCreateOk() },
});
dispose = scenario.dispose;

const bareRepoPath = realpathSync(
mkdtempSync(join(tmpdir(), "host-service-test-bare-")),
);
try {
await simpleGit().init(["--bare", "--initial-branch=main", bareRepoPath]);
await scenario.repo.git.addRemote("origin", bareRepoPath);
await scenario.repo.git.push("origin", "main", ["--set-upstream"]);

const remoteBranch = "claude/auto-balance-logo-sizing-1UFT7";
const typedBranch = "claude/auto-balance-logo-sizing-1uft7";
await scenario.repo.git.checkoutBranch(remoteBranch, "main");
const remoteTipOid = await scenario.repo.commit("remote work", {
"feature.txt": "remote feature work",
});
await scenario.repo.git.push("origin", remoteBranch);
await scenario.repo.git.checkout("main");
await scenario.repo.git.deleteLocalBranch(remoteBranch, true);
await scenario.repo.git.fetch(["origin", "--prune"]);

const result = await scenario.host.trpc.workspaces.create.mutate({
projectId: scenario.projectId,
name: "continue remote work",
branch: typedBranch,
});

const persisted = scenario.host.db
.select()
.from(workspaces)
.where(eq(workspaces.id, result?.workspace?.id ?? ""))
.get();
expect(persisted?.worktreePath).toBeTruthy();

// The worktree should be on the remote branch tip, not a fresh
// fork from main. If the server created a brand-new branch the
// HEAD would equal main's commit.
const worktreeGit = simpleGit(persisted?.worktreePath ?? "");
const worktreeHead = (
await worktreeGit.raw(["rev-parse", "HEAD"])
).trim();
expect(worktreeHead).toBe(remoteTipOid);
} finally {
rmSync(bareRepoPath, { recursive: true, force: true });
}
});

test("delete() rejects deleting a main workspace by path equality", async () => {
const scenario = await createBasicScenario();
dispose = scenario.dispose;
Expand Down