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 refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
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 refreshStatus({ environmentId, input: { cwd: branchCwd, localOnly: true } });
566 }
567 if (!open) {
568 setBranchQuery("");
569 }
570 };
571
572 useImperativeHandle(
573 ref,
574 () => ({
575 open: () => {
576 if (isInitialBranchesLoadPending || isBranchActionPending) return;
577 handleOpenChange(true);
578 },
579 }),
580 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
581 );
582
583 const triggerLabel = resolveBranchTriggerLabel({
584 activeWorktreePath,
585 effectiveEnvMode,
586 resolvedActiveBranch,
587 resolvedActiveBranchIsRemote,
588 startFromOrigin,
589 });
590
591 const branchPrBranch = resolveBranchToolbarPrBranch({
592 activeThreadBranch,
593 resolvedActiveBranch,
594 });
595 const branchPr = resolveDisplayedThreadPr({
596 threadBranch: branchPrBranch,
597 gitStatus: branchStatusQuery.data,
598 });
599 const {
600 badge: prBadge,
601 number: prNumber,
602 url: prUrl,
603 status: prStatus,
604 } = useThreadDisplayedPullRequest(
605 environmentId,
606 serverThread,
607 branchPr,
608 branchStatusQuery.data?.sourceControlProvider,
609 );
610 const openPrLink = useOpenPrLink(threadRef);
611
612 function selectPickerItem(itemValue: string) {
613 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
614 handleOpenChange(false);
615 onComposerFocusRequest?.();
616 onCheckoutPullRequestRequest(prReference);
617 } else if (itemValue === createBranchItemValue) {
618 createRef(trimmedBranchQuery);
619 } else {
620 const refName = branchByName.get(itemValue);
621 if (refName) selectBranch(refName);
622 }
623 }
624
625 function renderPickerItem(itemValue: string, index: number) {
626 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
627 return (
628 <ComboboxItem
629 hideIndicator
630 key={itemValue}
631 index={index}
632 value={itemValue}
633 onClick={() => selectPickerItem(itemValue)}
634 >
635 <div className="flex min-w-0 items-center gap-2 py-1">
636 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
637 <span className="flex min-w-0 flex-col items-start">
638 <span className="truncate font-medium">
639 Checkout {sourceControlPresentation.terminology.singular}
640 </span>
641 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
642 </span>
643 </div>
644 </ComboboxItem>
645 );
646 }
647 if (createBranchItemValue && itemValue === createBranchItemValue) {
648 return (
649 <ComboboxItem
650 hideIndicator
651 key={itemValue}
652 index={index}
653 value={itemValue}
654 onClick={() => selectPickerItem(itemValue)}
655 >
656 <span className="truncate">Create new ref "{newRefName}"</span>
657 </ComboboxItem>
658 );
659 }
660
661 const refName = branchByName.get(itemValue);
662 if (!refName) return null;
663
664 return (
665 <BranchPickerRefItem
666 branch={refName}
667 projectCwd={activeProjectCwd}
668 index={index}
669 value={itemValue}
670 disabled={
671 !canUpdateThreadBranch ||
672 (!canWriteSourceControl &&
673 !isSelectingWorktreeBase &&
674 (!activeProjectCwd ||
675 !resolveBranchSelectionTarget({
676 activeProjectCwd,
677 activeProjectCheckoutRoot,
678 activeWorktreePath,
679 refName,
680 }).reuseExistingWorktree)) ||
681 isWorktreeChangeBlockedForRef(refName)
682 }
683 onClick={() => selectPickerItem(itemValue)}
684 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
685 />
686 );
687 }
688
689 return (
690 <BranchPicker
691 items={branchPickerItems}
692 filteredItems={filteredBranchPickerItems}
693 open={isBranchMenuOpen}
694 onOpenChange={handleOpenChange}
695 onSelectItem={selectPickerItem}
696 value={resolvedActiveBranch}
697 query={branchQuery}
698 onQueryChange={setBranchQuery}
699 hasNextPage={hasNextPage}
700 isFetchingNextPage={isFetchingNextPage}
701 onLoadNext={branchRefState.loadNext}
702 statusText={branchStatusText}
703 notice={
704 refs.some((refName) => isWorktreeChangeBlockedForRef(refName))
705 ? WORKTREE_CHANGE_BLOCKED_MESSAGE
706 : null
707 }
708 renderItem={renderPickerItem}
709 getItemType={(item) =>
710 item === checkoutPullRequestItemValue
711 ? "checkout-pull-request"
712 : item === createBranchItemValue
713 ? "create-branch"
714 : "branch"
715 }
716 originControl={
717 isSelectingWorktreeBase
718 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
719 : undefined
720 }
721 popupProps={{
722 align: displayMode === "panel" ? "start" : "end",
723 side: displayMode === "panel" ? "bottom" : "top",
724 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
725 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
726 }}
727 >
728 <div
729 className={cn(
730 "flex min-w-0",
731 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
732 className,
733 )}
734 >
735 {displayMode !== "panel" ? (
736 <ThreadPullRequestBadgeControl
737 render={<ComposerControl size="xs" />}
738 badge={prBadge}
739 pullRequests={serverThread?.pullRequests ?? []}
740 number={prNumber}
741 url={prUrl}
742 status={prStatus}
743 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
744 onOpenPullRequest={(event, targetUrl = prUrl) => {
745 if (targetUrl) openPrLink(event, targetUrl);
746 }}
747 />
748 ) : null}
749 <span
750 className="flex min-w-0"
751 onMouseDownCapture={(event) => {
752 if (event.button !== 0 || event.ctrlKey) {
753 event.stopPropagation();
754 }
755 }}
756 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
757 >
758 <ComboboxTrigger
759 render={
760 displayMode === "panel" ? (
761 <ThreadDetailsControl part="select" />
762 ) : (
763 <ComposerControl size="xs" />
764 )
765 }
766 className="min-w-0 max-w-full active:scale-100"
767 disabled={isInitialBranchesLoadPending || isBranchActionPending}
768 >
769 <GitBranchIcon
770 className={cn(
771 "size-3 shrink-0",
772 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
773 )}
774 />
775 <ComposerContextLabel displayMode={displayMode}>
776 <MiddleTruncate value={triggerLabel} variant="cap-aligned" className="w-full" />
777 </ComposerContextLabel>
778 </ComboboxTrigger>
779 </span>
780 {displayMode === "panel" ? (
781 <ThreadDetailsThreadPrRows
782 threadRef={threadRef}
783 project={activeProject}
784 branchPr={branchPr}
785 branchSourceControlProvider={branchStatusQuery.data?.sourceControlProvider}
786 onActed={() => branchStatusQuery.refresh()}
787 />
788 ) : null}
789 </div>
790 </BranchPicker>
791 );
792}