Skip to content
22 changes: 22 additions & 0 deletions apps/server/src/vcs/GitVcsDriverCore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,28 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);

it.effect("matches only colliding refs in collision query mode", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
yield* git(cwd, ["branch", "feature/alpha"]);
yield* git(cwd, ["branch", "unrelated-feature"]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const collisions = (query: string) =>
driver
.listRefs({ cwd, query, queryMode: "collision", refKind: "local" })
.pipe(Effect.map((result) => result.refs.map((ref) => ref.name).toSorted()));

// Exact, plus both halves of a directory/file collision.
assert.deepStrictEqual(yield* collisions("feature/alpha"), ["feature/alpha"]);
assert.deepStrictEqual(yield* collisions("feature"), ["feature/alpha"]);
assert.deepStrictEqual(yield* collisions("feature/alpha/beta"), ["feature/alpha"]);
// A substring match is not a collision.
assert.deepStrictEqual(yield* collisions("feat"), []);
assert.deepStrictEqual(yield* collisions("alpha"), []);
}),
);

it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
Expand Down
15 changes: 14 additions & 1 deletion apps/server/src/vcs/GitVcsDriverCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,14 +208,27 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}

/**
* Refs git refuses to let `name` coexist with: the same ref, one nested under
* it, or one it would nest under (`feat` and `feat/foo` collide either way).
*/
function refCollidesWithName(refName: string, name: string): boolean {
return refName === name || refName.startsWith(`${name}/`) || name.startsWith(`${refName}/`);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Collision check ignores letter case

Medium Severity

refCollidesWithName compares refs with case-sensitive equality and prefix checks. Sibling helpers in the same package already treat branch collisions as case-insensitive, and git with core.ignorecase (default on macOS and Windows) refuses a new branch that differs from an existing one only by case. The input can mark a name available and the send path will proceed, then git worktree add -b fails.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 64bb942. Configure here.


function filterBranchesForListQuery(
refs: ReadonlyArray<VcsRef>,
query?: string,
queryMode?: "substring" | "collision",
): ReadonlyArray<VcsRef> {
if (!query) {
return refs;
}

if (queryMode === "collision") {
return refs.filter((refName) => refCollidesWithName(refName.name, query));
}

const normalizedQuery = query.toLowerCase();
return refs.filter((refName) => refName.name.toLowerCase().includes(normalizedQuery));
}
Expand Down Expand Up @@ -2805,7 +2818,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
? allBranches.filter((ref) => ref.isRemote)
: allBranches;
const refs = paginateBranches({
refs: filterBranchesForListQuery(branchesForKind, input.query),
refs: filterBranchesForListQuery(branchesForKind, input.query, input.queryMode),
cursor: input.cursor,
limit: input.limit,
});
Expand Down
76 changes: 59 additions & 17 deletions apps/web/src/components/BranchToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import {
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
import {
BranchToolbarWorktreeNameInput,
type WorktreeBranchNameStatus,
} from "./BranchToolbarWorktreeNameInput";
import { Button } from "./ui/button";
import {
Menu,
Expand All @@ -52,6 +56,7 @@ interface BranchToolbarProps {
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
startFromOrigin: boolean;
onStartFromOriginChange: (startFromOrigin: boolean) => void;
onWorktreeBranchNameStatusChange?: (status: WorktreeBranchNameStatus | null) => void;
envLocked: boolean;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
Expand Down Expand Up @@ -126,7 +131,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({

if (isLocked) {
return (
<span className="inline-flex h-7 min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden">
<span className="inline-flex h-7 min-w-0 max-w-[48%] shrink items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden">
{triggerContent}
</span>
);
Expand All @@ -136,7 +141,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<Menu>
<MenuTrigger
render={<Button variant="ghost" size="xs" />}
className="min-w-0 max-w-[48%] flex-1 justify-start text-muted-foreground/70 hover:text-foreground/80 md:hidden"
className="min-w-0 max-w-[48%] shrink justify-start text-muted-foreground/70 hover:text-foreground/80 md:hidden"
>
{triggerContent}
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
Expand Down Expand Up @@ -384,6 +389,7 @@ export const BranchToolbar = memo(function BranchToolbar({
onActiveThreadBranchOverrideChange,
startFromOrigin,
onStartFromOriginChange,
onWorktreeBranchNameStatusChange,
envLocked,
onCheckoutPullRequestRequest,
onComposerFocusRequest,
Expand Down Expand Up @@ -463,29 +469,64 @@ export const BranchToolbar = memo(function BranchToolbar({
const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
const labelsOverflow = useLabelsOverflow(stripElement);

// Naming the next worktree's branch only makes sense before the first send,
// when a brand-new worktree (not a reused one) is about to be created.
const showWorktreeNameInput =
showGitControls &&
serverThread === null &&
draftThread !== null &&
effectiveEnvMode === "worktree" &&
activeWorktreePath === null &&
!envLocked;
const onWorktreeBranchNameChange = useCallback(
(value: string) => {
setDraftThreadContext(draftId ?? threadRef, {
worktreeBranchName: value.length > 0 ? value : null,
});
},
[draftId, setDraftThreadContext, threadRef],
);

if (!hasActiveThread || !activeProject) return null;

// Rendered in both layouts: a stored name the user can't see is a name they
// can't clear, and the send path ignores it while the input is unmounted.
const worktreeNameInput = showWorktreeNameInput ? (
<BranchToolbarWorktreeNameInput
environmentId={environmentId}
cwd={activeProject.workspaceRoot}
value={draftThread?.worktreeBranchName ?? ""}
onValueChange={onWorktreeBranchNameChange}
{...(onWorktreeBranchNameStatusChange
? { onStatusChange: onWorktreeBranchNameStatusChange }
: {})}
/>
) : null;

return (
<div
ref={setStripElement}
data-compact={labelsOverflow ? "" : undefined}
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
>
{isMobile && showGitControls ? (
<MobileRunContextSelector
envLocked={envLocked}
envModeLocked={envModeLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
<>
<MobileRunContextSelector
envLocked={envLocked}
envModeLocked={envModeLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
previousWorktreeLabel={previousWorktreeLabel}
onUsePreviousWorktree={onUsePreviousWorktree}
/>
{worktreeNameInput}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the mobile branch this input becomes a direct child of the strip, but useLabelsOverflow treats every direct child as a group and measures it with contentWidth(child), which sums child.children. An <input> has no element children, so it contributes 0 to needed (only the extra 8px strip gap is counted) even though it occupies up to w-44 (176px).

Because the same undercount applies in both directions, the expand test in compact mode (needed > available - 16) can conclude the expanded layout fits when it doesn't: the strip expands, the branch label then clips, needed > available fires, and it flips back to compact — a flap loop with FLIP animations at widths where the field is the deciding factor. In the desktop branch the input sits inside the flex min-w-0 flex-1 group div and is measured correctly, so only the mobile path is affected.

Smallest fix: give the mobile pair the same group container the desktop layout uses, e.g. wrap MobileRunContextSelector and {worktreeNameInput} in <div className="flex min-w-0 items-center gap-2"> (same gap the strip uses, so spacing is unchanged). Alternatively, have contentWidth fall back to the child's own offsetWidth when it has no element children.

Posted via Macroscope — UI Consistency

</>
) : (
<div className="flex min-w-0 flex-1 items-center gap-1">
{showEnvironmentIndicator && availableEnvironments && (
Expand Down Expand Up @@ -515,12 +556,13 @@ export const BranchToolbar = memo(function BranchToolbar({
onUsePreviousWorktree={onUsePreviousWorktree}
/>
) : null}
{worktreeNameInput}
</div>
)}

{showGitControls ? (
<BranchToolbarBranchSelector
className="min-w-0 flex-1 justify-end md:ml-auto md:flex-none"
className="min-w-0 flex-auto justify-end md:ml-auto md:flex-none"
environmentId={environmentId}
threadId={threadId}
{...(draftId ? { draftId } : {})}
Expand Down
117 changes: 117 additions & 0 deletions apps/web/src/components/BranchToolbarWorktreeNameInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { normalizeWorktreeBranchName, sanitizeWorktreeBranchNameInput } from "@t3tools/shared/git";
import { useDeferredValue, useEffect, useRef } from "react";

import { cn } from "../lib/utils";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { useEnvironmentQuery } from "../state/query";
import { vcsEnvironment } from "../state/vcs";

/**
* What the send path knows about the typed name. `null` means no name is in
* play (empty input, or the input isn't mounted to validate one), so the send
* path must fall back to the generated branch name.
*/
export interface WorktreeBranchNameStatus {
/** The normalized name — the branch that would actually be created. */
name: string;
state: "checking" | "available" | "conflict";
}

interface BranchToolbarWorktreeNameInputProps {
environmentId: EnvironmentId;
/** Project root the refs are checked against (the worktree doesn't exist yet). */
cwd: string;
value: string;
onValueChange: (value: string) => void;
onStatusChange?: (status: WorktreeBranchNameStatus | null) => void;
}

/**
* Low-profile input naming the branch the next worktree is created with.
* Left empty, the branch name is generated from the first message instead.
* Marks itself invalid when the name collides with an existing local branch.
*/
export function BranchToolbarWorktreeNameInput({
environmentId,
cwd,
value,
onValueChange,
onStatusChange,
}: BranchToolbarWorktreeNameInputProps) {
const normalizedValue = normalizeWorktreeBranchName(value);
const deferredNormalizedValue = useDeferredValue(normalizedValue);
const conflictRefsQuery = useEnvironmentQuery(
deferredNormalizedValue === null
? null
: vcsEnvironment.listRefs({
environmentId,
input: {
cwd,
query: deferredNormalizedValue,
// `collision` makes the server answer over every local ref, so
// `totalCount` is the whole answer and paging can't hide a match.
// Locals only — a remote ref can't block worktree creation.
queryMode: "collision",
refKind: "local",
limit: 1,
},
}),
);
// Only a settled lookup for the value currently typed can clear a name for
// send; while the deferred value lags or the query is in flight the answer
// belongs to a different name. A failed lookup counts as settled — the
// server rejects a duplicate branch anyway.
const checked =
deferredNormalizedValue === normalizedValue &&
(conflictRefsQuery.data !== null || conflictRefsQuery.error !== null);
const conflict = checked && (conflictRefsQuery.data?.totalCount ?? 0) > 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Slash and dash names share paths

Medium Severity

The new collision check only compares git ref hierarchy, but createWorktree turns every / in the branch name into - for the worktree directory. Names such as feat/foo and feat-foo are treated as available even when they map to the same path, so the second create fails after the UI has already cleared the name for send.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 64bb942. Configure here.

// The collision may be a parent or child of the typed name rather than the
// name itself, so the message names the ref actually in the way.
const conflictingRef = conflict ? (conflictRefsQuery.data?.refs[0]?.name ?? null) : null;
const conflictMessage =
conflictingRef === null
? null
: conflictingRef === normalizedValue
? `Branch "${conflictingRef}" already exists.`
: `Branch "${conflictingRef}" already exists, so "${normalizedValue}" can't be created.`;
const state = checked ? (conflict ? "conflict" : "available") : "checking";
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

const onStatusChangeRef = useRef(onStatusChange);
onStatusChangeRef.current = onStatusChange;
useEffect(() => {
onStatusChangeRef.current?.(normalizedValue === null ? null : { name: normalizedValue, state });
}, [normalizedValue, state]);
// The send gate must not outlive the input (e.g. switching back to
// "Current checkout"), or it would block sends it no longer applies to.
useEffect(() => () => onStatusChangeRef.current?.(null), []);

// The tooltip stays mounted and merely disabled so a collision appearing
// mid-keystroke can't remount the input out from under the caret.
return (
<Tooltip disabled={conflictMessage === null}>
<TooltipTrigger
render={
<input
type="text"
value={value}
onChange={(event) => onValueChange(sanitizeWorktreeBranchNameInput(event.target.value))}
placeholder="custom branch name"
spellCheck={false}
autoComplete="off"
aria-label="Branch name for the new worktree"
data-composer-context-control
aria-invalid={conflict || undefined}
className={cn(
"h-7 w-44 min-w-0 shrink rounded-md bg-transparent px-2 font-mono text-xs outline-none transition-colors sm:h-6",
"placeholder:font-sans placeholder:text-muted-foreground/50",
"hover:bg-muted/40 focus:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring",
conflict ? "text-destructive" : "text-muted-foreground/70 focus:text-foreground/80",
)}
/>
}
/>
<TooltipPopup side="top">{conflictMessage}</TooltipPopup>
</Tooltip>
);
}
Loading
Loading