Skip to content

fix(desktop): validate branch name for git ref path conflicts#1009

Closed
saddlepaddle wants to merge 1 commit intomainfrom
satya-patel/fix-kiet-mcp
Closed

fix(desktop): validate branch name for git ref path conflicts#1009
saddlepaddle wants to merge 1 commit intomainfrom
satya-patel/fix-kiet-mcp

Conversation

@saddlepaddle
Copy link
Copy Markdown
Collaborator

@saddlepaddle saddlepaddle commented Jan 27, 2026

Summary

  • Adds early validation to detect when a new branch name would conflict with existing branches due to Git's ref storage structure
  • Provides a clear error message with a suggested alternative (e.g., "Try using release-v61 instead")
  • Validation happens before any database writes or background jobs start, so MCP and UI both get immediate feedback

Problem

When creating a workspace with branch name release/v61, if a branch release already exists, Git fails with a cryptic error:

fatal: 'refs/heads/release' exists; cannot create 'refs/heads/release/v61'

This happened during background initialization, so the MCP got no useful feedback and the UI showed a generic "Workspace setup failed" dialog.

Solution

Added findBranchPathConflict() function that checks if a new branch name would conflict with existing branches. Now users see:

Cannot create branch "release/v61" because branch "release" already exists. 
Git cannot have branches where one is a path prefix of another. 
Try using "release-v61" instead.

Test plan

  • Added unit tests for findBranchPathConflict() function
  • Try creating a workspace with branch name that conflicts with existing branch
  • Verify error shows up immediately in UI and MCP response

Summary by CodeRabbit

  • Bug Fixes

    • Improved branch creation to detect and prevent naming conflicts with existing branches. Users now receive helpful error messages with suggestions for alternative names when conflicts occur.
  • Tests

    • Added test coverage for branch conflict detection scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

…workspace creation

Adds early validation to detect when a new branch name would conflict with
existing branches due to Git's ref storage structure (e.g., can't create
"release/v61" if "release" exists). This provides a clear error message
with a suggested alternative before any database writes or background
jobs start, ensuring MCP and UI both get immediate feedback.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 27, 2026

📝 Walkthrough

Walkthrough

A utility function for detecting Git ref path conflicts between branch names has been added, along with integration into the workspace branch creation procedure to validate new branch names against existing branches before creation.

Changes

Cohort / File(s) Summary
Branch creation validation
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
Added import and validation logic that calls findBranchPathConflict before branch creation. When creating a new branch, checks for conflicts with existing branches; throws error with suggested alternative name if a conflict is detected.
Branch conflict utility
apps/desktop/src/shared/utils/branch.ts
Implemented findBranchPathConflict() function that detects Git ref path conflicts by comparing branch names case-insensitively with slash boundaries. Returns the conflicting branch name or null.
Utility tests
apps/desktop/src/shared/utils/branch.test.ts
Added test suite for findBranchPathConflict covering multiple scenarios: child/parent conflicts, deep nesting, siblings, case-insensitivity, empty branches, and exact-match edge cases.

Sequence Diagram

sequenceDiagram
    participant User
    participant CreateProc as Create Procedure
    participant Checker as findBranchPathConflict
    participant Branches as Existing Branches

    User->>CreateProc: Request branch creation
    CreateProc->>Checker: Check for path conflicts
    Checker->>Branches: Compare new branch vs. existing
    alt Conflict detected
        Branches-->>Checker: Conflicting branch found
        Checker-->>CreateProc: Return conflicting name
        CreateProc-->>User: Error with suggested name
    else No conflict
        Branches-->>Checker: No conflict
        Checker-->>CreateProc: Return null
        CreateProc->>CreateProc: Proceed with branch creation
        CreateProc-->>User: Branch created successfully
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 A rabbit hops with care today,
Checking paths don't block the way,
No branch shall cross another's line,
Git's ref semantics now align,
Conflicts caught before they tangle,
Testing covers every angle! 🌿

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding validation for Git ref path conflicts during branch creation.
Description check ✅ Passed The description is comprehensive with clear problem statement, solution details, and test plan, though it differs from the template format.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts`:
- Around line 332-347: Replace the generic Error throw in the branch conflict
check with a TRPCError so tRPC handlers return a proper BAD_REQUEST; import
TRPCError from "@trpc/server" at the top of the file and change the throw inside
the block that uses findBranchPathConflict (the branch conflict logic in create
branch procedure) to: throw new TRPCError({ code: "BAD_REQUEST", message: /*
same message */ }); keeping the original message text (including suggestedName)
unchanged.
🧹 Nitpick comments (1)
apps/desktop/src/shared/utils/branch.test.ts (1)

91-140: Good test coverage for the conflict detection logic.

The test suite covers the essential scenarios including child/parent conflicts, deep nesting, case-insensitivity, and the important edge case of exact matches not being flagged as path conflicts.

Consider adding edge case tests for robustness:

🧪 Optional: Additional edge case tests
 	test("does not match exact same branch name", () => {
 		// Exact match is not a path conflict (it's a duplicate, handled elsewhere)
 		expect(findBranchPathConflict("release", ["release"])).toBe(null);
 	});
+
+	test("handles empty string new branch", () => {
+		expect(findBranchPathConflict("", ["release", "main"])).toBe(null);
+	});
+
+	test("handles branches with trailing slashes gracefully", () => {
+		// Edge case: malformed branch names
+		expect(findBranchPathConflict("release/", ["release"])).toBe("release");
+	});

Comment on lines +332 to +347
// Check for Git ref path conflicts when creating a new branch
// e.g., can't create "release/v61" if "release" exists (or vice versa)
if (!existingBranchName) {
const conflictingBranch = findBranchPathConflict(
branch,
existingBranches,
);
if (conflictingBranch) {
const suggestedName = branch.replace(/\//g, "-");
throw new Error(
`Cannot create branch "${branch}" because branch "${conflictingBranch}" already exists. ` +
`Git cannot have branches where one is a path prefix of another. ` +
`Try using "${suggestedName}" instead.`,
);
}
}
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.

🛠️ Refactor suggestion | 🟠 Major

Use TRPCError instead of generic Error for consistent API error handling.

The conflict detection logic is correctly placed before any database writes. However, per coding guidelines for tRPC procedures, validation errors should throw TRPCError with code BAD_REQUEST instead of generic Error.

🔧 Proposed fix using TRPCError

First, ensure TRPCError is imported:

import { TRPCError } from "@trpc/server";

Then update the throw statement:

 				if (!existingBranchName) {
 					const conflictingBranch = findBranchPathConflict(
 						branch,
 						existingBranches,
 					);
 					if (conflictingBranch) {
 						const suggestedName = branch.replace(/\//g, "-");
-						throw new Error(
-							`Cannot create branch "${branch}" because branch "${conflictingBranch}" already exists. ` +
-								`Git cannot have branches where one is a path prefix of another. ` +
-								`Try using "${suggestedName}" instead.`,
-						);
+						throw new TRPCError({
+							code: "BAD_REQUEST",
+							message:
+								`Cannot create branch "${branch}" because branch "${conflictingBranch}" already exists. ` +
+								`Git cannot have branches where one is a path prefix of another. ` +
+								`Try using "${suggestedName}" instead.`,
+						});
 					}
 				}
🤖 Prompt for AI Agents
In `@apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts` around
lines 332 - 347, Replace the generic Error throw in the branch conflict check
with a TRPCError so tRPC handlers return a proper BAD_REQUEST; import TRPCError
from "@trpc/server" at the top of the file and change the throw inside the block
that uses findBranchPathConflict (the branch conflict logic in create branch
procedure) to: throw new TRPCError({ code: "BAD_REQUEST", message: /* same
message */ }); keeping the original message text (including suggestedName)
unchanged.

@github-actions
Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ⚠️ Neon database branch
  • ⚠️ Electric Fly.io app

Thank you for your contribution! 🎉

@Kitenite Kitenite deleted the satya-patel/fix-kiet-mcp branch February 1, 2026 03:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant