Compare commits

...
Author SHA1 Message Date
Julius Marminge 7a897e9b1f Handle remote checkout conflicts without duplicate local branch
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
2026-02-28 21:47:48 -08:00
Julius Marminge 0595cc87ef Handle remote lookup failures in branch listing
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
2026-02-28 21:32:30 -08:00
Julius Marminge 10c2efe696 Filter detached HEAD pseudo-refs from branch listings
- ignore branch lines starting with `(` when parsing `git branch` output
- add integration test to verify detached HEAD does not appear as a branch
2026-02-28 21:08:25 -08:00
Julius Marminge ff3e81de21 Handle branch checkout and dedupe for slash-named remotes
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
2026-02-28 20:32:39 -08:00
Julius Marminge e7a3e938f1 Reorder sidebar thread status badges and title layout
- Move PR status indicator into the main thread info row
- Keep thread status badge and title grouped for consistent alignment
2026-02-28 20:19:31 -08:00
Julius Marminge 3399ff4336 Hide duplicate remote branches when local branch exists
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
2026-02-28 20:16:21 -08:00
Julius Marminge 4b83e28638 Support remote branch listing and tracking checkout flow
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
2026-02-28 19:53:45 -08:00
8 changed files with 695 additions and 46 deletions

No files matched your search

+218
View File
@@ -266,6 +266,18 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(tmp, ["checkout", "--detach", "HEAD"]);
const result = yield* listGitBranches({ cwd: tmp });
expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);
expect(result.branches.some((branch) => branch.current)).toBe(false);
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -370,6 +382,82 @@ it.layer(TestLayer)("git integration", (it) => {
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
it.effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: tmp, branch: "feature/local-only" });
const remoteOnlyBranch = "feature/remote-only";
yield* checkoutGitBranch({ cwd: tmp, branch: defaultBranch });
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", "origin", remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const firstRemoteIndex = result.branches.findIndex((branch) => branch.isRemote);
expect(firstRemoteIndex).toBeGreaterThan(0);
expect(result.branches.slice(0, firstRemoteIndex).every((branch) => !branch.isRemote)).toBe(
true,
);
expect(result.branches.slice(firstRemoteIndex).every((branch) => branch.isRemote)).toBe(
true,
);
expect(
result.branches.some((branch) => branch.name === "feature/local-only" && !branch.isRemote),
).toBe(true);
expect(
result.branches.some(
(branch) => branch.name === "origin/feature/remote-only" && branch.isRemote,
),
).toBe(true);
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
const remoteName = "my-org/upstream";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const defaultBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", remoteName, remote]);
yield* git(tmp, ["push", "-u", remoteName, defaultBranch]);
const remoteOnlyBranch = "feature/remote-with-remote-name";
yield* git(tmp, ["checkout", "-b", remoteOnlyBranch]);
yield* git(tmp, ["push", "-u", remoteName, remoteOnlyBranch]);
yield* git(tmp, ["checkout", defaultBranch]);
yield* git(tmp, ["branch", "-D", remoteOnlyBranch]);
const result = yield* listGitBranches({ cwd: tmp });
const remoteBranch = result.branches.find(
(branch) => branch.name === `${remoteName}/${remoteOnlyBranch}`,
);
expect(remoteBranch).toBeDefined();
expect(remoteBranch?.isRemote).toBe(true);
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
});
// ── checkoutGitBranch ──
@@ -592,6 +680,87 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"does not silently checkout a local branch when a remote ref no longer exists",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
yield* createGitBranch({ cwd: source, branch: "feature" });
const checkoutResult = yield* Effect.result(
checkoutGitBranch({ cwd: source, branch: "origin/feature" }),
);
expect(checkoutResult._tag).toBe("Failure");
expect(yield* git(source, ["branch", "--show-current"])).toBe(defaultBranch);
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature content\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["push", "-u", remoteName, featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
yield* git(source, ["branch", "-D", featureBranch]);
yield* checkoutGitBranch({ cwd: source, branch: `${remoteName}/${featureBranch}` });
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
}),
);
it.effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
// Keep local branch but remove tracking so `--track origin/<branch>`
// would attempt to create an already-existing local branch.
yield* git(source, ["branch", "--unset-upstream"]);
yield* checkoutGitBranch({ cwd: source, branch: `origin/${defaultBranch}` });
const core = yield* GitCore;
const status = yield* core.statusDetails(source);
expect(status.branch).toBeNull();
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1153,5 +1322,54 @@ it.layer(TestLayer)("git integration", (it) => {
expect(didFailRecency).toBe(true);
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
const realGitService = yield* GitService;
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore({
execute: (input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteBranches",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
if (input.args.join(" ") === "remote") {
didFailRemoteNames = true;
return Effect.fail(
new GitCommandError({
operation: "git.test.listBranchesRemoteNames",
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "remote unavailable",
}),
);
}
return realGitService.execute(input);
},
});
const result = yield* core.listBranches({ cwd: tmp });
expect(result.isRepo).toBe(true);
expect(result.branches.length).toBeGreaterThan(0);
expect(result.branches.every((branch) => !branch.isRemote)).toBe(true);
expect(didFailRemoteBranches).toBe(true);
expect(didFailRemoteNames).toBe(true);
}),
);
});
});
+254 -18
View File
@@ -76,6 +76,87 @@ function parsePorcelainPath(line: string): string | null {
return filePath.length > 0 ? filePath : null;
}
function parseBranchLine(line: string): { name: string; current: boolean } | null {
const trimmed = line.trim();
if (trimmed.length === 0) return null;
const name = trimmed.replace(/^[*+]\s+/, "");
// Exclude symbolic refs like: "origin/HEAD -> origin/main".
// Exclude detached HEAD pseudo-refs like: "(HEAD detached at origin/main)".
if (name.includes(" -> ") || name.startsWith("(")) return null;
return {
name,
current: trimmed.startsWith("* "),
};
}
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return null;
}
function parseTrackingBranchByUpstreamRef(
stdout: string,
upstreamRef: string,
): string | null {
for (const line of stdout.split("\n")) {
const trimmedLine = line.trim();
if (trimmedLine.length === 0) {
continue;
}
const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t");
const branchName = branchNameRaw?.trim() ?? "";
const upstreamBranch = upstreamBranchRaw.trim();
if (branchName.length === 0 || upstreamBranch.length === 0) {
continue;
}
if (upstreamBranch === upstreamRef) {
return branchName;
}
}
return null;
}
function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {
const separatorIndex = branchName.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {
return null;
}
const localBranch = branchName.slice(separatorIndex + 1).trim();
return localBranch.length > 0 ? localBranch : null;
}
function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
@@ -264,7 +345,12 @@ const makeGitCore = Effect.gen(function* () {
const branchRecency = yield* executeGit(
"GitCore.readBranchRecency",
cwd,
["for-each-ref", "--format=%(refname:short)%09%(committerdate:unix)", "refs/heads"],
[
"for-each-ref",
"--format=%(refname:short)%09%(committerdate:unix)",
"refs/heads",
"refs/remotes",
],
{
timeoutMs: 15_000,
allowNonZeroExit: true,
@@ -564,7 +650,7 @@ const makeGitCore = Effect.gen(function* () {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
);
const result = yield* executeGit(
const localBranchResult = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
@@ -574,8 +660,8 @@ const makeGitCore = Effect.gen(function* () {
},
);
if (result.code !== 0) {
const stderr = result.stderr.trim();
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return { branches: [], isRepo: false };
}
@@ -587,7 +673,40 @@ const makeGitCore = Effect.gen(function* () {
);
}
const [defaultRef, worktreeList, branchLastCommit] = yield* Effect.all(
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const remoteNamesResultEffect = executeGit(
"GitCore.listBranches.remoteNames",
input.cwd,
["remote"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.catch((error) =>
Effect.logWarning(
`GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`,
).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })),
),
);
const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] =
yield* Effect.all(
[
executeGit(
"GitCore.listBranches.defaultRef",
@@ -607,11 +726,25 @@ const makeGitCore = Effect.gen(function* () {
allowNonZeroExit: true,
},
),
remoteBranchResultEffect,
remoteNamesResultEffect,
branchRecencyPromise,
],
{ concurrency: "unbounded" },
);
const remoteNames = remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];
if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`,
);
}
if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) {
yield* Effect.logWarning(
`GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,
);
}
const defaultBranch =
defaultRef.code === 0
? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
@@ -636,19 +769,17 @@ const makeGitCore = Effect.gen(function* () {
}
}
const branches = result.stdout
const localBranches = localBranchResult.stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const name = line.replace(/^[*+]\s+/, "");
return {
name,
current: line.startsWith("* "),
isDefault: name === defaultBranch,
worktreePath: worktreeMap.get(name) ?? null,
};
})
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => ({
name: branch.name,
current: branch.current,
isRemote: false,
isDefault: branch.name === defaultBranch,
worktreePath: worktreeMap.get(branch.name) ?? null,
}))
.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
@@ -660,6 +791,43 @@ const makeGitCore = Effect.gen(function* () {
return a.name.localeCompare(b.name);
});
const remoteBranches =
remoteBranchResult.code === 0
? remoteBranchResult.stdout
.split("\n")
.map(parseBranchLine)
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
.map((branch) => {
const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames);
const remoteBranch: {
name: string;
current: boolean;
isRemote: boolean;
remoteName?: string;
isDefault: boolean;
worktreePath: string | null;
} = {
name: branch.name,
current: false,
isRemote: true,
isDefault: false,
worktreePath: null,
};
if (parsedRemoteRef) {
remoteBranch.remoteName = parsedRemoteRef.remoteName;
}
return remoteBranch;
})
.toSorted((a, b) => {
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
return a.name.localeCompare(b.name);
})
: [];
const branches = [...localBranches, ...remoteBranches];
return { branches, isRepo: true };
});
@@ -719,7 +887,75 @@ const makeGitCore = Effect.gen(function* () {
const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) =>
Effect.gen(function* () {
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, ["checkout", input.branch], {
const [localInputExists, remoteExists] = yield* Effect.all(
[
executeGit(
"GitCore.checkoutBranch.localInputExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
executeGit(
"GitCore.checkoutBranch.remoteExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0)),
],
{ concurrency: "unbounded" },
);
const localTrackingBranch =
remoteExists
? yield* executeGit(
"GitCore.checkoutBranch.localTrackingBranch",
input.cwd,
["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(
Effect.map((result) =>
result.code === 0
? parseTrackingBranchByUpstreamRef(result.stdout, input.branch)
: null,
),
)
: null;
const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch);
const localTrackedBranchTargetExists =
remoteExists && localTrackedBranchCandidate
? yield* executeGit(
"GitCore.checkoutBranch.localTrackedBranchTargetExists",
input.cwd,
["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`],
{
timeoutMs: 5_000,
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0))
: false;
const checkoutArgs =
localInputExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch && localTrackedBranchTargetExists
? ["checkout", input.branch]
: remoteExists && !localTrackingBranch
? ["checkout", "--track", input.branch]
: remoteExists && localTrackingBranch
? ["checkout", localTrackingBranch]
: ["checkout", input.branch];
yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
+1 -1
View File
@@ -101,7 +101,7 @@ export interface GitCoreShape {
) => Effect.Effect<string | null, GitCommandError>;
/**
* List local branches and branch metadata.
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
@@ -1,6 +1,10 @@
import { ThreadId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
const branches: GitBranch[] = [
{
@@ -57,3 +61,124 @@ describe("deriveSyncedLocalBranch", () => {
expect(result).toBeNull();
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
});
it("supports remote names that contain slashes", () => {
expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe(
"upstream/feature/demo",
);
});
it("returns the original name when ref is malformed", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/")).toBe("origin/");
expect(deriveLocalBranchNameFromRemoteRef("/feature/demo")).toBe("/feature/demo");
});
});
describe("dedupeRemoteBranchesWithLocalMatches", () => {
it("hides remote refs when the matching local branch exists", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/demo",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
});
it("keeps all entries when no local match exists for a remote ref", () => {
const input: GitBranch[] = [
{
name: "feature/local",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "origin/feature/remote-only",
isRemote: true,
remoteName: "origin",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/local",
"origin/feature/remote-only",
]);
});
it("dedupes remote refs for remotes whose names contain slashes", () => {
const input: GitBranch[] = [
{
name: "feature/demo",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature/demo",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"feature/demo",
]);
});
it("dedupes remote refs when git tracks with first-slash local naming", () => {
const input: GitBranch[] = [
{
name: "upstream/feature",
current: false,
isDefault: false,
worktreePath: null,
},
{
name: "my-org/upstream/feature",
isRemote: true,
remoteName: "my-org/upstream",
current: false,
isDefault: false,
worktreePath: null,
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
"upstream/feature",
]);
});
});
@@ -8,6 +8,54 @@ interface DeriveSyncedLocalBranchInput {
queryBranches: ReadonlyArray<GitBranch> | undefined;
}
export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
const firstSeparatorIndex = branchName.indexOf("/");
if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {
return branchName;
}
return branchName.slice(firstSeparatorIndex + 1);
}
function deriveLocalBranchNameCandidatesFromRemoteRef(
branchName: string,
remoteName?: string,
): ReadonlyArray<string> {
const candidates = new Set<string>();
const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);
if (firstSlashCandidate.length > 0) {
candidates.add(firstSlashCandidate);
}
if (remoteName) {
const remotePrefix = `${remoteName}/`;
if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {
candidates.add(branchName.slice(remotePrefix.length));
}
}
return [...candidates];
}
export function dedupeRemoteBranchesWithLocalMatches(
branches: ReadonlyArray<GitBranch>,
): ReadonlyArray<GitBranch> {
const localBranchNames = new Set(
branches.filter((branch) => !branch.isRemote).map((branch) => branch.name),
);
return branches.filter((branch) => {
if (!branch.isRemote) {
return true;
}
const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(
branch.name,
branch.remoteName,
);
return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));
});
}
export function deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
+29 -9
View File
@@ -10,7 +10,11 @@ import {
} from "../lib/gitReactQuery";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { deriveSyncedLocalBranch } from "./BranchToolbar.logic";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
Combobox,
@@ -55,7 +59,7 @@ export default function BranchToolbar({
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = branchesQuery.data?.branches ?? [];
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
@@ -174,10 +178,21 @@ export default function BranchToolbar({
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
checkoutMutation.mutate(branch.name, {
onSuccess: () => {
onSuccess: async () => {
setThreadError(null);
setThreadBranch(branch.name, activeWorktreePath);
let nextBranchName = selectedBranchName;
if (branch.isRemote) {
const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
if (status?.branch) {
nextBranchName = status.branch;
}
}
setThreadBranch(nextBranchName, activeWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
},
@@ -283,6 +298,15 @@ export default function BranchToolbar({
const hasSecondaryWorktree =
branch.worktreePath && branch.worktreePath !== activeProject.cwd;
const badge = branch.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
? "remote"
: branch.isDefault
? "default"
: null;
return (
<ComboboxItem
hideIndicator
@@ -295,11 +319,7 @@ export default function BranchToolbar({
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
{(branch.current || branch.isDefault || hasSecondaryWorktree) && (
<span className="shrink-0 text-[10px] text-muted-foreground/45">
{branch.current ? "current" : hasSecondaryWorktree ? "worktree" : "default"}
</span>
)}
{badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
</div>
</ComboboxItem>
);
+17 -17
View File
@@ -784,23 +784,6 @@ export default function Sidebar() {
}}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{prStatus && (
<Tooltip>
<TooltipTrigger
@@ -820,6 +803,23 @@ export default function Sidebar() {
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && (
<span
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
>
<span
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
threadStatus.pulse ? "animate-pulse" : ""
}`}
/>
<span className="hidden md:inline">{threadStatus.label}</span>
</span>
)}
<span className="min-w-0 flex-1 truncate text-xs">
{thread.title}
</span>
</div>
<div className="ml-auto flex shrink-0 items-center gap-1.5">
{terminalStatus && (
<span
role="img"
+2
View File
@@ -23,6 +23,8 @@ export type GitStatusPrState = typeof GitStatusPrState.Type;
export const GitBranch = Schema.Struct({
name: TrimmedNonEmptyStringSchema,
isRemote: Schema.optional(Schema.Boolean),
remoteName: Schema.optional(TrimmedNonEmptyStringSchema),
current: Schema.Boolean,
isDefault: Schema.Boolean,
worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),