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