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