Guard worktree branch rename and fix branch toolbar state

- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
This commit is contained in:
Julius Marminge committed 2026-03-02 16:17:07 -08:00
1 parent ecb4a1efa4
commit dcb2c2f225
5 files changed
+231 -76

No files matched your search

@@ -108,11 +108,27 @@ describe("ProviderCommandReactor", () => {
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn((_: unknown) => Effect.void);
const stopSession = vi.fn((_: unknown) => Effect.void);
const statusBranchByCwd = new Map<string, string | null>();
const renameBranch = vi.fn((_: unknown) =>
Effect.succeed({
branch: "t3code/generated-name",
}),
);
const statusDetails = vi.fn((cwd: string) =>
Effect.succeed({
branch: statusBranchByCwd.get(cwd) ?? null,
upstreamRef: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
insertions: 0,
deletions: 0,
},
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
}),
);
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
Effect.succeed({
branch: "generated-name",
@@ -141,7 +157,12 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(
GitCore,
{ renameBranch, statusDetails } as unknown as GitCoreShape,
),
),
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
),
@@ -189,7 +210,11 @@ describe("ProviderCommandReactor", () => {
respondToRequest,
stopSession,
renameBranch,
statusDetails,
generateBranchName,
setStatusBranch: (cwd: string, branch: string | null) => {
statusBranchByCwd.set(cwd, branch);
},
stateDir,
};
}
@@ -235,6 +260,7 @@ describe("ProviderCommandReactor", () => {
it("generates and renames temporary worktree branch on first turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const worktreeCwd = "/tmp/provider-project/.t3/worktrees/t3code-89abc123";
await Effect.runPromise(
harness.engine.dispatch({
@@ -242,9 +268,10 @@ describe("ProviderCommandReactor", () => {
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/89abc123",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
worktreePath: worktreeCwd,
}),
);
harness.setStatusBranch(worktreeCwd, "t3code/89abc123");
await Effect.runPromise(
harness.engine.dispatch({
@@ -275,7 +302,7 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
cwd: worktreeCwd,
message: "Fix visual bug from screenshot",
attachments: [
{
@@ -288,18 +315,14 @@ describe("ProviderCommandReactor", () => {
],
});
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
cwd: worktreeCwd,
oldBranch: "t3code/89abc123",
newBranch: "t3code/generated-name",
});
await waitFor(() => {
const readModel = Effect.runSync(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.branch === "t3code/generated-name";
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.branch).toBe("t3code/89abc123");
});
it("passes persisted attachment references to branch generation and turn start", async () => {
@@ -373,6 +396,7 @@ describe("ProviderCommandReactor", () => {
it("skips worktree branch generation after the first user turn", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const worktreeCwd = "/tmp/provider-project/.t3/worktrees/t3code-1234abcd";
await Effect.runPromise(
harness.engine.dispatch({
@@ -380,9 +404,10 @@ describe("ProviderCommandReactor", () => {
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
worktreePath: worktreeCwd,
}),
);
harness.setStatusBranch(worktreeCwd, "t3code/1234abcd");
await Effect.runPromise(
harness.engine.dispatch({
@@ -425,6 +450,44 @@ describe("ProviderCommandReactor", () => {
expect(harness.renameBranch.mock.calls.length).toBe(1);
});
it("skips worktree rename when active branch already changed", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const worktreeCwd = "/tmp/provider-project/.t3/worktrees/t3code-badf00d0";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-switched"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/badf00d0",
worktreePath: worktreeCwd,
}),
);
harness.setStatusBranch(worktreeCwd, "feature/add-vscode-open-in-support");
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-switched"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-worktree-switched"),
role: "user",
text: "Fix visual bug from screenshot",
attachments: [],
},
approvalPolicy: "on-request",
sandboxMode: "workspace-write",
createdAt: now,
}),
);
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
await Effect.runPromise(Effect.sleep("20 millis"));
expect(harness.renameBranch.mock.calls.length).toBe(0);
});
it("skips worktree rename when branch-name generation fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -330,17 +330,42 @@ const make = Effect.gen(function* () {
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return Effect.void;
return Effect.flatMap(
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
(renamed) =>
orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
}),
);
return Effect.gen(function* () {
const currentBranch = yield* git.statusDetails(cwd).pipe(
Effect.map((status) => status.branch),
Effect.catch((error) =>
Effect.logWarning(
"provider command reactor failed to read active worktree branch",
{
threadId: input.threadId,
cwd,
oldBranch,
targetBranch,
reason: error.message,
},
).pipe(Effect.as(null)),
),
);
if (currentBranch !== oldBranch) {
return yield* Effect.logWarning(
"provider command reactor skipped worktree branch rename because active branch changed",
{
threadId: input.threadId,
cwd,
oldBranch,
targetBranch,
currentBranch,
},
);
}
yield* git.renameBranch({
cwd,
oldBranch,
newBranch: targetBranch,
});
});
}),
Effect.catchCause((cause) =>
Effect.logWarning(
+11 -51
View File
@@ -1,6 +1,6 @@
import type { GitBranch, ThreadId } from "@t3tools/contracts";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useState } from "react";
import { newCommandId } from "../lib/utils";
import {
@@ -14,7 +14,6 @@ import { useStore } from "../store";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
deriveSyncedLocalBranch,
} from "./BranchToolbar.logic";
import { Button } from "./ui/button";
import {
@@ -72,6 +71,11 @@ export default function BranchToolbar({
const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
const resolvedActiveBranch =
effectiveEnvMode === "worktree" && !activeWorktreePath
? activeThreadBranch
: (currentGitBranch ?? activeThreadBranch);
const branchNames = branches.map((branch) => branch.name);
const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
const trimmedBranchQuery = branchQuery.trim();
@@ -92,50 +96,6 @@ export default function BranchToolbar({
gitCreateBranchAndCheckoutMutationOptions({ cwd: branchCwd, queryClient }),
);
// ── Effects ───────────────────────────────────────────────────────────
// Keep thread branch synced to git current branch for local threads.
const queryBranches = branchesQuery.data?.branches;
useEffect(() => {
const syncedBranch = deriveSyncedLocalBranch({
activeThreadId,
activeWorktreePath,
envMode: effectiveEnvMode,
activeThreadBranch,
queryBranches,
});
if (!activeThreadId || !syncedBranch) return;
const api = readNativeApi();
if (api && hasServerThread) {
void api.orchestration.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch: syncedBranch,
worktreePath: null,
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, syncedBranch, null);
return;
}
setDraftThreadContext(threadId, {
branch: syncedBranch,
worktreePath: null,
});
}, [
activeThreadId,
activeWorktreePath,
activeThreadBranch,
queryBranches,
effectiveEnvMode,
setThreadBranchAction,
hasServerThread,
setDraftThreadContext,
threadId,
]);
// ── Helpers ───────────────────────────────────────────────────────────
const setThreadError = (error: string | null) => {
@@ -282,7 +242,7 @@ export default function BranchToolbar({
}
}}
open={isBranchMenuOpen}
value={activeThreadBranch}
value={resolvedActiveBranch}
>
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
@@ -290,10 +250,10 @@ export default function BranchToolbar({
disabled={branchesQuery.isLoading}
>
<span className="max-w-[240px] truncate">
{activeThreadBranch
{resolvedActiveBranch
? effectiveEnvMode === "worktree" && !activeWorktreePath
? `From ${activeThreadBranch}`
: activeThreadBranch
? `From ${resolvedActiveBranch}`
: resolvedActiveBranch
: "Select branch"}
</span>
<ChevronDownIcon />
@@ -347,7 +307,7 @@ export default function BranchToolbar({
key={itemValue}
value={itemValue}
className={
itemValue === activeThreadBranch ? "bg-accent text-foreground" : undefined
itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
}
onClick={() => selectBranch(branch)}
>
+2 -2
View File
@@ -100,7 +100,7 @@ import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./u
import { Separator } from "./ui/separator";
import { Group, GroupSeparator } from "./ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { CursorIcon, Icon } from "./Icons";
import { CursorIcon, Icon, VisualStudioCode } from "./Icons";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -3681,7 +3681,7 @@ const OpenInPicker = memo(function OpenInPicker({
},
{
label: "VS Code",
Icon: FileIcon,
Icon: VisualStudioCode,
value: "vscode",
},
{
+107
View File
@@ -19,3 +19,110 @@ export const CursorIcon: Icon = (props) => (
<path d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z" />
</svg>
);
export const VisualStudioCode: Icon = (props) => (
<svg {...props} fill="none" viewBox="0 0 100 100">
<mask
id="vscode__a"
width="100"
height="100"
x="0"
y="0"
maskUnits="userSpaceOnUse"
>
<path
fill="#fff"
fillRule="evenodd"
d="M70.912 99.317a6.223 6.223 0 0 0 4.96-.19l20.589-9.907A6.25 6.25 0 0 0 100 83.587V16.413a6.25 6.25 0 0 0-3.54-5.632L75.874.874a6.226 6.226 0 0 0-7.104 1.21L29.355 38.04 12.187 25.01a4.162 4.162 0 0 0-5.318.236l-5.506 5.009a4.168 4.168 0 0 0-.004 6.162L16.247 50 1.36 63.583a4.168 4.168 0 0 0 .004 6.162l5.506 5.01a4.162 4.162 0 0 0 5.318.236l17.168-13.032L68.77 97.917a6.217 6.217 0 0 0 2.143 1.4ZM75.015 27.3 45.11 50l29.906 22.701V27.3Z"
clipRule="evenodd"
/>
</mask>
<g mask="url(#vscode__a)">
<path
fill="#0065A9"
d="M96.461 10.796 75.857.876a6.23 6.23 0 0 0-7.107 1.207l-67.451 61.5a4.167 4.167 0 0 0 .004 6.162l5.51 5.009a4.167 4.167 0 0 0 5.32.236l81.228-61.62c2.725-2.067 6.639-.124 6.639 3.297v-.24a6.25 6.25 0 0 0-3.539-5.63Z"
/>
<g filter="url(#vscode__b)">
<path
fill="#007ACC"
d="m96.461 89.204-20.604 9.92a6.229 6.229 0 0 1-7.107-1.207l-67.451-61.5a4.167 4.167 0 0 1 .004-6.162l5.51-5.009a4.167 4.167 0 0 1 5.32-.236l81.228 61.62c2.725 2.067 6.639.124 6.639-3.297v.24a6.25 6.25 0 0 1-3.539 5.63Z"
/>
</g>
<g filter="url(#vscode__c)">
<path
fill="#1F9CF0"
d="M75.858 99.126a6.232 6.232 0 0 1-7.108-1.21c2.306 2.307 6.25.674 6.25-2.588V4.672c0-3.262-3.944-4.895-6.25-2.589a6.232 6.232 0 0 1 7.108-1.21l20.6 9.908A6.25 6.25 0 0 1 100 16.413v67.174a6.25 6.25 0 0 1-3.541 5.633l-20.601 9.906Z"
/>
</g>
<path
fill="url(#vscode__d)"
fillRule="evenodd"
d="M70.851 99.317a6.224 6.224 0 0 0 4.96-.19L96.4 89.22a6.25 6.25 0 0 0 3.54-5.633V16.413a6.25 6.25 0 0 0-3.54-5.632L75.812.874a6.226 6.226 0 0 0-7.104 1.21L29.294 38.04 12.126 25.01a4.162 4.162 0 0 0-5.317.236l-5.507 5.009a4.168 4.168 0 0 0-.004 6.162L16.186 50 1.298 63.583a4.168 4.168 0 0 0 .004 6.162l5.507 5.009a4.162 4.162 0 0 0 5.317.236L29.294 61.96l39.414 35.958a6.218 6.218 0 0 0 2.143 1.4ZM74.954 27.3 45.048 50l29.906 22.701V27.3Z"
clipRule="evenodd"
opacity=".25"
style={{ mixBlendMode: "overlay" }}
/>
</g>
<defs>
<filter
id="vscode__b"
width="116.727"
height="92.246"
x="-8.394"
y="15.829"
colorInterpolationFilters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
<feBlend
in2="BackgroundImageFix"
mode="overlay"
result="effect1_dropShadow"
/>
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
</filter>
<filter
id="vscode__c"
width="47.917"
height="116.151"
x="60.417"
y="-8.076"
colorInterpolationFilters="sRGB"
filterUnits="userSpaceOnUse"
>
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feColorMatrix
in="SourceAlpha"
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
/>
<feOffset />
<feGaussianBlur stdDeviation="4.167" />
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
<feBlend
in2="BackgroundImageFix"
mode="overlay"
result="effect1_dropShadow"
/>
<feBlend in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
</filter>
<linearGradient
id="vscode__d"
x1="49.939"
x2="49.939"
y1=".258"
y2="99.742"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#fff" />
<stop offset="1" stopColor="#fff" stopOpacity="0" />
</linearGradient>
</defs>
</svg>
);