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

BranchToolbarBranchSelector.tsx

759 lines26.3 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 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;
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;
93​
94function toBranchActionErrorMessage(error: unknown): string {
95 return error instanceof Error ? error.message : "An error occurred.";
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 createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
130 reportFailure: false,
131 });
132 const threadRef = scopeThreadRef(environmentId, threadId);
133 const serverThread = useQuietThreadShell(threadRef);
134 const serverSession = serverThread?.runtime ?? null;
135 const draftThread = useComposerDraftStore((store) =>
136 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
137 );
138 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
139​
140 const activeProjectRef = serverThread
141 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
142 : draftThread
143 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
144 : null;
145 const activeProject = useProject(activeProjectRef);
146​
147 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
148 const activeThreadBranch =
149 activeThreadBranchOverride !== undefined
150 ? activeThreadBranchOverride
151 : (serverThread?.branch ?? draftThread?.branch ?? null);
152 const activeWorktreePath = forceNewWorktree
153 ? null
154 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
155 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
156 const branchCwd = activeWorktreePath ?? activeProjectCwd;
157 const hasServerThread = serverThread !== null;
158 const canUpdateThreadBranch = !hasServerThread || canOperateThread;
159 const canChangeThreadBranch = canWriteSourceControl && canUpdateThreadBranch;
160 const effectiveEnvMode =
161 effectiveEnvModeOverride ??
162 resolveEffectiveEnvMode({
163 activeWorktreePath,
164 hasServerThread,
165 draftThreadEnvMode: draftThread?.envMode,
166 });
167​
168 const setThreadBranch = (
169 branch: string | null,
170 worktreePath: string | null,
171 automatic = false,
172 ) => {
173 if (
174 !activeThreadId ||
175 !activeProject ||
176 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
177 )
178 return;
179 if (serverSession && worktreePath !== activeWorktreePath) {
180 void stopThreadSession({
181 environmentId,
182 input: { threadId: activeThreadId },
183 });
184 }
185 if (hasServerThread) {
186 void (automatic ? updateEmptyThreadMetadata : updateThreadMetadata)({
187 environmentId,
188 input: {
189 threadId: activeThreadId,
190 branch,
191 worktreePath,
192 ...(automatic ? { expectedEmpty: true } : {}),
193 },
194 });
195 }
196 if (hasServerThread) {
197 onActiveThreadBranchOverrideChange?.(branch);
198 return;
199 }
200 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
201 nextWorktreePath: worktreePath,
202 currentWorktreePath: activeWorktreePath,
203 effectiveEnvMode,
204 });
205 setDraftThreadContext(draftId ?? threadRef, {
206 branch,
207 worktreePath,
208 envMode: nextDraftEnvMode,
209 environmentSelection: automatic ? (draftThread?.environmentSelection ?? "auto") : "manual",
210 projectRef: scopeProjectRef(environmentId, activeProject.id),
211 });
212 };
213​
214 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
215 const [branchQuery, setBranchQuery] = useState("");
216 const deferredBranchQuery = useDeferredValue(branchQuery);
217​
218 const branchStatusQuery = useEnvironmentQuery(
219 branchCwd === null
220 ? null
221 : vcsEnvironment.status({
222 environmentId,
223 input: { cwd: branchCwd },
224 }),
225 );
226 const branchRefState = usePaginatedBranches({
227 environmentId,
228 cwd: branchCwd,
229 // The server filters refs by substring, so it has to be given the sanitized
230 // name as well: querying the raw "new branch" drops an existing new-branch
231 // from the response entirely, which would defeat the collision check below.
232 // Ref names cannot contain an ASCII space, so sanitizing loses no matches.
233 query: sanitizeNewRefName(deferredBranchQuery.trim()),
234 });
235 const trimmedBranchQuery = branchQuery.trim();
236 const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
237 const refs = branchRefState.refs;
238 const branchByName = new Map(refs.map((refName) => [refName.name, refName] as const));
239 const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
240 const prReference = parsePullRequestReference(trimmedBranchQuery);
241 const isSelectingWorktreeBase =
242 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
243 const checkoutPullRequestItemValue =
244 canChangeThreadBranch && prReference && onCheckoutPullRequestRequest
245 ? `__checkout_pull_request__:${prReference}`
246 : null;
247 const canCreateBranch =
248 canChangeThreadBranch && !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
249 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
250 const hasExactBranchMatch = branchByName.has(newRefName);
251 const createBranchItemValue = canCreateBranch
252 ? `__create_new_branch__:${trimmedBranchQuery}`
253 : null;
254 const defaultBranchName = refs.find((refName) => refName.isDefault)?.name ?? null;
255 const pickerCreateBranchItemValue = hasExactBranchMatch ? null : createBranchItemValue;
256 const branchPickerItems = [
257 ...(checkoutPullRequestItemValue ? [checkoutPullRequestItemValue] : []),
258 ...refs.map((refName) => refName.name),
259 ...(pickerCreateBranchItemValue ? [pickerCreateBranchItemValue] : []),
260 ];
261 const filteredBranchPickerItems =
262 normalizedDeferredBranchQuery.length === 0
263 ? branchPickerItems
264 : branchPickerItems.filter((itemValue) =>
265 shouldIncludeBranchPickerItem({
266 itemValue,
267 normalizedQuery: normalizedDeferredBranchQuery,
268 createBranchItemValue: pickerCreateBranchItemValue,
269 checkoutPullRequestItemValue,
270 }),
271 );
272 const hasNextPage =
273 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
274 const isFetchingNextPage = branchRefState.isFetchingNextPage;
275 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
276 const currentGitBranch =
277 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
278 const sourceControlPresentation = getSourceControlPresentation(
279 branchStatusQuery.data?.sourceControlProvider,
280 );
281 const SourceControlIcon = sourceControlPresentation.Icon;
282 const canonicalActiveBranch = resolveBranchToolbarValue({
283 envMode: effectiveEnvMode,
284 activeWorktreePath,
285 activeThreadBranch,
286 currentGitBranch,
287 });
288 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
289 canonicalActiveBranch,
290 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
291 );
292 const listedActiveBranch =
293 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
294 const activeBranchRefQuery = useEnvironmentQuery(
295 branchCwd !== null && resolvedActiveBranch !== null
296 ? vcsEnvironment.listRefs({
297 environmentId,
298 input: {
299 cwd: branchCwd,
300 query: resolvedActiveBranch,
301 limit: 10,
302 },
303 })
304 : null,
305 );
306 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
307 (refName) => refName.name === resolvedActiveBranch,
308 );
309 const resolvedActiveBranchIsRemote =
310 listedActiveBranch !== null
311 ? listedActiveBranch.isRemote === true
312 : queriedActiveBranch
313 ? queriedActiveBranch.isRemote === true
314 : null;
315 const [isBranchActionPending, startBranchActionTransition] = useTransition();
316 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
317 const branchStatusText = isInitialBranchesLoadPending
318 ? "Loading refs..."
319 : isFetchingNextPage
320 ? "Loading more refs..."
321 : hasNextPage
322 ? `Showing ${refs.length} of ${totalBranchCount} refs`
323 : null;
324​
325 const copyBranchName = (branchName: string) => {
326 void writeTextToClipboard(branchName, "branch name").then(
327 (didCopy) => {
328 if (!didCopy) return;
329 toastManager.add({
330 type: "success",
331 title: "Branch name copied",
332 description: branchName,
333 });
334 },
335 (error: unknown) => {
336 toastManager.add(
337 stackedThreadToast({
338 type: "error",
339 title: "Failed to copy branch name",
340 description: toBranchActionErrorMessage(error),
341 }),
342 );
343 },
344 );
345 };
346​
347 const handleBranchContextMenu = (event: ReactMouseEvent, branchName: string | null) => {
348 if (!branchName) return;
349 const api = readLocalApi();
350 if (!api) return;
351 event.preventDefault();
352 event.stopPropagation();
353 const items: ContextMenuItem<"copy-branch-name">[] = [
354 { id: "copy-branch-name", label: "Copy branch name", icon: "copy" },
355 ];
356 void api.contextMenu.show(items, { x: event.clientX, y: event.clientY }).then((action) => {
357 if (action === "copy-branch-name") copyBranchName(branchName);
358 });
359 };
360​
361 const runBranchAction = (action: () => Promise<void>) => {
362 if (
363 !readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
364 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
365 ) {
366 toastManager.add(
367 stackedThreadToast({
368 type: "error",
369 title: "Action unavailable",
370 description: "This connection cannot change the thread's branch.",
371 }),
372 );
373 return;
374 }
375 startBranchActionTransition(async () => {
376 await action();
377 branchRefState.refresh();
378 branchStatusQuery.refresh();
379 });
380 };
381​
382 const selectBranch = (refName: VcsRef) => {
383 if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
384​
385 if (isSelectingWorktreeBase) {
386 setThreadBranch(refName.name, null);
387 setIsBranchMenuOpen(false);
388 onComposerFocusRequest?.();
389 return;
390 }
391​
392 const selectionTarget = resolveBranchSelectionTarget({
393 activeProjectCwd,
394 activeWorktreePath,
395 refName,
396 });
397​
398 if (selectionTarget.reuseExistingWorktree) {
399 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
400 setIsBranchMenuOpen(false);
401 onComposerFocusRequest?.();
402 return;
403 }
404​
405 const selectedBranchName = refName.isRemote
406 ? deriveLocalBranchNameFromRemoteRef(refName.name)
407 : refName.name;
408​
409 setIsBranchMenuOpen(false);
410 onComposerFocusRequest?.();
411​
412 runBranchAction(async () => {
413 const previousBranch = resolvedActiveBranch;
414 setOptimisticBranch(selectedBranchName);
415 const checkoutResult = await switchRef({
416 environmentId,
417 input: {
418 cwd: selectionTarget.checkoutCwd,
419 refName: refName.name,
420 },
421 });
422 if (checkoutResult._tag === "Success") {
423 const nextBranchName = refName.isRemote
424 ? (checkoutResult.value.refName ?? selectedBranchName)
425 : selectedBranchName;
426 setOptimisticBranch(nextBranchName);
427 setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
428 return;
429 }
430 setOptimisticBranch(previousBranch);
431 if (!isAtomCommandInterrupted(checkoutResult)) {
432 toastManager.add(
433 stackedThreadToast({
434 type: "error",
435 title: "Failed to switch ref.",
436 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
437 }),
438 );
439 }
440 });
441 };
442​
443 const createRef = (rawName: string) => {
444 if (!canChangeThreadBranch) return;
445 const name = sanitizeNewRefName(rawName);
446 if (!branchCwd || !name || isBranchActionPending) return;
447​
448 setIsBranchMenuOpen(false);
449 onComposerFocusRequest?.();
450​
451 runBranchAction(async () => {
452 const previousBranch = resolvedActiveBranch;
453 setOptimisticBranch(name);
454 const createBranchResult = await createRefMutation({
455 environmentId,
456 input: {
457 cwd: branchCwd,
458 refName: name,
459 switchRef: true,
460 },
461 });
462 if (createBranchResult._tag === "Success") {
463 setOptimisticBranch(createBranchResult.value.refName);
464 setThreadBranch(createBranchResult.value.refName, activeWorktreePath);
465 return;
466 }
467 setOptimisticBranch(previousBranch);
468 if (!isAtomCommandInterrupted(createBranchResult)) {
469 toastManager.add(
470 stackedThreadToast({
471 type: "error",
472 title: "Failed to create and switch ref.",
473 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
474 }),
475 );
476 }
477 });
478 };
479​
480 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
481 ? null
482 : (defaultBranchName ?? currentGitBranch);
483​
484 // A started thread's server is creating its worktree and records the branch
485 // itself; defaulting it here would reset the thread to the base checkout and
486 // detach the agent that just started.
487 const threadStarted = serverSession !== null;
488 useEffect(() => {
489 if (
490 threadStarted ||
491 effectiveEnvMode !== "worktree" ||
492 activeWorktreePath ||
493 activeThreadBranch ||
494 !worktreeBaseBranchCandidate
495 ) {
496 return;
497 }
498 setThreadBranch(worktreeBaseBranchCandidate, null, true);
499 }, [
500 activeThreadBranch,
501 activeWorktreePath,
502 effectiveEnvMode,
503 setThreadBranch,
504 threadStarted,
505 worktreeBaseBranchCandidate,
506 ]);
507​
508 const handleOpenChange = (open: boolean) => {
509 setIsBranchMenuOpen(open);
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 &quot;{newRefName}&quot;</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 resultsQuery={deferredTrimmedBranchQuery}
654 onQueryChange={setBranchQuery}
655 hasNextPage={hasNextPage}
656 isFetchingNextPage={isFetchingNextPage}
657 onLoadNext={branchRefState.loadNext}
658 statusText={branchStatusText}
659 renderItem={renderPickerItem}
660 getItemType={(item) =>
661 item === checkoutPullRequestItemValue
662 ? "checkout-pull-request"
663 : item === createBranchItemValue
664 ? "create-branch"
665 : "branch"
666 }
667 originControl={
668 isSelectingWorktreeBase
669 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
670 : undefined
671 }
672 popupProps={{
673 align: displayMode === "panel" ? "start" : "end",
674 side: displayMode === "panel" ? "bottom" : "top",
675 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
676 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
677 }}
678 >
679 <div
680 className={cn(
681 "flex min-w-0",
682 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
683 className,
684 )}
685 >
686 {displayMode !== "panel" ? (
687 <ThreadPullRequestBadgeControl
688 render={<ComposerControl size="xs" />}
689 badge={prBadge}
690 pullRequests={serverThread?.pullRequests ?? []}
691 number={prNumber}
692 url={prUrl}
693 status={displayedPrStatus}
694 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
695 onOpenPullRequest={(event, targetUrl = prUrl) => {
696 if (targetUrl) openPrLink(event, targetUrl);
697 }}
698 />
699 ) : null}
700 <span
701 className="flex min-w-0"
702 onMouseDownCapture={(event) => {
703 if (event.button !== 0 || event.ctrlKey) {
704 event.stopPropagation();
705 }
706 }}
707 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
708 >
709 <ComboboxTrigger
710 render={
711 displayMode === "panel" ? (
712 <ThreadDetailsControl part="select" />
713 ) : (
714 <ComposerControl size="xs" />
715 )
716 }
717 className="min-w-0 max-w-full active:scale-100"
718 disabled={isInitialBranchesLoadPending || isBranchActionPending}
719 >
720 <GitBranchIcon
721 className={cn(
722 "size-3 shrink-0 opacity-70",
723 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
724 )}
725 />
726 <ComposerContextLabel displayMode={displayMode}>
727 <MiddleTruncate
728 value={triggerLabel}
729 variant={displayMode === "panel" ? "cap-aligned" : "default"}
730 className="w-full"
731 />
732 </ComposerContextLabel>
733 {displayMode !== "panel" ? (
734 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
735 ) : null}
736 </ComboboxTrigger>
737 </span>
738 {displayMode === "panel" && prNumber !== undefined && prUrl !== undefined ? (
739 <ThreadDetailsPrRows
740 threadRef={threadRef}
741 links={serverThread?.pullRequests ?? []}
742 currentLink={currentLinkedPr}
743 onOpenLink={openPrLink}
744 environmentId={environmentId}
745 pr={displayedPr}
746 number={prNumber}
747 reference={currentLinkedPr}
748 status={displayedPrStatus}
749 project={activeProject}
750 label={panelPrLabel}
751 openAriaLabel={prUrl ?? "Open pull request"}
752 onOpen={(event) => openPrLink(event, prUrl)}
753 onActed={() => branchStatusQuery.refresh()}
754 />
755 ) : null}
756 </div>
757 </BranchPicker>
758 );