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

BranchToolbarBranchSelector.tsx

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