Open History to see the last commit
1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
2import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
3import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
4import { LegendList, type LegendListRef } from "@legendapp/list/react";
5import { ChevronDownIcon } from "lucide-react";
6import {
7 useCallback,
8 useDeferredValue,
9 useEffect,
10 useMemo,
11 useOptimistic,
12 useRef,
13 useState,
14 useTransition,
15} from "react";
16
17import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
18import { readEnvironmentApi } from "../environmentApi";
19import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery";
20import { useGitStatus } from "../lib/gitStatusState";
21import { newCommandId } from "../lib/utils";
22import { parsePullRequestReference } from "../pullRequestReference";
23import { useStore } from "../store";
24import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
25import {
26 deriveLocalBranchNameFromRemoteRef,
27 resolveBranchSelectionTarget,
28 resolveBranchToolbarValue,
29 resolveDraftEnvModeAfterBranchChange,
30 resolveEffectiveEnvMode,
31 shouldIncludeBranchPickerItem,
32} from "./BranchToolbar.logic";
33import { Button } from "./ui/button";
34import {
35 Combobox,
36 ComboboxEmpty,
37 ComboboxInput,
38 ComboboxItem,
39 ComboboxList,
40 ComboboxListVirtualized,
41 ComboboxPopup,
42 ComboboxStatus,
43 ComboboxTrigger,
44} from "./ui/combobox";
45import { toastManager } from "./ui/toast";
46
47interface BranchToolbarBranchSelectorProps {
48 environmentId: EnvironmentId;
49 threadId: ThreadId;
50 draftId?: DraftId;
51 envLocked: boolean;
52 onCheckoutPullRequestRequest?: (reference: string) => void;
53 onComposerFocusRequest?: () => void;
54}
55
56function toBranchActionErrorMessage(error: unknown): string {
57 return error instanceof Error ? error.message : "An error occurred.";
58}
59
60function getBranchTriggerLabel(input: {
61 activeWorktreePath: string | null;
62 effectiveEnvMode: "local" | "worktree";
63 resolvedActiveBranch: string | null;
64}): string {
65 const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
66 if (!resolvedActiveBranch) {
67 return "Select branch";
68 }
69 if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
70 return `From ${resolvedActiveBranch}`;
71 }
72 return resolvedActiveBranch;
73}
74
75export function BranchToolbarBranchSelector({
76 environmentId,
77 threadId,
78 draftId,
79 envLocked,
80 onCheckoutPullRequestRequest,
81 onComposerFocusRequest,
82}: BranchToolbarBranchSelectorProps) {
83 // ---------------------------------------------------------------------------
84 // Thread / project state (pushed down from parent to colocate with mutation)
85 // ---------------------------------------------------------------------------
86 const threadRef = useMemo(
87 () => scopeThreadRef(environmentId, threadId),
88 [environmentId, threadId],
89 );
90 const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]);
91 const serverThread = useStore(serverThreadSelector);
92 const serverSession = serverThread?.session ?? null;
93 const setThreadBranchAction = useStore((store) => store.setThreadBranch);
94 const draftThread = useComposerDraftStore((store) =>
95 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
96 );
97 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
98
99 const activeProjectRef = serverThread
100 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
101 : draftThread
102 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
103 : null;
104 const activeProjectSelector = useMemo(
105 () => createProjectSelectorByRef(activeProjectRef),
106 [activeProjectRef],
107 );
108 const activeProject = useStore(activeProjectSelector);
109
110 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
111 const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null;
112 const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
113 const activeProjectCwd = activeProject?.cwd ?? null;
114 const branchCwd = activeWorktreePath ?? activeProjectCwd;
115 const hasServerThread = serverThread !== undefined;
116 const effectiveEnvMode = resolveEffectiveEnvMode({
117 activeWorktreePath,
118 hasServerThread,
119 draftThreadEnvMode: draftThread?.envMode,
120 });
121
122 // ---------------------------------------------------------------------------
123 // Thread branch mutation (colocated — only this component calls it)
124 // ---------------------------------------------------------------------------
125 const setThreadBranch = useCallback(
126 (branch: string | null, worktreePath: string | null) => {
127 if (!activeThreadId || !activeProject) return;
128 const api = readEnvironmentApi(environmentId);
129 if (serverSession && worktreePath !== activeWorktreePath && api) {
130 void api.orchestration
131 .dispatchCommand({
132 type: "thread.session.stop",
133 commandId: newCommandId(),
134 threadId: activeThreadId,
135 createdAt: new Date().toISOString(),
136 })
137 .catch(() => undefined);
138 }
139 if (api && hasServerThread) {
140 void api.orchestration.dispatchCommand({
141 type: "thread.meta.update",
142 commandId: newCommandId(),
143 threadId: activeThreadId,
144 branch,
145 worktreePath,
146 });
147 }
148 if (hasServerThread) {
149 setThreadBranchAction(threadRef, branch, worktreePath);
150 return;
151 }
152 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
153 nextWorktreePath: worktreePath,
154 currentWorktreePath: activeWorktreePath,
155 effectiveEnvMode,
156 });
157 setDraftThreadContext(draftId ?? threadRef, {
158 branch,
159 worktreePath,
160 envMode: nextDraftEnvMode,
161 projectRef: scopeProjectRef(environmentId, activeProject.id),
162 });
163 },
164 [
165 activeThreadId,
166 activeProject,
167 serverSession,
168 activeWorktreePath,
169 hasServerThread,
170 setThreadBranchAction,
171 setDraftThreadContext,
172 draftId,
173 threadRef,
174 environmentId,
175 effectiveEnvMode,
176 ],
177 );
178
179 // ---------------------------------------------------------------------------
180 // Git branch queries
181 // ---------------------------------------------------------------------------
182 const queryClient = useQueryClient();
183 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
184 const [branchQuery, setBranchQuery] = useState("");
185 const deferredBranchQuery = useDeferredValue(branchQuery);
186
187 const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
188 const trimmedBranchQuery = branchQuery.trim();
189 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
190
191 useEffect(() => {
192 if (!branchCwd) return;
193 void queryClient.prefetchInfiniteQuery(
194 gitBranchSearchInfiniteQueryOptions({ environmentId, cwd: branchCwd, query: "" }),
195 );
196 }, [branchCwd, environmentId, queryClient]);
197
198 const {
199 data: branchesSearchData,
200 fetchNextPage,
201 hasNextPage,
202 isFetchingNextPage,
203 isPending: isBranchesSearchPending,
204 } = useInfiniteQuery(
205 gitBranchSearchInfiniteQueryOptions({
206 environmentId,
207 cwd: branchCwd,
208 query: deferredTrimmedBranchQuery,
209 }),
210 );
211 const branches = useMemo(
212 () => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
213 [branchesSearchData?.pages],
214 );
215 const currentGitBranch =
216 branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
217 const canonicalActiveBranch = resolveBranchToolbarValue({
218 envMode: effectiveEnvMode,
219 activeWorktreePath,
220 activeThreadBranch,
221 currentGitBranch,
222 });
223 const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
224 const branchByName = useMemo(
225 () => new Map(branches.map((branch) => [branch.name, branch] as const)),
226 [branches],
227 );
228 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
229 const prReference = parsePullRequestReference(trimmedBranchQuery);
230 const isSelectingWorktreeBase =
231 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
232 const checkoutPullRequestItemValue =
233 prReference && onCheckoutPullRequestRequest ? `__checkout_pull_request__:${prReference}` : null;
234 const canCreateBranch = !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
235 const hasExactBranchMatch = branchByName.has(trimmedBranchQuery);
236 const createBranchItemValue = canCreateBranch
237 ? `__create_new_branch__:${trimmedBranchQuery}`
238 : null;
239 const branchPickerItems = useMemo(() => {
240 const items = [...branchNames];
241 if (createBranchItemValue && !hasExactBranchMatch) {
242 items.push(createBranchItemValue);
243 }
244 if (checkoutPullRequestItemValue) {
245 items.unshift(checkoutPullRequestItemValue);
246 }
247 return items;
248 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
249 const filteredBranchPickerItems = useMemo(
250 () =>
251 normalizedDeferredBranchQuery.length === 0
252 ? branchPickerItems
253 : branchPickerItems.filter((itemValue) =>
254 shouldIncludeBranchPickerItem({
255 itemValue,
256 normalizedQuery: normalizedDeferredBranchQuery,
257 createBranchItemValue,
258 checkoutPullRequestItemValue,
259 }),
260 ),
261 [
262 branchPickerItems,
263 checkoutPullRequestItemValue,
264 createBranchItemValue,
265 normalizedDeferredBranchQuery,
266 ],
267 );
268 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
269 canonicalActiveBranch,
270 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
271 );
272 const [isBranchActionPending, startBranchActionTransition] = useTransition();
273 const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
274 const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
275 const branchStatusText = isBranchesSearchPending
276 ? "Loading branches..."
277 : isFetchingNextPage
278 ? "Loading more branches..."
279 : hasNextPage
280 ? `Showing ${branches.length} of ${totalBranchCount} branches`
281 : null;
282
283 // ---------------------------------------------------------------------------
284 // Branch actions
285 // ---------------------------------------------------------------------------
286 const runBranchAction = (action: () => Promise<void>) => {
287 startBranchActionTransition(async () => {
288 await action().catch(() => undefined);
289 await queryClient
290 .invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) })
291 .catch(() => undefined);
292 });
293 };
294
295 const selectBranch = (branch: GitBranch) => {
296 const api = readEnvironmentApi(environmentId);
297 if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
298
299 if (isSelectingWorktreeBase) {
300 setThreadBranch(branch.name, null);
301 setIsBranchMenuOpen(false);
302 onComposerFocusRequest?.();
303 return;
304 }
305
306 const selectionTarget = resolveBranchSelectionTarget({
307 activeProjectCwd,
308 activeWorktreePath,
309 branch,
310 });
311
312 if (selectionTarget.reuseExistingWorktree) {
313 setThreadBranch(branch.name, selectionTarget.nextWorktreePath);
314 setIsBranchMenuOpen(false);
315 onComposerFocusRequest?.();
316 return;
317 }
318
319 const selectedBranchName = branch.isRemote
320 ? deriveLocalBranchNameFromRemoteRef(branch.name)
321 : branch.name;
322
323 setIsBranchMenuOpen(false);
324 onComposerFocusRequest?.();
325
326 runBranchAction(async () => {
327 const previousBranch = resolvedActiveBranch;
328 setOptimisticBranch(selectedBranchName);
329 try {
330 const checkoutResult = await api.git.checkout({
331 cwd: selectionTarget.checkoutCwd,
332 branch: branch.name,
333 });
334 const nextBranchName = branch.isRemote
335 ? (checkoutResult.branch ?? selectedBranchName)
336 : selectedBranchName;
337 setOptimisticBranch(nextBranchName);
338 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
339 } catch (error) {
340 setOptimisticBranch(previousBranch);
341 toastManager.add({
342 type: "error",
343 title: "Failed to checkout branch.",
344 description: toBranchActionErrorMessage(error),
345 });
346 }
347 });
348 };
349
350 const createBranch = (rawName: string) => {
351 const name = rawName.trim();
352 const api = readEnvironmentApi(environmentId);
353 if (!api || !branchCwd || !name || isBranchActionPending) return;
354
355 setIsBranchMenuOpen(false);
356 onComposerFocusRequest?.();
357
358 runBranchAction(async () => {
359 const previousBranch = resolvedActiveBranch;
360 setOptimisticBranch(name);
361 try {
362 const createBranchResult = await api.git.createBranch({
363 cwd: branchCwd,
364 branch: name,
365 checkout: true,
366 });
367 setOptimisticBranch(createBranchResult.branch);
368 setThreadBranch(createBranchResult.branch, activeWorktreePath);
369 } catch (error) {
370 setOptimisticBranch(previousBranch);
371 toastManager.add({
372 type: "error",
373 title: "Failed to create and checkout branch.",
374 description: toBranchActionErrorMessage(error),
375 });
376 }
377 });
378 };
379
380 useEffect(() => {
381 if (
382 effectiveEnvMode !== "worktree" ||
383 activeWorktreePath ||
384 activeThreadBranch ||
385 !currentGitBranch
386 ) {
387 return;
388 }
389 setThreadBranch(currentGitBranch, null);
390 }, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
391
392 // ---------------------------------------------------------------------------
393 // Combobox / list plumbing
394 // ---------------------------------------------------------------------------
395 const handleOpenChange = useCallback(
396 (open: boolean) => {
397 setIsBranchMenuOpen(open);
398 if (!open) {
399 setBranchQuery("");
400 return;
401 }
402 void queryClient.invalidateQueries({
403 queryKey: gitQueryKeys.branches(environmentId, branchCwd),
404 });
405 },
406 [branchCwd, environmentId, queryClient],
407 );
408
409 const branchListScrollElementRef = useRef<HTMLDivElement | null>(null);
410 const maybeFetchNextBranchPage = useCallback(() => {
411 if (!isBranchMenuOpen || !hasNextPage || isFetchingNextPage) {
412 return;
413 }
414
415 const scrollElement = branchListScrollElementRef.current;
416 if (!scrollElement) {
417 return;
418 }
419
420 const distanceFromBottom =
421 scrollElement.scrollHeight - scrollElement.scrollTop - scrollElement.clientHeight;
422 if (distanceFromBottom > 96) {
423 return;
424 }
425
426 void fetchNextPage().catch(() => undefined);
427 }, [fetchNextPage, hasNextPage, isBranchMenuOpen, isFetchingNextPage]);
428 const branchListRef = useRef<LegendListRef | null>(null);
429 const setBranchListRef = useCallback((element: HTMLDivElement | null) => {
430 branchListScrollElementRef.current = (element?.parentElement as HTMLDivElement | null) ?? null;
431 }, []);
432
433 useEffect(() => {
434 if (!isBranchMenuOpen) {
435 return;
436 }
437
438 if (shouldVirtualizeBranchList) {
439 branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
440 } else {
441 branchListScrollElementRef.current?.scrollTo({ top: 0 });
442 }
443 }, [deferredTrimmedBranchQuery, isBranchMenuOpen, shouldVirtualizeBranchList]);
444
445 useEffect(() => {
446 const scrollElement = branchListScrollElementRef.current;
447 if (!scrollElement || !isBranchMenuOpen) {
448 return;
449 }
450
451 const handleScroll = () => {
452 maybeFetchNextBranchPage();
453 };
454
455 scrollElement.addEventListener("scroll", handleScroll, { passive: true });
456 handleScroll();
457 return () => {
458 scrollElement.removeEventListener("scroll", handleScroll);
459 };
460 }, [isBranchMenuOpen, maybeFetchNextBranchPage]);
461
462 useEffect(() => {
463 if (shouldVirtualizeBranchList) return;
464 maybeFetchNextBranchPage();
465 }, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
466
467 const triggerLabel = getBranchTriggerLabel({
468 activeWorktreePath,
469 effectiveEnvMode,
470 resolvedActiveBranch,
471 });
472
473 function renderPickerItem(itemValue: string, index: number) {
474 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
475 return (
476 <ComboboxItem
477 hideIndicator
478 key={itemValue}
479 index={index}
480 value={itemValue}
481 onClick={() => {
482 if (!prReference || !onCheckoutPullRequestRequest) {
483 return;
484 }
485 setIsBranchMenuOpen(false);
486 setBranchQuery("");
487 onComposerFocusRequest?.();
488 onCheckoutPullRequestRequest(prReference);
489 }}
490 >
491 <div className="flex min-w-0 flex-col items-start py-1">
492 <span className="truncate font-medium">Checkout Pull Request</span>
493 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
494 </div>
495 </ComboboxItem>
496 );
497 }
498 if (createBranchItemValue && itemValue === createBranchItemValue) {
499 return (
500 <ComboboxItem
501 hideIndicator
502 key={itemValue}
503 index={index}
504 value={itemValue}
505 onClick={() => createBranch(trimmedBranchQuery)}
506 >
507 <span className="truncate">Create new branch "{trimmedBranchQuery}"</span>
508 </ComboboxItem>
509 );
510 }
511
512 const branch = branchByName.get(itemValue);
513 if (!branch) return null;
514
515 const hasSecondaryWorktree =
516 branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd;
517 const badge = branch.current
518 ? "current"
519 : hasSecondaryWorktree
520 ? "worktree"
521 : branch.isRemote
522 ? "remote"
523 : branch.isDefault
524 ? "default"
525 : null;
526 return (
527 <ComboboxItem
528 hideIndicator
529 key={itemValue}
530 index={index}
531 value={itemValue}
532 onClick={() => selectBranch(branch)}
533 >
534 <div className="flex w-full items-center justify-between gap-2">
535 <span className="truncate">{itemValue}</span>
536 {badge && <span className="shrink-0 text-[10px] text-muted-foreground/45">{badge}</span>}
537 </div>
538 </ComboboxItem>
539 );
540 }
541
542 return (
543 <Combobox
544 items={branchPickerItems}
545 filteredItems={filteredBranchPickerItems}
546 autoHighlight
547 virtualized={shouldVirtualizeBranchList}
548 onItemHighlighted={(_value, eventDetails) => {
549 if (!isBranchMenuOpen || eventDetails.index < 0 || eventDetails.reason !== "keyboard") {
550 return;
551 }
552 branchListRef.current?.scrollIndexIntoView?.({
553 index: eventDetails.index,
554 animated: false,
555 });
556 }}
557 onOpenChange={handleOpenChange}
558 open={isBranchMenuOpen}
559 value={resolvedActiveBranch}
560 >
561 <ComboboxTrigger
562 render={<Button variant="ghost" size="xs" />}
563 className="text-muted-foreground/70 hover:text-foreground/80"
564 disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
565 >
566 <span className="max-w-[240px] truncate">{triggerLabel}</span>
567 <ChevronDownIcon />
568 </ComboboxTrigger>
569 <ComboboxPopup align="end" side="top" className="w-80">
570 <div className="border-b p-1">
571 <ComboboxInput
572 className="[&_input]:font-sans rounded-md"
573 inputClassName="ring-0"
574 placeholder="Search branches..."
575 showTrigger={false}
576 size="sm"
577 value={branchQuery}
578 onChange={(event) => setBranchQuery(event.target.value)}
579 />
580 </div>
581 <ComboboxEmpty>No branches found.</ComboboxEmpty>
582
583 {shouldVirtualizeBranchList ? (
584 <ComboboxListVirtualized>
585 <LegendList<string>
586 ref={branchListRef}
587 data={filteredBranchPickerItems}
588 keyExtractor={(item) => item}
589 renderItem={({ item, index }) => renderPickerItem(item, index)}
590 estimatedItemSize={28}
591 drawDistance={336}
592 onEndReached={() => {
593 if (hasNextPage && !isFetchingNextPage) {
594 void fetchNextPage().catch(() => undefined);
595 }
596 }}
597 style={{ maxHeight: "14rem" }}
598 />
599 </ComboboxListVirtualized>
600 ) : (
601 <ComboboxList ref={setBranchListRef} className="max-h-56">
602 {filteredBranchPickerItems.map((itemValue, index) =>
603 renderPickerItem(itemValue, index),
604 )}
605 </ComboboxList>
606 )}
607 {branchStatusText ? <ComboboxStatus>{branchStatusText}</ComboboxStatus> : null}
608 </ComboboxPopup>
609 </Combobox>
610 );
611}