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

BranchToolbarBranchSelector.tsx

757 lines26.2 KB

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 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 refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, {
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 // 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
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 && !isBranchMenuOpen && branchCwd !== null) {
511 void refreshLocalStatusForPicker({
512 environmentId,
513 input: { cwd: branchCwd, localOnly: true },
514 });
515 }
516 if (!open) {
517 setBranchQuery("");
518 }
519 };
520​
521 useImperativeHandle(
522 ref,
523 () => ({
524 open: () => {
525 if (isInitialBranchesLoadPending || isBranchActionPending) return;
526 handleOpenChange(true);
527 },
528 }),
529 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
530 );
531​
532 const triggerLabel = resolveBranchTriggerLabel({
533 activeWorktreePath,
534 effectiveEnvMode,
535 resolvedActiveBranch,
536 resolvedActiveBranchIsRemote,
537 startFromOrigin,
538 });
539​
540 const branchPrBranch = resolveBranchToolbarPrBranch({
541 activeThreadBranch,
542 resolvedActiveBranch,
543 });
544 const branchPr =
545 branchPrBranch !== null && branchStatusQuery.data?.refName === branchPrBranch
546 ? (branchStatusQuery.data.pr ?? null)
547 : null;
548 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(environmentId);
549 const linkedStatus = useLinkedThreadPullRequest(
550 environmentId,
551 serverThread?.linkedPullRequest,
552 true,
553 serverThread?.pullRequests,
554 serverThread?.branchPullRequest,
555 );
556 const currentLinkedPr = supportsMultiplePullRequests
557 ? resolveThreadCurrentPullRequestLink(serverThread?.pullRequests ?? [])
558 : null;
559 const prBadge = supportsMultiplePullRequests
560 ? resolveThreadPullRequestBadge(serverThread?.pullRequests)
561 : null;
562 const displayedPr = linkedStatus?.pr ?? (currentLinkedPr === null ? branchPr : null);
563 const displayedPrStatus = prStatusIndicator(
564 displayedPr,
565 linkedStatus?.sourceControlProvider ?? branchStatusQuery.data?.sourceControlProvider,
566 );
567 const prNumber = currentLinkedPr?.number ?? displayedPr?.number;
568 const prUrl = currentLinkedPr?.url ?? displayedPr?.url;
569 const openPrLink = useOpenPrLink(threadRef);
570 const panelPrLabel =
571 prNumber === undefined
572 ? ""
573 : `#${prNumber}${displayedPr?.title.trim() ? `: ${displayedPr.title}` : ""}`;
574​
575 function selectPickerItem(itemValue: string) {
576 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
577 handleOpenChange(false);
578 onComposerFocusRequest?.();
579 onCheckoutPullRequestRequest(prReference);
580 } else if (itemValue === createBranchItemValue) {
581 createRef(trimmedBranchQuery);
582 } else {
583 const refName = branchByName.get(itemValue);
584 if (refName) selectBranch(refName);
585 }
586 }
587​
588 function renderPickerItem(itemValue: string, index: number) {
589 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
590 return (
591 <ComboboxItem
592 hideIndicator
593 key={itemValue}
594 index={index}
595 value={itemValue}
596 onClick={() => selectPickerItem(itemValue)}
597 >
598 <div className="flex min-w-0 items-center gap-2 py-1">
599 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
600 <span className="flex min-w-0 flex-col items-start">
601 <span className="truncate font-medium">
602 Checkout {sourceControlPresentation.terminology.singular}
603 </span>
604 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
605 </span>
606 </div>
607 </ComboboxItem>
608 );
609 }
610 if (createBranchItemValue && itemValue === createBranchItemValue) {
611 return (
612 <ComboboxItem
613 hideIndicator
614 key={itemValue}
615 index={index}
616 value={itemValue}
617 onClick={() => selectPickerItem(itemValue)}
618 >
619 <span className="truncate">Create new ref &quot;{newRefName}&quot;</span>
620 </ComboboxItem>
621 );
622 }
623​
624 const refName = branchByName.get(itemValue);
625 if (!refName) return null;
626​
627 return (
628 <BranchPickerRefItem
629 branch={refName}
630 projectCwd={activeProjectCwd}
631 index={index}
632 value={itemValue}
633 disabled={
634 !canUpdateThreadBranch ||
635 (!canWriteSourceControl &&
636 !isSelectingWorktreeBase &&
637 (!activeProjectCwd ||
638 !resolveBranchSelectionTarget({
639 activeProjectCwd,
640 activeWorktreePath,
641 refName,
642 }).reuseExistingWorktree))
643 }
644 onClick={() => selectPickerItem(itemValue)}
645 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
646 />
647 );
648 }
649​
650 return (
651 <BranchPicker
652 items={branchPickerItems}
653 filteredItems={filteredBranchPickerItems}
654 open={isBranchMenuOpen}
655 onOpenChange={handleOpenChange}
656 onSelectItem={selectPickerItem}
657 value={resolvedActiveBranch}
658 query={branchQuery}
659 onQueryChange={setBranchQuery}
660 hasNextPage={hasNextPage}
661 isFetchingNextPage={isFetchingNextPage}
662 onLoadNext={branchRefState.loadNext}
663 statusText={branchStatusText}
664 renderItem={renderPickerItem}
665 getItemType={(item) =>
666 item === checkoutPullRequestItemValue
667 ? "checkout-pull-request"
668 : item === createBranchItemValue
669 ? "create-branch"
670 : "branch"
671 }
672 originControl={
673 isSelectingWorktreeBase
674 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
675 : undefined
676 }
677 popupProps={{
678 align: displayMode === "panel" ? "start" : "end",
679 side: displayMode === "panel" ? "bottom" : "top",
680 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
681 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
682 }}
683 >
684 <div
685 className={cn(
686 "flex min-w-0",
687 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
688 className,
689 )}
690 >
691 {displayMode !== "panel" ? (
692 <ThreadPullRequestBadgeControl
693 render={<ComposerControl size="xs" />}
694 badge={prBadge}
695 pullRequests={serverThread?.pullRequests ?? []}
696 number={prNumber}
697 url={prUrl}
698 status={displayedPrStatus}
699 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
700 onOpenPullRequest={(event, targetUrl = prUrl) => {
701 if (targetUrl) openPrLink(event, targetUrl);
702 }}
703 />
704 ) : null}
705 <span
706 className="flex min-w-0"
707 onMouseDownCapture={(event) => {
708 if (event.button !== 0 || event.ctrlKey) {
709 event.stopPropagation();
710 }
711 }}
712 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
713 >
714 <ComboboxTrigger
715 render={
716 displayMode === "panel" ? (
717 <ThreadDetailsControl part="select" />
718 ) : (
719 <ComposerControl size="xs" />
720 )
721 }
722 className="min-w-0 max-w-full active:scale-100"
723 disabled={isInitialBranchesLoadPending || isBranchActionPending}
724 >
725 <GitBranchIcon
726 className={cn(
727 "size-3 shrink-0",
728 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
729 )}
730 />
731 <ComposerContextLabel displayMode={displayMode}>
732 <MiddleTruncate value={triggerLabel} variant="cap-aligned" className="w-full" />
733 </ComposerContextLabel>
734 </ComboboxTrigger>
735 </span>
736 {displayMode === "panel" && prNumber !== undefined && prUrl !== undefined ? (
737 <ThreadDetailsPrRows
738 threadRef={threadRef}
739 links={serverThread?.pullRequests ?? []}
740 currentLink={currentLinkedPr}
741 onOpenLink={openPrLink}
742 environmentId={environmentId}
743 pr={displayedPr}
744 number={prNumber}
745 reference={currentLinkedPr}
746 status={displayedPrStatus}
747 project={activeProject}
748 label={panelPrLabel}
749 openAriaLabel={prUrl ?? `Open ${sourceControlPresentation.terminology.singular}`}
750 onOpen={(event) => openPrLink(event, prUrl)}
751 onActed={() => branchStatusQuery.refresh()}
752 />
753 ) : null}
754 </div>
755 </BranchPicker>
756 );