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