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