Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchToolbar.tsx

354 lines13.0 KB

1import type { GitBranch, ThreadId } from "@t3tools/contracts";
2import { useQuery, useQueryClient } from "@tanstack/react-query";
3import { useOptimistic, useState, useTransition } from "react";
4​
5import { newCommandId } from "../lib/utils";
6import { gitBranchesQueryOptions, invalidateGitQueries } from "../lib/gitReactQuery";
7import { readNativeApi } from "../nativeApi";
8import { useComposerDraftStore } from "../composerDraftStore";
9import { useStore } from "../store";
10import {
11 dedupeRemoteBranchesWithLocalMatches,
12 deriveLocalBranchNameFromRemoteRef,
13} from "./BranchToolbar.logic";
14import { Button } from "./ui/button";
15import {
16 Combobox,
17 ComboboxEmpty,
18 ComboboxInput,
19 ComboboxItem,
20 ComboboxList,
21 ComboboxPopup,
22 ComboboxTrigger,
23} from "./ui/combobox";
24import { ChevronDownIcon } from "lucide-react";
25import { toastManager } from "./ui/toast";
26​
27interface BranchToolbarProps {
28 threadId: ThreadId;
29 envMode: "local" | "worktree";
30 onEnvModeChange: (mode: "local" | "worktree") => void;
31 envLocked: boolean;
32 onComposerFocusRequest?: () => void;
34​
35export default function BranchToolbar({
36 threadId,
37 envMode,
38 onEnvModeChange,
39 envLocked,
40 onComposerFocusRequest,
41}: BranchToolbarProps) {
42 const threads = useStore((store) => store.threads);
43 const projects = useStore((store) => store.projects);
44 const setThreadBranchAction = useStore((store) => store.setThreadBranch);
45 const setThreadErrorAction = useStore((store) => store.setError);
46 const draftThread = useComposerDraftStore((store) => store.getDraftThread(threadId));
47 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
48 const queryClient = useQueryClient();
49​
50 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
51 const [branchQuery, setBranchQuery] = useState("");
52​
53 const serverThread = threads.find((thread) => thread.id === threadId);
54 const activeProjectId = serverThread?.projectId ?? draftThread?.projectId ?? null;
55 const activeProject = projects.find((project) => project.id === activeProjectId);
56 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
57 const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
58 const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
59 const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null;
60 const hasServerThread = serverThread !== undefined;
61 const effectiveEnvMode: "local" | "worktree" =
62 activeWorktreePath || (!hasServerThread && draftThread?.envMode === "worktree")
63 ? "worktree"
64 : envMode;
65​
66 // ── Queries ───────────────────────────────────────────────────────────
67​
68 const branchesQuery = useQuery(gitBranchesQueryOptions(branchCwd));
69​
70 const branches = dedupeRemoteBranchesWithLocalMatches(branchesQuery.data?.branches ?? []);
71 const currentGitBranch = branches.find((branch) => branch.current)?.name ?? null;
72 const canonicalActiveBranch =
73 effectiveEnvMode === "worktree" && !activeWorktreePath
74 ? activeThreadBranch
75 : (currentGitBranch ?? activeThreadBranch);
76 const branchNames = branches.map((branch) => branch.name);
77 const branchByName = new Map(branches.map((branch) => [branch.name, branch]));
78 const trimmedBranchQuery = branchQuery.trim();
79 const canCreateBranch = effectiveEnvMode === "local" && trimmedBranchQuery.length > 0;
80 const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
81 const createBranchItemValue = canCreateBranch
82 ? `__create_new_branch__:${trimmedBranchQuery}`
83 : null;
84 const branchPickerItems =
85 createBranchItemValue && !hasExactBranchMatch
86 ? [...branchNames, createBranchItemValue]
87 : branchNames;
88​
89 // ── Helpers ───────────────────────────────────────────────────────────
90​
91 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
92 canonicalActiveBranch,
93 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
94 );
95 const [isBranchActionPending, startBranchActionTransition] = useTransition();
96 const runBranchAction = (action: () => Promise<void>) => {
97 startBranchActionTransition(async () => {
98 await action().catch(() => undefined);
99 await invalidateGitQueries(queryClient).catch(() => undefined);
100 });
101 };
102​
103 const setThreadError = (error: string | null) => {
104 if (!activeThreadId) return;
105 setThreadErrorAction(activeThreadId, error);
106 };
107​
108 const setThreadBranch = (branch: string | null, worktreePath: string | null) => {
109 if (!activeThreadId) return;
110 const api = readNativeApi();
111 // If the effective cwd is about to change, stop the running session so the
112 // next message creates a new one with the correct cwd.
113 const sessionId = serverThread?.session?.sessionId;
114 if (sessionId && worktreePath !== activeWorktreePath && api) {
115 void api.orchestration
116 .dispatchCommand({
117 type: "thread.session.stop",
118 commandId: newCommandId(),
119 threadId: activeThreadId,
120 createdAt: new Date().toISOString(),
121 })
122 .catch(() => undefined);
123 }
124 if (api && hasServerThread) {
125 void api.orchestration.dispatchCommand({
126 type: "thread.meta.update",
127 commandId: newCommandId(),
128 threadId: activeThreadId,
129 branch,
130 worktreePath,
131 });
132 }
133 if (hasServerThread) {
134 setThreadBranchAction(activeThreadId, branch, worktreePath);
135 return;
136 }
137 setDraftThreadContext(threadId, {
138 branch,
139 worktreePath,
140 envMode: effectiveEnvMode,
141 });
142 };
143​
144 const selectBranch = (branch: GitBranch) => {
145 const api = readNativeApi();
146 if (!api || !activeThreadId || !branchCwd || isBranchActionPending) return;
147​
148 // For new worktree mode, selecting a branch picks the base branch.
149 if (effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath) {
150 setThreadBranch(branch.name, null);
151 setIsBranchMenuOpen(false);
152 onComposerFocusRequest?.();
153 return;
154 }
155​
156 // If the branch already lives in a worktree, redirect there instead of
157 // trying to checkout (which git would reject with "already used by worktree").
158 if (branch.worktreePath) {
159 const isMainWorktree = branch.worktreePath === activeProject?.cwd;
160 // Main worktree → switch back to local (project cwd, worktreePath=null).
161 // Secondary worktree → point the thread at that worktree path.
162 setThreadBranch(branch.name, isMainWorktree ? null : branch.worktreePath);
163 setIsBranchMenuOpen(false);
164 onComposerFocusRequest?.();
165 return;
166 }
167​
168 const selectedBranchName = branch.isRemote
169 ? deriveLocalBranchNameFromRemoteRef(branch.name)
170 : branch.name;
171​
172 setIsBranchMenuOpen(false);
173 onComposerFocusRequest?.();
174​
175 runBranchAction(async () => {
176 setOptimisticBranch(selectedBranchName);
177 try {
178 await api.git.checkout({ cwd: branchCwd, branch: branch.name });
179 await invalidateGitQueries(queryClient);
180 } catch (error) {
181 toastManager.add({
182 type: "error",
183 title: "Failed to checkout branch.",
184 description: error instanceof Error ? error.message : "An error occurred.",
185 });
186 return;
187 }
188​
189 let nextBranchName = selectedBranchName;
190 if (branch.isRemote) {
191 const status = await api.git.status({ cwd: branchCwd }).catch(() => null);
192 if (status?.branch) {
193 nextBranchName = status.branch;
194 }
195 }
196​
197 setOptimisticBranch(nextBranchName);
198 setThreadBranch(nextBranchName, activeWorktreePath);
199 });
200 };
201​
202 const createBranch = (rawName: string) => {
203 const name = rawName.trim();
204 const api = readNativeApi();
205 if (!api || !activeThreadId || !branchCwd || !name || isBranchActionPending) return;
206​
207 setIsBranchMenuOpen(false);
208 onComposerFocusRequest?.();
209​
210 runBranchAction(async () => {
211 setOptimisticBranch(name);
212​
213 try {
214 await api.git.createBranch({ cwd: branchCwd, branch: name });
215 try {
216 await api.git.checkout({ cwd: branchCwd, branch: name });
217 } catch (error) {
218 toastManager.add({
219 type: "error",
220 title: "Failed to checkout branch.",
221 description: error instanceof Error ? error.message : "An error occurred.",
222 });
223 return;
224 }
225 } catch (error) {
226 toastManager.add({
227 type: "error",
228 title: "Failed to create branch.",
229 description: error instanceof Error ? error.message : "An error occurred.",
230 });
231 return;
232 }
233​
234 setOptimisticBranch(name);
235 setThreadBranch(name, activeWorktreePath);
236 setBranchQuery("");
237 });
238 };
239​
240 if (!activeThreadId || !activeProject) return null;
241​
242 return (
243 <div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
244 <div className="flex items-center gap-2">
245 {envLocked || activeWorktreePath ? (
246 <span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
247 {activeWorktreePath ? "Worktree" : "Local"}
248 </span>
249 ) : (
250 <Button
251 type="button"
252 variant="ghost"
253 className="text-muted-foreground/70 hover:text-foreground/80"
254 size="xs"
255 onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
256 >
257 {effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
258 </Button>
259 )}
260 </div>
261​
262 <Combobox
263 items={branchPickerItems}
264 autoHighlight
265 onOpenChange={(open) => {
266 setIsBranchMenuOpen(open);
267 if (!open) setBranchQuery("");
268 else void invalidateGitQueries(queryClient);
269 }}
270 open={isBranchMenuOpen}
271 value={resolvedActiveBranch}
272 >
273 <ComboboxTrigger
274 render={<Button variant="ghost" size="xs" />}
275 className="text-muted-foreground/70 hover:text-foreground/80"
276 disabled={branchesQuery.isLoading || isBranchActionPending}
277 >
278 <span className="max-w-[240px] truncate">
279 {resolvedActiveBranch
280 ? effectiveEnvMode === "worktree" && !activeWorktreePath
281 ? `From ${resolvedActiveBranch}`
282 : resolvedActiveBranch
283 : "Select branch"}
284 </span>
285 <ChevronDownIcon />
286 </ComboboxTrigger>
287 <ComboboxPopup align="end" side="top" className="w-64">
288 <div className="border-b p-1">
289 <ComboboxInput
290 className="[&_input]:font-sans rounded-md"
291 inputClassName="ring-0"
292 placeholder="Search branches..."
293 showTrigger={false}
294 size="sm"
295 value={branchQuery}
296 onChange={(event) => setBranchQuery(event.target.value)}
297 />
298 </div>
299 <ComboboxEmpty>No branches found.</ComboboxEmpty>
300​
301 <ComboboxList className="max-h-56">
302 {(itemValue) => {
303 if (createBranchItemValue && itemValue === createBranchItemValue) {
304 return (
305 <ComboboxItem
306 hideIndicator
307 key={itemValue}
308 value={itemValue}
309 onClick={() => createBranch(trimmedBranchQuery)}
310 >
311 <span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
312 </ComboboxItem>
313 );
314 }
315​
316 const branch = branchByName.get(itemValue);
317 if (!branch) return null;
318​
319 const hasSecondaryWorktree =
320 branch.worktreePath && branch.worktreePath !== activeProject.cwd;
321 const badge = branch.current
322 ? "current"
323 : hasSecondaryWorktree
324 ? "worktree"
325 : branch.isRemote
326 ? "remote"
327 : branch.isDefault
328 ? "default"
329 : null;
330 return (
331 <ComboboxItem
332 hideIndicator
333 key={itemValue}
334 value={itemValue}
335 className={
336 itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined
337 }
338 onClick={() => selectBranch(branch)}
339 >
340 <div className="flex w-full items-center justify-between gap-2">
341 <span className="truncate">{itemValue}</span>
342 {badge && (
343 <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>
344 )}
345 </div>
346 </ComboboxItem>
347 );
348 }}
349 </ComboboxList>
350 </ComboboxPopup>
351 </Combobox>
352 </div>
353 );