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