Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BranchToolbarBranchSelector.tsx

803 lines27.4 KB

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;
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;
95​
96function toBranchActionErrorMessage(error: unknown): string {
97 return error instanceof Error ? error.message : "An error occurred.";
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 createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
132 reportFailure: false,
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 const setThreadBranch = useCallback(
174 (branch: string | null, worktreePath: string | null, automatic = false) => {
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 activeThreadId,
217 activeProject,
218 serverSession,
219 activeWorktreePath,
220 hasServerThread,
221 onActiveThreadBranchOverrideChange,
222 setDraftThreadContext,
223 draftId,
224 threadRef,
225 environmentId,
226 effectiveEnvMode,
227 draftThread?.environmentSelection,
228 stopThreadSession,
229 updateEmptyThreadMetadata,
230 updateThreadMetadata,
231 ],
232 );
233​
234 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
235 const [branchQuery, setBranchQuery] = useState("");
236 const deferredBranchQuery = useDeferredValue(branchQuery);
237​
238 const branchStatusQuery = useEnvironmentQuery(
239 branchCwd === null
240 ? null
241 : vcsEnvironment.status({
242 environmentId,
243 input: { cwd: branchCwd },
244 }),
245 );
246 const trimmedBranchQuery = branchQuery.trim();
247 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
248 // The server filters refs by substring, so it has to be given the sanitized
249 // name as well: querying the raw "new branch" drops an existing new-branch
250 // from the response entirely, which would defeat the collision check below.
251 // Ref names cannot contain an ASCII space, so sanitizing loses no matches.
252 const branchRefQuery = sanitizeNewRefName(deferredTrimmedBranchQuery);
253 const branchRefState = usePaginatedBranches({
254 environmentId,
255 cwd: branchCwd,
256 query: branchRefQuery,
257 });
258 const refs = branchRefState.refs;
259 const hasNextPage =
260 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
261 const isFetchingNextPage = branchRefState.isFetchingNextPage;
262 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
263 const currentGitBranch =
264 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
265 const sourceControlPresentation = useMemo(
266 () => getSourceControlPresentation(branchStatusQuery.data?.sourceControlProvider),
267 [branchStatusQuery.data?.sourceControlProvider],
268 );
269 const SourceControlIcon = sourceControlPresentation.Icon;
270 const canonicalActiveBranch = resolveBranchToolbarValue({
271 envMode: effectiveEnvMode,
272 activeWorktreePath,
273 activeThreadBranch,
274 currentGitBranch,
275 });
276 const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
277 const branchByName = useMemo(
278 () => new Map(refs.map((refName) => [refName.name, refName] as const)),
279 [refs],
280 );
281 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
282 const prReference = parsePullRequestReference(trimmedBranchQuery);
283 const isSelectingWorktreeBase =
284 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
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 branchPickerItems = useMemo(() => {
297 const items = [...branchNames];
298 if (createBranchItemValue && !hasExactBranchMatch) {
299 items.push(createBranchItemValue);
300 }
301 if (checkoutPullRequestItemValue) {
302 items.unshift(checkoutPullRequestItemValue);
303 }
304 return items;
305 }, [branchNames, checkoutPullRequestItemValue, createBranchItemValue, hasExactBranchMatch]);
306 const filteredBranchPickerItems = useMemo(
307 () =>
308 normalizedDeferredBranchQuery.length === 0
309 ? branchPickerItems
310 : branchPickerItems.filter((itemValue) =>
311 shouldIncludeBranchPickerItem({
312 itemValue,
313 normalizedQuery: normalizedDeferredBranchQuery,
314 createBranchItemValue,
315 checkoutPullRequestItemValue,
316 }),
317 ),
318 [
319 branchPickerItems,
320 checkoutPullRequestItemValue,
321 createBranchItemValue,
322 normalizedDeferredBranchQuery,
323 ],
324 );
325 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
326 canonicalActiveBranch,
327 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
328 );
329 const listedActiveBranch =
330 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
331 const activeBranchRefQuery = useEnvironmentQuery(
332 branchCwd !== null && resolvedActiveBranch !== null
333 ? vcsEnvironment.listRefs({
334 environmentId,
335 input: {
336 cwd: branchCwd,
337 query: resolvedActiveBranch,
338 limit: 10,
339 },
340 })
341 : null,
342 );
343 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
344 (refName) => refName.name === resolvedActiveBranch,
345 );
346 const resolvedActiveBranchIsRemote =
347 listedActiveBranch !== null
348 ? listedActiveBranch.isRemote === true
349 : queriedActiveBranch
350 ? queriedActiveBranch.isRemote === true
351 : null;
352 const [isBranchActionPending, startBranchActionTransition] = useTransition();
353 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
354 const branchStatusText = isInitialBranchesLoadPending
355 ? "Loading refs..."
356 : isFetchingNextPage
357 ? "Loading more refs..."
358 : hasNextPage
359 ? `Showing ${refs.length} of ${totalBranchCount} refs`
360 : null;
361​
362 const copyBranchName = useCallback((branchName: string) => {
363 void writeTextToClipboard(branchName, "branch name").then(
364 (didCopy) => {
365 if (!didCopy) return;
366 toastManager.add({
367 type: "success",
368 title: "Branch name copied",
369 description: branchName,
370 });
371 },
372 (error: unknown) => {
373 toastManager.add(
374 stackedThreadToast({
375 type: "error",
376 title: "Failed to copy branch name",
377 description: toBranchActionErrorMessage(error),
378 }),
379 );
380 },
381 );
382 }, []);
383​
384 const handleBranchContextMenu = useCallback(
385 (event: ReactMouseEvent, branchName: string | null) => {
386 if (!branchName) return;
387 const api = readLocalApi();
388 if (!api) return;
389 event.preventDefault();
390 event.stopPropagation();
391 const items: ContextMenuItem<"copy-branch-name">[] = [
392 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
393 ];
394 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
395 if (action === "copy-branch-name") copyBranchName(branchName);
396 });
397 },
398 [copyBranchName],
399 );
400​
401 const runBranchAction = (action: () => Promise<void>) => {
402 if (
403 !readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
404 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
405 ) {
406 toastManager.add(
407 stackedThreadToast({
408 type: "error",
409 title: "Action unavailable",
410 description: "This connection cannot change the thread's branch.",
411 }),
412 );
413 return;
414 }
415 startBranchActionTransition(async () => {
416 await action();
417 branchRefState.refresh();
418 branchStatusQuery.refresh();
419 });
420 };
421​
422 const selectBranch = (refName: VcsRef) => {
423 if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
424​
425 if (isSelectingWorktreeBase) {
426 setThreadBranch(refName.name, null);
427 setIsBranchMenuOpen(false);
428 onComposerFocusRequest?.();
429 return;
430 }
431​
432 const selectionTarget = resolveBranchSelectionTarget({
433 activeProjectCwd,
434 activeWorktreePath,
435 refName,
436 });
437​
438 if (selectionTarget.reuseExistingWorktree) {
439 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
440 setIsBranchMenuOpen(false);
441 onComposerFocusRequest?.();
442 return;
443 }
444​
445 const selectedBranchName = refName.isRemote
446 ? deriveLocalBranchNameFromRemoteRef(refName.name)
447 : refName.name;
448​
449 setIsBranchMenuOpen(false);
450 onComposerFocusRequest?.();
451​
452 runBranchAction(async () => {
453 const previousBranch = resolvedActiveBranch;
454 setOptimisticBranch(selectedBranchName);
455 const checkoutResult = await switchRef({
456 environmentId,
457 input: {
458 cwd: selectionTarget.checkoutCwd,
459 refName: refName.name,
460 },
461 });
462 if (checkoutResult._tag === "Success") {
463 const nextBranchName = refName.isRemote
464 ? (checkoutResult.value.refName ?? selectedBranchName)
465 : selectedBranchName;
466 setOptimisticBranch(nextBranchName);
467 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
468 return;
469 }
470 setOptimisticBranch(previousBranch);
471 if (!isAtomCommandInterrupted(checkoutResult)) {
472 toastManager.add(
473 stackedThreadToast({
474 type: "error",
475 title: "Failed to switch ref.",
476 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
477 }),
478 );
479 }
480 });
481 };
482​
483 const createRef = (rawName: string) => {
484 if (!canChangeThreadBranch) return;
485 const name = sanitizeNewRefName(rawName);
486 if (!branchCwd || !name || isBranchActionPending) return;
487​
488 setIsBranchMenuOpen(false);
489 onComposerFocusRequest?.();
490​
491 runBranchAction(async () => {
492 const previousBranch = resolvedActiveBranch;
493 setOptimisticBranch(name);
494 const createBranchResult = await createRefMutation({
495 environmentId,
496 input: {
497 cwd: branchCwd,
498 refName: name,
499 switchRef: true,
500 },
501 });
502 if (createBranchResult._tag === "Success") {
503 setOptimisticBranch(createBranchResult.value.refName);
504 setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
505 return;
506 }
507 setOptimisticBranch(previousBranch);
508 if (!isAtomCommandInterrupted(createBranchResult)) {
509 toastManager.add(
510 stackedThreadToast({
511 type: "error",
512 title: "Failed to create and switch ref.",
513 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
514 }),
515 );
516 }
517 });
518 };
519​
520 const defaultBranchName = useMemo(
521 () => refs.find((refName) => refName.isDefault)?.name ?? null,
522 [refs],
523 );
524 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
525 ? null
526 : (defaultBranchName ?? currentGitBranch);
527​
528 // A started thread's server is creating its worktree and records the branch
529 // itself; defaulting it here would reset the thread to the base checkout and
530 // detach the agent that just started.
531 const threadStarted = serverSession !== null;
532 useEffect(() => {
533 if (
534 threadStarted ||
535 effectiveEnvMode !== "worktree" ||
536 activeWorktreePath ||
537 activeThreadBranch ||
538 !worktreeBaseBranchCandidate
539 ) {
540 return;
541 }
542 setThreadBranch(worktreeBaseBranchCandidate, null, true);
543 }, [
544 activeThreadBranch,
545 activeWorktreePath,
546 effectiveEnvMode,
547 setThreadBranch,
548 threadStarted,
549 worktreeBaseBranchCandidate,
550 ]);
551​
552 const handleOpenChange = useCallback((open: boolean) => {
553 setIsBranchMenuOpen(open);
554 if (!open) {
555 setBranchQuery("");
556 }
557 }, []);
558​
559 useImperativeHandle(
560 ref,
561 () => ({
562 open: () => {
563 if (isInitialBranchesLoadPending || isBranchActionPending) return;
564 handleOpenChange(true);
565 },
566 }),
567 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
568 );
569​
570 const triggerLabel = resolveBranchTriggerLabel({
571 activeWorktreePath,
572 effectiveEnvMode,
573 resolvedActiveBranch,
574 resolvedActiveBranchIsRemote,
575 startFromOrigin,
576 });
577​
578 const branchPrBranch = resolveBranchToolbarPrBranch({
579 activeThreadBranch,
580 resolvedActiveBranch,
581 });
582 const branchPr =
583 branchPrBranch !== null && branchStatusQuery.data?.refName === branchPrBranch
584 ? (branchStatusQuery.data.pr ?? null)
585 : null;
586 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId);
587 const linkedStatus = useLinkedThreadPullRequest(
588 environmentId,
589 serverThread?.linkedPullRequest,
590 true,
591 serverThread?.pullRequests,
592 serverThread?.branchPullRequest,
593 );
594 const currentLinkedPr = supportsMultiplePullRequests
595 ? resolveThreadCurrentPullRequestLink(serverThread?.pullRequests ?? [])
596 : null;
597 const prBadge = supportsMultiplePullRequests
598 ? resolveThreadPullRequestBadge(serverThread?.pullRequests)
599 : null;
600 const displayedPr = linkedStatus?.pr ?? (currentLinkedPr === null ? branchPr : null);
601 const displayedPrStatus = prStatusIndicator(
602 displayedPr,
603 linkedStatus?.sourceControlProvider ?? branchStatusQuery.data?.sourceControlProvider,
604 );
605 const prNumber = currentLinkedPr?.number ?? displayedPr?.number;
606 const prUrl = currentLinkedPr?.url ?? displayedPr?.url;
607 const openPrLink = useOpenPrLink(threadRef);
608 const panelPrLabel =
609 prNumber === undefined
610 ? ""
611 : `#${prNumber}${displayedPr?.title.trim() ? `: ${displayedPr.title}` : ""}`;
612​
613 function selectPickerItem(itemValue: string) {
614 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
615 handleOpenChange(false);
616 onComposerFocusRequest?.();
617 onCheckoutPullRequestRequest(prReference);
618 } else if (itemValue === createBranchItemValue) {
619 createRef(trimmedBranchQuery);
620 } else {
621 const refName = branchByName.get(itemValue);
622 if (refName) selectBranch(refName);
623 }
624 }
625​
626 function renderPickerItem(itemValue: string, index: number) {
627 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
628 return (
629 <ComboboxItem
630 hideIndicator
631 key={itemValue}
632 index={index}
633 value={itemValue}
634 onClick={() => selectPickerItem(itemValue)}
635 >
636 <div className="flex min-w-0 items-center gap-2 py-1">
637 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
638 <span className="flex min-w-0 flex-col items-start">
639 <span className="truncate font-medium">
640 Checkout {sourceControlPresentation.terminology.singular}
641 </span>
642 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
643 </span>
644 </div>
645 </ComboboxItem>
646 );
647 }
648 if (createBranchItemValue && itemValue === createBranchItemValue) {
649 return (
650 <ComboboxItem
651 hideIndicator
652 key={itemValue}
653 index={index}
654 value={itemValue}
655 onClick={() => selectPickerItem(itemValue)}
656 >
657 <span className="truncate">Create new ref &quot;{newRefName}&quot;</span>
658 </ComboboxItem>
659 );
660 }
661​
662 const refName = branchByName.get(itemValue);
663 if (!refName) return null;
664​
665 return (
666 <BranchPickerRefItem
667 branch={refName}
668 projectCwd={activeProjectCwd}
669 index={index}
670 value={itemValue}
671 disabled={
672 !canUpdateThreadBranch ||
673 (!canWriteSourceControl &&
674 !isSelectingWorktreeBase &&
675 (!activeProjectCwd ||
676 !resolveBranchSelectionTarget({
677 activeProjectCwd,
678 activeWorktreePath,
679 refName,
680 }).reuseExistingWorktree))
681 }
682 onClick={() => selectPickerItem(itemValue)}
683 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
684 />
685 );
686 }
687​
688 return (
689 <BranchPicker
690 items={branchPickerItems}
691 filteredItems={filteredBranchPickerItems}
692 open={isBranchMenuOpen}
693 onOpenChange={handleOpenChange}
694 onSelectItem={selectPickerItem}
695 value={resolvedActiveBranch}
696 query={branchQuery}
697 resultsQuery={deferredTrimmedBranchQuery}
698 onQueryChange={setBranchQuery}
699 hasNextPage={hasNextPage}
700 isFetchingNextPage={isFetchingNextPage}
701 onLoadNext={branchRefState.loadNext}
702 statusText={branchStatusText}
703 renderItem={renderPickerItem}
704 getItemType={(item) =>
705 item === checkoutPullRequestItemValue
706 ? "checkout-pull-request"
707 : item === createBranchItemValue
708 ? "create-branch"
709 : "branch"
710 }
711 originControl={
712 isSelectingWorktreeBase
713 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
714 : undefined
715 }
716 popupProps={{
717 align: displayMode === "panel" ? "start" : "end",
718 side: displayMode === "panel" ? "bottom" : "top",
719 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
720 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
721 }}
722 >
723 <div
724 className={cn(
725 "flex min-w-0",
726 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
727 className,
728 )}
729 >
730 {displayMode !== "panel" ? (
731 <ThreadPullRequestBadgeControl
732 render={<ComposerControl size="xs" />}
733 badge={prBadge}
734 pullRequests={serverThread?.pullRequests ?? []}
735 number={prNumber}
736 url={prUrl}
737 status={displayedPrStatus}
738 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
739 onOpenPullRequest={(event, targetUrl = prUrl) => {
740 if (targetUrl) openPrLink(event, targetUrl);
741 }}
742 />
743 ) : null}
744 <span
745 className="flex min-w-0"
746 onMouseDownCapture={(event) => {
747 if (event.button !== 0 || event.ctrlKey) {
748 event.stopPropagation();
749 }
750 }}
751 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
752 >
753 <ComboboxTrigger
754 render={
755 displayMode === "panel" ? (
756 <ThreadDetailsControl part="select" />
757 ) : (
758 <ComposerControl size="xs" />
759 )
760 }
761 className="min-w-0 max-w-full active:scale-100"
762 disabled={isInitialBranchesLoadPending || isBranchActionPending}
763 >
764 <GitBranchIcon
765 className={cn(
766 "size-3 shrink-0 opacity-70",
767 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
768 )}
769 />
770 <ComposerContextLabel displayMode={displayMode}>
771 <MiddleTruncate
772 value={triggerLabel}
773 variant={displayMode === "panel" ? "cap-aligned" : "default"}
774 className="w-full"
775 />
776 </ComposerContextLabel>
777 {displayMode !== "panel" ? (
778 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
779 ) : null}
780 </ComboboxTrigger>
781 </span>
782 {displayMode === "panel" && prNumber !== undefined && prUrl !== undefined ? (
783 <ThreadDetailsPrRows
784 threadRef={threadRef}
785 links={serverThread?.pullRequests ?? []}
786 currentLink={currentLinkedPr}
787 onOpenLink={openPrLink}
788 environmentId={environmentId}
789 pr={displayedPr}
790 number={prNumber}
791 reference={currentLinkedPr}
792 status={displayedPrStatus}
793 project={activeProject}
794 label={panelPrLabel}
795 openAriaLabel={prUrl ?? "Open pull request"}
796 onOpen={(event) => openPrLink(event, prUrl)}
797 onActed={() => branchStatusQuery.refresh()}
798 />
799 ) : null}
800 </div>
801 </BranchPicker>
802 );