Open History to see the last commit
1import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2import { ComposerContextLabel } from "./ComposerContextLabel";
3import { useRightPanelStore } from "../rightPanelStore";
4import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
5import {
6 isAtomCommandInterrupted,
7 squashAtomCommandFailure,
8} from "@t3tools/client-runtime/state/runtime";
9import {
10 AuthOrchestrationOperateScope,
11 AuthSourceControlWriteScope,
12 type ContextMenuItem,
13 type EnvironmentId,
14 type VcsRef,
15 type ThreadId,
16} from "@t3tools/contracts";
17import { GitBranchIcon } from "lucide-react";
18import {
19 useEffect,
20 useImperativeHandle,
21 useOptimistic,
22 useState,
23 useTransition,
24 type MouseEvent as ReactMouseEvent,
25 type Ref,
26} from "react";
27
28import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
29import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
30import { readLocalApi } from "../localApi";
31import { useOpenPrLink } from "../lib/openPullRequestLink";
32import { usePaginatedBranches } from "../state/queries";
33import { readThreadShell, useProject, useQuietThreadShell } from "../state/entities";
34import { useEnvironmentQuery } from "../state/query";
35import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
36import { threadEnvironment } from "../state/threads";
37import { useAtomCommand } from "../state/use-atom-command";
38import { vcsEnvironment } from "../state/vcs";
39import { cn } from "../lib/utils";
40import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./chat/threadDetailsPanelStyles";
41import { ThreadDetailsThreadPrRows } from "./chat/ThreadDetailsPrRows";
42import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input";
43import { getSourceControlPresentation } from "../sourceControlPresentation";
44import { useComposerMenuProps } from "./chat/composerEventScope";
45import {
46 deriveLocalBranchNameFromRemoteRef,
47 isWorktreeChangeBlocked,
48 resolveBranchTriggerLabel,
49 resolveBranchToolbarPrBranch,
50 resolveBranchSelectionTarget,
51 resolveBranchToolbarValue,
52 resolveDraftEnvModeAfterBranchChange,
53 resolveEffectiveEnvMode,
54 sanitizeNewRefName,
55 shouldIncludeBranchPickerItem,
56} from "./BranchToolbar.logic";
57import {
58 ThreadPullRequestBadgeControl,
59 resolveDisplayedThreadPr,
60 useThreadDisplayedPullRequest,
61} from "./ThreadStatusIndicators";
62
63import { ComboboxItem, ComboboxTrigger } from "./ui/combobox";
64import { ComposerControl } from "./chat/ComposerControl";
65import { MiddleTruncate } from "./ui/middle-truncate";
66import { BranchPicker, BranchPickerRefItem } from "./BranchPicker";
67import { stackedThreadToast, toastManager } from "./ui/toast";
68
69export interface BranchToolbarBranchSelectorHandle {
70 open: () => void;
71}
72
73interface BranchToolbarBranchSelectorProps {
74 forceNewWorktree?: boolean;
75 ref?: Ref<BranchToolbarBranchSelectorHandle>;
76 className?: string;
77 displayMode?: "toolbar" | "panel";
78 environmentId: EnvironmentId;
79 threadId: ThreadId;
80 draftId?: DraftId;
81 envLocked: boolean;
82 effectiveEnvModeOverride?: "local" | "worktree";
83 activeThreadBranchOverride?: string | null;
84 onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
85 startFromOrigin: boolean;
86 onStartFromOriginChange: (startFromOrigin: boolean) => void;
87 onCheckoutPullRequestRequest?: (reference: string) => void;
88 onComposerFocusRequest?: () => void;
89}
90
91const WORKTREE_CHANGE_BLOCKED_MESSAGE = "Stop the current turn to switch worktrees.";
92
93function toBranchActionErrorMessage(error: unknown): string {
94 return error instanceof Error ? error.message : "An error occurred.";
95}
96
97export function BranchToolbarBranchSelector({
98 forceNewWorktree = false,
99 ref,
100 className,
101 displayMode = "toolbar",
102 environmentId,
103 threadId,
104 draftId,
105 envLocked,
106 effectiveEnvModeOverride,
107 activeThreadBranchOverride,
108 onActiveThreadBranchOverrideChange,
109 startFromOrigin,
110 onStartFromOriginChange,
111 onCheckoutPullRequestRequest,
112 onComposerFocusRequest,
113}: BranchToolbarBranchSelectorProps) {
114 const composerFloatingLayerProps = useComposerMenuProps();
115 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
116 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
117 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
118 const updateThreadMetadata = useAtomCommand(
119 threadEnvironment.updateMetadata,
120 "thread metadata update",
121 );
122 const updateEmptyThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
123 reportFailure: false,
124 });
125 const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
126 reportFailure: false,
127 });
128 const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, {
129 reportFailure: false,
130 });
131 const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
132 reportFailure: false,
133 });
134 const threadRef = scopeThreadRef(environmentId, threadId);
135 const serverThread = useQuietThreadShell(threadRef);
136 const serverSession = serverThread?.runtime ?? null;
137 const draftThread = useComposerDraftStore((store) =>
138 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
139 );
140 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
141
142 const activeProjectRef = serverThread
143 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
144 : draftThread
145 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
146 : null;
147 const activeProject = useProject(activeProjectRef);
148
149 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
150 const activeThreadBranch =
151 activeThreadBranchOverride !== undefined
152 ? activeThreadBranchOverride
153 : (serverThread?.branch ?? draftThread?.branch ?? null);
154 const activeWorktreePath = forceNewWorktree
155 ? null
156 : serverThread
157 ? serverThread.worktreePath
158 : (draftThread?.worktreePath ?? null);
159 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
160 const branchCwd = activeWorktreePath ?? activeProjectCwd;
161 const hasServerThread = serverThread !== null;
162 const canUpdateThreadBranch = !hasServerThread || canOperateThread;
163 const canChangeThreadBranch = canWriteSourceControl && canUpdateThreadBranch;
164 const effectiveEnvMode =
165 effectiveEnvModeOverride ??
166 resolveEffectiveEnvMode({
167 activeWorktreePath,
168 hasServerThread,
169 draftThreadEnvMode: draftThread?.envMode,
170 });
171
172 const readLatestThreadState = () =>
173 readThreadShell(threadRef) ??
174 serverThread ?? { runtime: null, worktreePath: activeWorktreePath };
175
176 const setThreadBranch = (
177 branch: string | null,
178 worktreePath: string | null,
179 automatic = false,
180 ) => {
181 if (
182 !activeThreadId ||
183 !activeProject ||
184 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
185 )
186 return false;
187 const latest = readLatestThreadState();
188 if (automatic && (latest.runtime || latest.worktreePath)) return false;
189 if (
190 isWorktreeChangeBlocked({
191 runtime: latest.runtime,
192 currentWorktreePath: latest.worktreePath,
193 nextWorktreePath: worktreePath,
194 })
195 ) {
196 toastManager.add(
197 stackedThreadToast({ type: "warning", title: WORKTREE_CHANGE_BLOCKED_MESSAGE }),
198 );
199 return false;
200 }
201 if (latest.runtime && worktreePath !== latest.worktreePath) {
202 void stopThreadSession({
203 environmentId,
204 input: { threadId: activeThreadId },
205 });
206 }
207 if (hasServerThread) {
208 void (automatic ? updateEmptyThreadMetadata : updateThreadMetadata)({
209 environmentId,
210 input: {
211 threadId: activeThreadId,
212 branch,
213 worktreePath,
214 ...(automatic ? { expectedEmpty: true } : {}),
215 },
216 });
217 }
218 if (hasServerThread) {
219 onActiveThreadBranchOverrideChange?.(branch);
220 return true;
221 }
222 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
223 nextWorktreePath: worktreePath,
224 currentWorktreePath: activeWorktreePath,
225 effectiveEnvMode,
226 });
227 setDraftThreadContext(draftId ?? threadRef, {
228 branch,
229 worktreePath,
230 envMode: nextDraftEnvMode,
231 environmentSelection: automatic ? (draftThread?.environmentSelection ?? "auto") : "manual",
232 projectRef: scopeProjectRef(environmentId, activeProject.id),
233 });
234 return true;
235 };
236
237 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
238 const [branchQuery, setBranchQuery] = useState("");
239
240 const branchStatusQuery = useEnvironmentQuery(
241 branchCwd === null
242 ? null
243 : vcsEnvironment.status({
244 environmentId,
245 input: { cwd: branchCwd },
246 }),
247 );
248 const projectStatusQuery = useEnvironmentQuery(
249 activeProjectCwd === null
250 ? null
251 : vcsEnvironment.status({ environmentId, input: { cwd: activeProjectCwd } }),
252 );
253 const activeProjectCheckoutRoot = projectStatusQuery.data?.workingTree.rootPath;
254 const trimmedBranchQuery = branchQuery.trim();
255 const branchRefState = usePaginatedBranches({
256 environmentId,
257 cwd: branchCwd,
258 // Substring search needs sanitized names to detect new-branch collisions; refs cannot contain ASCII
259 // spaces.
260 query: sanitizeNewRefName(trimmedBranchQuery),
261 });
262 const refs = branchRefState.refs;
263 const branchByName = new Map(refs.map((refName) => [refName.name, refName] as const));
264 const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
265 const prReference = parsePullRequestReference(trimmedBranchQuery);
266 const isSelectingWorktreeBase =
267 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
268 const isWorktreeChangeBlockedForRef = (refName: VcsRef) =>
269 activeProjectCwd !== null &&
270 isWorktreeChangeBlocked({
271 runtime: serverSession,
272 currentWorktreePath: serverThread ? serverThread.worktreePath : activeWorktreePath,
273 nextWorktreePath: isSelectingWorktreeBase
274 ? null
275 : resolveBranchSelectionTarget({
276 activeProjectCwd,
277 activeProjectCheckoutRoot,
278 activeWorktreePath,
279 refName,
280 }).nextWorktreePath,
281 });
282 const checkoutPullRequestItemValue =
283 canChangeThreadBranch && prReference && onCheckoutPullRequestRequest
284 ? `__checkout_pull_request__:${prReference}`
285 : null;
286 const canCreateBranch =
287 canChangeThreadBranch && !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
288 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
289 const hasExactBranchMatch = branchByName.has(newRefName);
290 const createBranchItemValue = canCreateBranch
291 ? `__create_new_branch__:${trimmedBranchQuery}`
292 : null;
293 const defaultBranchName = refs.find((refName) => refName.isDefault)?.name ?? null;
294 const pickerCreateBranchItemValue = hasExactBranchMatch ? null : createBranchItemValue;
295 const branchPickerItems = [
296 ...(checkoutPullRequestItemValue ? [checkoutPullRequestItemValue] : []),
297 ...refs.map((refName) => refName.name),
298 ...(pickerCreateBranchItemValue ? [pickerCreateBranchItemValue] : []),
299 ];
300 const filteredBranchPickerItems =
301 normalizedBranchQuery.length === 0
302 ? branchPickerItems
303 : branchPickerItems.filter((itemValue) =>
304 shouldIncludeBranchPickerItem({
305 itemValue,
306 normalizedQuery: normalizedBranchQuery,
307 createBranchItemValue: pickerCreateBranchItemValue,
308 checkoutPullRequestItemValue,
309 }),
310 );
311 const hasNextPage =
312 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
313 const isFetchingNextPage = branchRefState.isFetchingNextPage;
314 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
315 const currentGitBranch =
316 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
317 const sourceControlPresentation = getSourceControlPresentation(
318 branchStatusQuery.data?.sourceControlProvider,
319 );
320 const SourceControlIcon = sourceControlPresentation.Icon;
321 const canonicalActiveBranch = resolveBranchToolbarValue({
322 envMode: effectiveEnvMode,
323 activeWorktreePath,
324 activeThreadBranch,
325 currentGitBranch,
326 });
327 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
328 canonicalActiveBranch,
329 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
330 );
331 const listedActiveBranch =
332 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
333 const activeBranchRefQuery = useEnvironmentQuery(
334 branchCwd !== null && resolvedActiveBranch !== null
335 ? vcsEnvironment.listRefs({
336 environmentId,
337 input: {
338 cwd: branchCwd,
339 query: resolvedActiveBranch,
340 limit: 10,
341 },
342 })
343 : null,
344 );
345 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
346 (refName) => refName.name === resolvedActiveBranch,
347 );
348 const resolvedActiveBranchIsRemote =
349 listedActiveBranch !== null
350 ? listedActiveBranch.isRemote === true
351 : queriedActiveBranch
352 ? queriedActiveBranch.isRemote === true
353 : null;
354 const [isBranchActionPending, startBranchActionTransition] = useTransition();
355 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
356 const branchStatusText = isInitialBranchesLoadPending
357 ? "Loading refs..."
358 : isFetchingNextPage
359 ? "Loading more refs..."
360 : hasNextPage
361 ? `Showing ${refs.length} of ${totalBranchCount} refs`
362 : null;
363
364 const copyBranchName = (branchName: string) => {
365 void writeTextToClipboard(branchName, "branch name").then(
366 (didCopy) => {
367 if (!didCopy) return;
368 toastManager.add({
369 type: "success",
370 title: "Branch name copied",
371 description: branchName,
372 });
373 },
374 (error: unknown) => {
375 toastManager.add(
376 stackedThreadToast({
377 type: "error",
378 title: "Failed to copy branch name",
379 description: toBranchActionErrorMessage(error),
380 }),
381 );
382 },
383 );
384 };
385
386 const handleBranchContextMenu = (event: ReactMouseEvent, branchName: string | null) => {
387 if (!branchName) return;
388 const api = readLocalApi();
389 if (!api) return;
390 event.preventDefault();
391 event.stopPropagation();
392 const items: ContextMenuItem<"copy-branch-name">[] = [
393 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
394 ];
395 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
396 if (action === "copy-branch-name") copyBranchName(branchName);
397 });
398 };
399
400 const runBranchAction = (action: () => Promise<void>) => {
401 if (
402 !readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
403 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
404 ) {
405 toastManager.add(
406 stackedThreadToast({
407 type: "error",
408 title: "Action unavailable",
409 description: "This connection cannot change the thread's branch.",
410 }),
411 );
412 return;
413 }
414 startBranchActionTransition(async () => {
415 await action();
416 branchRefState.refresh();
417 branchStatusQuery.refresh();
418 });
419 };
420
421 const selectBranch = (refName: VcsRef) => {
422 if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
423
424 const latest = readLatestThreadState();
425 if (isSelectingWorktreeBase) {
426 if (latest.worktreePath) return;
427 setThreadBranch(refName.name, null);
428 setIsBranchMenuOpen(false);
429 onComposerFocusRequest?.();
430 return;
431 }
432 const selectionTarget = resolveBranchSelectionTarget({
433 activeProjectCwd,
434 activeProjectCheckoutRoot,
435 activeWorktreePath: latest.worktreePath,
436 refName,
437 });
438
439 if (
440 isWorktreeChangeBlocked({
441 runtime: latest.runtime,
442 currentWorktreePath: latest.worktreePath,
443 nextWorktreePath: selectionTarget.nextWorktreePath,
444 })
445 )
446 return;
447
448 if (selectionTarget.reuseExistingWorktree) {
449 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
450 setIsBranchMenuOpen(false);
451 onComposerFocusRequest?.();
452 return;
453 }
454
455 const selectedBranchName = refName.isRemote
456 ? deriveLocalBranchNameFromRemoteRef(refName.name)
457 : refName.name;
458
459 setIsBranchMenuOpen(false);
460 onComposerFocusRequest?.();
461
462 runBranchAction(async () => {
463 const previousBranch = resolvedActiveBranch;
464 setOptimisticBranch(selectedBranchName);
465 const checkoutResult = await switchRef({
466 environmentId,
467 input: {
468 cwd: selectionTarget.checkoutCwd,
469 refName: refName.name,
470 },
471 });
472 if (checkoutResult._tag === "Success") {
473 const nextBranchName = refName.isRemote
474 ? (checkoutResult.value.refName ?? selectedBranchName)
475 : selectedBranchName;
476 setOptimisticBranch(
477 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath)
478 ? nextBranchName
479 : previousBranch,
480 );
481 return;
482 }
483 setOptimisticBranch(previousBranch);
484 if (!isAtomCommandInterrupted(checkoutResult)) {
485 toastManager.add(
486 stackedThreadToast({
487 type: "error",
488 title: "Failed to switch ref.",
489 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
490 }),
491 );
492 }
493 });
494 };
495
496 const createRef = (rawName: string) => {
497 if (!canChangeThreadBranch) return;
498 const name = sanitizeNewRefName(rawName);
499 if (!branchCwd || !name || isBranchActionPending) return;
500
501 setIsBranchMenuOpen(false);
502 onComposerFocusRequest?.();
503
504 runBranchAction(async () => {
505 const previousBranch = resolvedActiveBranch;
506 setOptimisticBranch(name);
507 const createBranchResult = await createRefMutation({
508 environmentId,
509 input: {
510 cwd: branchCwd,
511 refName: name,
512 switchRef: true,
513 },
514 });
515 if (createBranchResult._tag === "Success") {
516 const nextBranchName = createBranchResult.value.refName;
517 setOptimisticBranch(
518 setThreadBranch(nextBranchName, activeWorktreePath) ? nextBranchName : previousBranch,
519 );
520 return;
521 }
522 setOptimisticBranch(previousBranch);
523 if (!isAtomCommandInterrupted(createBranchResult)) {
524 toastManager.add(
525 stackedThreadToast({
526 type: "error",
527 title: "Failed to create and switch ref.",
528 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
529 }),
530 );
531 }
532 });
533 };
534
535 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
536 ? null
537 : (defaultBranchName ?? currentGitBranch);
538
539 // The server sets started threads' branches; defaulting here would detach the agent from its worktree.
540 const threadStarted = serverSession !== null;
541 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes a default base branch to the server thread or draft once branches load for a new worktree thread
542 useEffect(() => {
543 if (
544 threadStarted ||
545 effectiveEnvMode !== "worktree" ||
546 activeWorktreePath ||
547 activeThreadBranch ||
548 !worktreeBaseBranchCandidate
549 ) {
550 return;
551 }
552 setThreadBranch(worktreeBaseBranchCandidate, null, true);
553 }, [
554 activeThreadBranch,
555 activeWorktreePath,
556 effectiveEnvMode,
557 setThreadBranch,
558 threadStarted,
559 worktreeBaseBranchCandidate,
560 ]);
561
562 const handleOpenChange = (open: boolean) => {
563 setIsBranchMenuOpen(open);
564 if (open && !isBranchMenuOpen && branchCwd !== null) {
565 void refreshLocalStatusForPicker({
566 environmentId,
567 input: { cwd: branchCwd, localOnly: true },
568 });
569 }
570 if (!open) {
571 setBranchQuery("");
572 }
573 };
574
575 useImperativeHandle(
576 ref,
577 () => ({
578 open: () => {
579 if (isInitialBranchesLoadPending || isBranchActionPending) return;
580 handleOpenChange(true);
581 },
582 }),
583 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
584 );
585
586 const triggerLabel = resolveBranchTriggerLabel({
587 activeWorktreePath,
588 effectiveEnvMode,
589 resolvedActiveBranch,
590 resolvedActiveBranchIsRemote,
591 startFromOrigin,
592 });
593
594 const branchPrBranch = resolveBranchToolbarPrBranch({
595 activeThreadBranch,
596 resolvedActiveBranch,
597 });
598 const branchPr = resolveDisplayedThreadPr({
599 threadBranch: branchPrBranch,
600 gitStatus: branchStatusQuery.data,
601 });
602 const {
603 badge: prBadge,
604 number: prNumber,
605 url: prUrl,
606 status: prStatus,
607 } = useThreadDisplayedPullRequest(
608 environmentId,
609 serverThread,
610 branchPr,
611 branchStatusQuery.data?.sourceControlProvider,
612 );
613 const openPrLink = useOpenPrLink(threadRef);
614
615 function selectPickerItem(itemValue: string) {
616 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
617 handleOpenChange(false);
618 onComposerFocusRequest?.();
619 onCheckoutPullRequestRequest(prReference);
620 } else if (itemValue === createBranchItemValue) {
621 createRef(trimmedBranchQuery);
622 } else {
623 const refName = branchByName.get(itemValue);
624 if (refName) selectBranch(refName);
625 }
626 }
627
628 function renderPickerItem(itemValue: string, index: number) {
629 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
630 return (
631 <ComboboxItem
632 hideIndicator
633 key={itemValue}
634 index={index}
635 value={itemValue}
636 onClick={() => selectPickerItem(itemValue)}
637 >
638 <div className="flex min-w-0 items-center gap-2 py-1">
639 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
640 <span className="flex min-w-0 flex-col items-start">
641 <span className="truncate font-medium">
642 Checkout {sourceControlPresentation.terminology.singular}
643 </span>
644 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
645 </span>
646 </div>
647 </ComboboxItem>
648 );
649 }
650 if (createBranchItemValue && itemValue === createBranchItemValue) {
651 return (
652 <ComboboxItem
653 hideIndicator
654 key={itemValue}
655 index={index}
656 value={itemValue}
657 onClick={() => selectPickerItem(itemValue)}
658 >
659 <span className="truncate">Create new ref "{newRefName}"</span>
660 </ComboboxItem>
661 );
662 }
663
664 const refName = branchByName.get(itemValue);
665 if (!refName) return null;
666
667 return (
668 <BranchPickerRefItem
669 branch={refName}
670 projectCwd={activeProjectCwd}
671 index={index}
672 value={itemValue}
673 disabled={
674 !canUpdateThreadBranch ||
675 (!canWriteSourceControl &&
676 !isSelectingWorktreeBase &&
677 (!activeProjectCwd ||
678 !resolveBranchSelectionTarget({
679 activeProjectCwd,
680 activeProjectCheckoutRoot,
681 activeWorktreePath,
682 refName,
683 }).reuseExistingWorktree)) ||
684 isWorktreeChangeBlockedForRef(refName)
685 }
686 onClick={() => selectPickerItem(itemValue)}
687 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
688 />
689 );
690 }
691
692 return (
693 <BranchPicker
694 items={branchPickerItems}
695 filteredItems={filteredBranchPickerItems}
696 open={isBranchMenuOpen}
697 onOpenChange={handleOpenChange}
698 onSelectItem={selectPickerItem}
699 value={resolvedActiveBranch}
700 query={branchQuery}
701 onQueryChange={setBranchQuery}
702 hasNextPage={hasNextPage}
703 isFetchingNextPage={isFetchingNextPage}
704 onLoadNext={branchRefState.loadNext}
705 statusText={branchStatusText}
706 notice={
707 refs.some((refName) => isWorktreeChangeBlockedForRef(refName))
708 ? WORKTREE_CHANGE_BLOCKED_MESSAGE
709 : null
710 }
711 renderItem={renderPickerItem}
712 getItemType={(item) =>
713 item === checkoutPullRequestItemValue
714 ? "checkout-pull-request"
715 : item === createBranchItemValue
716 ? "create-branch"
717 : "branch"
718 }
719 originControl={
720 isSelectingWorktreeBase
721 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
722 : undefined
723 }
724 popupProps={{
725 align: displayMode === "panel" ? "start" : "end",
726 side: displayMode === "panel" ? "bottom" : "top",
727 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
728 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
729 }}
730 >
731 <div
732 className={cn(
733 "flex min-w-0",
734 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
735 className,
736 )}
737 >
738 {displayMode !== "panel" ? (
739 <ThreadPullRequestBadgeControl
740 render={<ComposerControl size="xs" />}
741 badge={prBadge}
742 pullRequests={serverThread?.pullRequests ?? []}
743 number={prNumber}
744 url={prUrl}
745 status={prStatus}
746 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
747 onOpenPullRequest={(event, targetUrl = prUrl) => {
748 if (targetUrl) openPrLink(event, targetUrl);
749 }}
750 />
751 ) : null}
752 <span
753 className="flex min-w-0"
754 onMouseDownCapture={(event) => {
755 if (event.button !== 0 || event.ctrlKey) {
756 event.stopPropagation();
757 }
758 }}
759 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
760 >
761 <ComboboxTrigger
762 render={
763 displayMode === "panel" ? (
764 <ThreadDetailsControl part="select" />
765 ) : (
766 <ComposerControl size="xs" />
767 )
768 }
769 className="min-w-0 max-w-full active:scale-100"
770 disabled={isInitialBranchesLoadPending || isBranchActionPending}
771 >
772 <GitBranchIcon
773 className={cn(
774 "size-3 shrink-0",
775 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
776 )}
777 />
778 <ComposerContextLabel displayMode={displayMode}>
779 <MiddleTruncate value={triggerLabel} variant="cap-aligned" className="w-full" />
780 </ComposerContextLabel>
781 </ComboboxTrigger>
782 </span>
783 {displayMode === "panel" ? (
784 <ThreadDetailsThreadPrRows
785 threadRef={threadRef}
786 project={activeProject}
787 branchPr={branchPr}
788 branchSourceControlProvider={branchStatusQuery.data?.sourceControlProvider}
789 onActed={() => branchStatusQuery.refresh()}
790 />
791 ) : null}
792 </div>
793 </BranchPicker>
794 );
795}