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

BranchToolbarBranchSelector.tsx

941 lines33.3 KB

1import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2import { contextMenuSourceOf } from "../contextMenuSource";
3import { ComposerContextLabel } from "./ComposerContextLabel";
4import { useRightPanelStore } from "../rightPanelStore";
5import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import {
11 AuthOrchestrationOperateScope,
12 AuthSourceControlWriteScope,
13 type ContextMenuItem,
14 type EnvironmentId,
15 type VcsRef,
16 type ThreadId,
17} from "@t3tools/contracts";
18import { msg, T, useGT, useMessages, Var } from "gt-react";
19import { GitBranchIcon } from "lucide-react";
20import {
21 useEffect,
22 useEffectEvent,
23 useImperativeHandle,
24 useOptimistic,
25 useRef,
26 useState,
27 useTransition,
28 type MouseEvent as ReactMouseEvent,
29 type Ref,
30} from "react";
31​
32import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
33import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
34import { readLocalApi } from "../localApi";
35import { useOpenPrLink } from "../lib/openPullRequestLink";
36import { usePaginatedBranches } from "../state/queries";
37import { useProjectClone } from "../state/projectClones";
38import { readThreadShell, useProject, useQuietThreadShell } from "../state/entities";
39import { useEnvironmentQuery } from "../state/query";
40import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
41import { threadEnvironment } from "../state/threads";
42import { useAtomCommand } from "../state/use-atom-command";
43import { vcsEnvironment } from "../state/vcs";
44import { cn } from "../lib/utils";
45import { THREAD_DETAILS_PANEL_ICON_CLASS } from "./chat/threadDetailsPanelStyles";
46import { ThreadDetailsThreadPrRows } from "./chat/ThreadDetailsPrRows";
47import { ThreadDetailsIssueRows } from "./chat/ThreadDetailsIssueRows";
48import { parsePullRequestReference } from "@t3tools/client-runtime/pull-request-link-input";
49import { getSourceControlPresentation } from "../sourceControlPresentation";
50import { changeRequestTermKind } from "./pullRequest/changeRequestTerm";
51import { useComposerMenuProps } from "./chat/composerEventScope";
52import {
53 type BranchHold,
54 deriveLocalBranchNameFromRemoteRef,
55 isBranchHoldCurrent,
56 isWorktreeChangeBlocked,
57 resolveBranchTriggerLabel,
58 resolveBranchToolbarPrBranch,
59 resolveBranchSelectionTarget,
60 resolveBranchToolbarValue,
61 resolveConfirmedSelectedRef,
62 resolveDefaultWorktreeBaseBranch,
63 resolveDraftEnvModeAfterBranchChange,
64 resolveEffectiveEnvMode,
65 sanitizeNewRefName,
66 shouldIncludeBranchPickerItem,
67 toBranchActionErrorMessage,
68} from "./BranchToolbar.logic";
69import {
70 ThreadPullRequestBadgeControl,
71 resolveDisplayedThreadPr,
72 useThreadDisplayedPullRequest,
73} from "./ThreadStatusIndicators";
74​
75import { ComboboxItem, ComboboxTrigger } from "./ui/combobox";
76import { ComposerControl } from "./chat/ComposerControl";
77import { MiddleTruncate } from "./ui/middle-truncate";
78import { BranchPicker, BranchPickerRefItem } from "./BranchPicker";
79import { stackedThreadToast, toastManager } from "./ui/toast";
80​
81export interface BranchToolbarBranchSelectorHandle {
82 open: () => void;
84​
85interface BranchToolbarBranchSelectorProps {
86 forceNewWorktree?: boolean;
87 ref?: Ref<BranchToolbarBranchSelectorHandle>;
88 className?: string;
89 displayMode?: "toolbar" | "panel";
90 environmentId: EnvironmentId;
91 threadId: ThreadId;
92 draftId?: DraftId;
93 envLocked: boolean;
94 effectiveEnvModeOverride?: "local" | "worktree";
95 activeThreadBranchOverride?: string | null;
96 onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
97 startFromOrigin: boolean;
98 onStartFromOriginChange: (startFromOrigin: boolean) => void;
99 onCheckoutPullRequestRequest?: (reference: string) => void;
100 onComposerFocusRequest?: () => void;
102​
103const WORKTREE_CHANGE_BLOCKED_MESSAGE = msg("Stop the current turn to switch worktrees.");
104​
105// Picker checkouts by environment and checkout: null while in flight, then the branch it landed
106// on. Shared because a draft thread mounts two selectors on one checkout, and the switch's own
107// settle reloads refs for both.
108const pickerCheckouts = new Map<string, string | null>();
109const pickerCheckoutKey = (environmentId: string, cwd: string) => `${environmentId}\u0000${cwd}`;
110​
111export function BranchToolbarBranchSelector({
112 forceNewWorktree = false,
113 ref,
114 className,
115 displayMode = "toolbar",
116 environmentId,
117 threadId,
118 draftId,
119 envLocked,
120 effectiveEnvModeOverride,
121 activeThreadBranchOverride,
122 onActiveThreadBranchOverrideChange,
123 startFromOrigin,
124 onStartFromOriginChange,
125 onCheckoutPullRequestRequest,
126 onComposerFocusRequest,
127}: BranchToolbarBranchSelectorProps) {
128 const gt = useGT();
129 const messages = useMessages();
130 const composerFloatingLayerProps = useComposerMenuProps();
131 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
132 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
133 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
134 const updateThreadMetadata = useAtomCommand(
135 threadEnvironment.updateMetadata,
136 "thread metadata update",
137 );
138 const updateEmptyThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
139 reportFailure: false,
140 });
141 const switchRef = useAtomCommand(vcsEnvironment.switchRef, {
142 reportFailure: false,
143 });
144 const readRefs = useAtomCommand(vcsEnvironment.readRefs, {
145 reportFailure: false,
146 });
147 const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, {
148 reportFailure: false,
149 });
150 const createRefMutation = useAtomCommand(vcsEnvironment.createRef, {
151 reportFailure: false,
152 });
153 const threadRef = scopeThreadRef(environmentId, threadId);
154 const serverThread = useQuietThreadShell(threadRef);
155 const serverSession = serverThread?.runtime ?? null;
156 const draftThread = useComposerDraftStore((store) =>
157 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
158 );
159 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
160​
161 const activeProjectRef = serverThread
162 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
163 : draftThread
164 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
165 : null;
166 const activeProject = useProject(activeProjectRef);
167​
168 const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined);
169 const activeThreadBranch =
170 activeThreadBranchOverride !== undefined
171 ? activeThreadBranchOverride
172 : (serverThread?.branch ?? draftThread?.branch ?? null);
173 const activeWorktreePath = forceNewWorktree
174 ? null
175 : serverThread
176 ? serverThread.worktreePath
177 : (draftThread?.worktreePath ?? null);
178 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
179 const branchCwd = activeWorktreePath ?? activeProjectCwd;
180 const hasServerThread = serverThread !== null;
181 const canUpdateThreadBranch = !hasServerThread || canOperateThread;
182 const canChangeThreadBranch = canWriteSourceControl && canUpdateThreadBranch;
183 const effectiveEnvMode =
184 effectiveEnvModeOverride ??
185 resolveEffectiveEnvMode({
186 activeWorktreePath,
187 hasServerThread,
188 draftThreadEnvMode: draftThread?.envMode,
189 });
190​
191 const readLatestThreadState = () =>
192 readThreadShell(threadRef) ??
193 serverThread ?? { runtime: null, worktreePath: activeWorktreePath };
194​
195 const setThreadBranch = (
196 branch: string | null,
197 worktreePath: string | null,
198 automatic = false,
199 onMetadataFailure?: () => void,
200 ) => {
201 if (
202 !activeThreadId ||
203 !activeProject ||
204 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
205 )
206 return false;
207 const latest = readLatestThreadState();
208 if (automatic && (latest.runtime || latest.worktreePath)) return false;
209 if (
210 isWorktreeChangeBlocked({
211 runtime: latest.runtime,
212 currentWorktreePath: latest.worktreePath,
213 nextWorktreePath: worktreePath,
214 })
215 ) {
216 toastManager.add(
217 stackedThreadToast({ type: "warning", title: messages(WORKTREE_CHANGE_BLOCKED_MESSAGE) }),
218 );
219 return false;
220 }
221 if (latest.runtime && worktreePath !== latest.worktreePath) {
222 void stopThreadSession({
223 environmentId,
224 input: { threadId: activeThreadId },
225 });
226 }
227 if (hasServerThread) {
228 void (automatic ? updateEmptyThreadMetadata : updateThreadMetadata)({
229 environmentId,
230 input: {
231 threadId: activeThreadId,
232 branch,
233 worktreePath,
234 ...(automatic ? { expectedEmpty: true } : {}),
235 },
236 }).then((result) => {
237 if (result._tag !== "Success") onMetadataFailure?.();
238 });
239 }
240 if (hasServerThread) {
241 onActiveThreadBranchOverrideChange?.(branch);
242 return true;
243 }
244 const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
245 nextWorktreePath: worktreePath,
246 currentWorktreePath: activeWorktreePath,
247 effectiveEnvMode,
248 });
249 setDraftThreadContext(draftId ?? threadRef, {
250 branch,
251 worktreePath,
252 envMode: nextDraftEnvMode,
253 environmentSelection: automatic ? (draftThread?.environmentSelection ?? "auto") : "manual",
254 projectRef: scopeProjectRef(environmentId, activeProject.id),
255 });
256 return true;
257 };
258​
259 const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
260 const [branchQuery, setBranchQuery] = useState("");
261​
262 const branchStatusQuery = useEnvironmentQuery(
263 branchCwd === null
264 ? null
265 : vcsEnvironment.status({
266 environmentId,
267 input: { cwd: branchCwd },
268 }),
269 );
270 const projectStatusQuery = useEnvironmentQuery(
271 activeProjectCwd === null
272 ? null
273 : vcsEnvironment.status({ environmentId, input: { cwd: activeProjectCwd } }),
274 );
275 const activeProjectCheckoutRoot = projectStatusQuery.data?.workingTree.rootPath;
276 const trimmedBranchQuery = branchQuery.trim();
277 const branchRefState = usePaginatedBranches(
278 {
279 environmentId,
280 cwd: branchCwd,
281 // Substring search needs sanitized names to detect new-branch collisions; refs cannot contain ASCII
282 // spaces.
283 query: sanitizeNewRefName(trimmedBranchQuery),
284 },
285 messages,
286 );
287 const refs = branchRefState.refs;
288 const branchByName = new Map(refs.map((refName) => [refName.name, refName] as const));
289 const normalizedBranchQuery = trimmedBranchQuery.toLowerCase();
290 const prReference = parsePullRequestReference(trimmedBranchQuery);
291 const isSelectingWorktreeBase =
292 effectiveEnvMode === "worktree" && !envLocked && !activeWorktreePath;
293 const isWorktreeChangeBlockedForRef = (refName: VcsRef) =>
294 activeProjectCwd !== null &&
295 isWorktreeChangeBlocked({
296 runtime: serverSession,
297 currentWorktreePath: serverThread ? serverThread.worktreePath : activeWorktreePath,
298 nextWorktreePath: isSelectingWorktreeBase
299 ? null
300 : resolveBranchSelectionTarget({
301 activeProjectCwd,
302 activeProjectCheckoutRoot,
303 activeWorktreePath,
304 refName,
305 }).nextWorktreePath,
306 });
307 const checkoutPullRequestItemValue =
308 canChangeThreadBranch && prReference && onCheckoutPullRequestRequest
309 ? `__checkout_pull_request__:${prReference}`
310 : null;
311 const canCreateBranch =
312 canChangeThreadBranch && !isSelectingWorktreeBase && trimmedBranchQuery.length > 0;
313 const newRefName = sanitizeNewRefName(trimmedBranchQuery);
314 const hasExactBranchMatch = branchByName.has(newRefName);
315 const createBranchItemValue = canCreateBranch
316 ? `__create_new_branch__:${trimmedBranchQuery}`
317 : null;
318 const pickerCreateBranchItemValue = hasExactBranchMatch ? null : createBranchItemValue;
319 const branchPickerItems = [
320 ...(checkoutPullRequestItemValue ? [checkoutPullRequestItemValue] : []),
321 ...refs.map((refName) => refName.name),
322 ...(pickerCreateBranchItemValue ? [pickerCreateBranchItemValue] : []),
323 ];
324 const filteredBranchPickerItems =
325 normalizedBranchQuery.length === 0
326 ? branchPickerItems
327 : branchPickerItems.filter((itemValue) =>
328 shouldIncludeBranchPickerItem({
329 itemValue,
330 normalizedQuery: normalizedBranchQuery,
331 createBranchItemValue: pickerCreateBranchItemValue,
332 checkoutPullRequestItemValue,
333 }),
334 );
335 const hasNextPage =
336 branchRefState.data?.nextCursor !== null && branchRefState.data?.nextCursor !== undefined;
337 const isFetchingNextPage = branchRefState.isFetchingNextPage;
338 const isInitialBranchesLoadPending = branchRefState.isPending && branchRefState.data === null;
339 const currentGitBranch =
340 branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
341 const sourceControlPresentation = getSourceControlPresentation(
342 branchStatusQuery.data?.sourceControlProvider,
343 );
344 const SourceControlIcon = sourceControlPresentation.Icon;
345 const canonicalActiveBranch = resolveBranchToolbarValue({
346 envMode: effectiveEnvMode,
347 activeWorktreePath,
348 activeThreadBranch,
349 currentGitBranch,
350 });
351 const [branchHold, setBranchHold] = useState<BranchHold | null>(null);
352 const branchHoldCurrent =
353 branchHold !== null &&
354 isBranchHoldCurrent(branchHold, {
355 canonicalBranch: canonicalActiveBranch,
356 environmentId,
357 cwd: branchCwd,
358 });
359 if (branchHold !== null && !branchHoldCurrent) setBranchHold(null);
360 const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
361 branchHoldCurrent ? branchHold.branch : canonicalActiveBranch,
362 (_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
363 );
364 const listedActiveBranch =
365 resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
366 const activeBranchRefQuery = useEnvironmentQuery(
367 branchCwd !== null && resolvedActiveBranch !== null
368 ? vcsEnvironment.listRefs({
369 environmentId,
370 input: {
371 cwd: branchCwd,
372 query: resolvedActiveBranch,
373 limit: 10,
374 },
375 })
376 : null,
377 );
378 const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
379 (refName) => refName.name === resolvedActiveBranch,
380 );
381 const resolvedActiveBranchIsRemote =
382 listedActiveBranch !== null
383 ? listedActiveBranch.isRemote === true
384 : queriedActiveBranch
385 ? queriedActiveBranch.isRemote === true
386 : null;
387 const [isBranchActionPending, startBranchActionTransition] = useTransition();
388 const totalBranchCount = branchRefState.data?.totalCount ?? 0;
389 const branchStatusText = isInitialBranchesLoadPending
390 ? gt("Loading refs...")
391 : isFetchingNextPage
392 ? gt("Loading more refs...")
393 : hasNextPage
394 ? gt(
395 "{total, plural, one {Showing {shown} of {total} refs} other {Showing {shown} of {total} refs}}",
396 { shown: refs.length, total: totalBranchCount },
397 )
398 : null;
399​
400 const copyBranchName = (branchName: string) => {
401 void writeTextToClipboard(branchName, {
402 target: "branch name",
403 unavailableMessage: msg("Clipboard API is unavailable while copying branch name."),
404 failureMessage: msg("Failed to copy branch name to the clipboard."),
405 }).then(undefined, (error: unknown) => {
406 toastManager.add(
407 stackedThreadToast({
408 type: "error",
409 title: gt("Failed to copy branch name"),
410 description: toBranchActionErrorMessage(error),
411 }),
412 );
413 });
414 };
415​
416 const handleBranchContextMenu = (event: ReactMouseEvent, branchName: string | null) => {
417 if (!branchName) return;
418 const api = readLocalApi();
419 if (!api) return;
420 event.preventDefault();
421 event.stopPropagation();
422 const items: ContextMenuItem<"copy-branch-name">[] = [
423 { id: "copy-branch-name", label: gt("Copy branch name"), icon: "copy" },
424 ];
425 void api.contextMenu
426 .show(items, { x: event.clientX, y: event.clientY }, contextMenuSourceOf(event))
427 .then((action) => {
428 if (action === "copy-branch-name") copyBranchName(branchName);
429 });
430 };
431​
432 const runBranchAction = (action: () => Promise<void>) => {
433 if (
434 !readEnvironmentScope(environmentId, AuthSourceControlWriteScope) ||
435 (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
436 ) {
437 toastManager.add(
438 stackedThreadToast({
439 type: "error",
440 title: gt("Action unavailable"),
441 description: gt("This connection cannot change the thread's branch."),
442 }),
443 );
444 return;
445 }
446 startBranchActionTransition(async () => {
447 await action();
448 branchRefState.refresh();
449 });
450 };
451​
452 // The picker's list, and the server's coalesced ref listing, can predate a checkout an agent
453 // ran itself. Only the claimed worktree's live HEAD confirms the claim; an unconfirmed one
454 // falls back to a real checkout, which Git refuses if the branch is checked out elsewhere.
455 const latestSelectionIdRef = useRef(0);
456 const readSelectedRef = async (worktreePath: string, listedRef: VcsRef): Promise<VcsRef> => {
457 const result = await readRefs({
458 environmentId,
459 input: { cwd: worktreePath, query: listedRef.name, refKind: "local", limit: 1 },
460 });
461 return resolveConfirmedSelectedRef(listedRef, result._tag === "Success" ? result.value : null);
462 };
463​
464 const selectBranch = async (listedRef: VcsRef) => {
465 if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
466 const selectionId = ++latestSelectionIdRef.current;
467​
468 let latest = readLatestThreadState();
469 if (isSelectingWorktreeBase) {
470 if (latest.worktreePath) return;
471 setThreadBranch(listedRef.name, null);
472 setIsBranchMenuOpen(false);
473 onComposerFocusRequest?.();
474 return;
475 }
476​
477 setIsBranchMenuOpen(false);
478 onComposerFocusRequest?.();
479​
480 const refName = listedRef.worktreePath
481 ? await readSelectedRef(listedRef.worktreePath, listedRef)
482 : listedRef;
483 // A later pick made while this one was confirming its worktree wins.
484 if (selectionId !== latestSelectionIdRef.current) return;
485 latest = readLatestThreadState();
486 const selectionTarget = resolveBranchSelectionTarget({
487 activeProjectCwd,
488 activeProjectCheckoutRoot,
489 activeWorktreePath: latest.worktreePath,
490 refName,
491 });
492​
493 if (
494 isWorktreeChangeBlocked({
495 runtime: latest.runtime,
496 currentWorktreePath: latest.worktreePath,
497 nextWorktreePath: selectionTarget.nextWorktreePath,
498 })
499 )
500 return;
501​
502 if (
503 selectionTarget.reuseExistingWorktree &&
504 !(selectionTarget.staysInActiveCheckout && canWriteSourceControl)
505 ) {
506 setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
507 return;
508 }
509​
510 const selectedBranchName = refName.isRemote
511 ? deriveLocalBranchNameFromRemoteRef(refName.name, refName.remoteName)
512 : refName.name;
513​
514 runBranchAction(async () => {
515 const previousBranch = resolvedActiveBranch;
516 setOptimisticBranch(selectedBranchName);
517 const checkoutKey = pickerCheckoutKey(environmentId, selectionTarget.checkoutCwd);
518 pickerCheckouts.set(checkoutKey, null);
519 const checkoutResult = await switchRef({
520 environmentId,
521 input: {
522 cwd: selectionTarget.checkoutCwd,
523 refName: refName.name,
524 },
525 });
526 if (checkoutResult._tag === "Success") {
527 const nextBranchName = refName.isRemote
528 ? (checkoutResult.value.refName ?? selectedBranchName)
529 : selectedBranchName;
530 pickerCheckouts.set(checkoutKey, nextBranchName);
531 const movesCheckout = selectionTarget.checkoutCwd !== branchCwd;
532 let hold: BranchHold | null = null;
533 const applied = setThreadBranch(
534 nextBranchName,
535 selectionTarget.nextWorktreePath,
536 false,
537 // A failed move leaves the thread in its old checkout, which never had the new branch.
538 movesCheckout
539 ? () => setBranchHold((current) => (current === hold ? null : current))
540 : undefined,
541 );
542 if (applied) {
543 hold = {
544 branch: nextBranchName,
545 environmentId,
546 // The thread keeps its old checkout until the metadata update moves it to the new one.
547 checkouts: [
548 { cwd: branchCwd, replaces: canonicalActiveBranch },
549 ...(movesCheckout
550 ? [
551 {
552 cwd: selectionTarget.checkoutCwd,
553 replaces: projectStatusQuery.data?.refName ?? null,
554 },
555 ]
556 : []),
557 ],
558 };
559 setBranchHold(hold);
560 }
561 setOptimisticBranch(applied ? nextBranchName : previousBranch);
562 return;
563 }
564 pickerCheckouts.delete(checkoutKey);
565 setOptimisticBranch(previousBranch);
566 if (!isAtomCommandInterrupted(checkoutResult)) {
567 toastManager.add(
568 stackedThreadToast({
569 type: "error",
570 title: gt("Failed to switch ref."),
571 description: toBranchActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
572 }),
573 );
574 }
575 });
576 };
577​
578 const createRef = (rawName: string) => {
579 if (!canChangeThreadBranch) return;
580 const name = sanitizeNewRefName(rawName);
581 if (!branchCwd || !name || isBranchActionPending) return;
582 latestSelectionIdRef.current++;
583​
584 setIsBranchMenuOpen(false);
585 onComposerFocusRequest?.();
586​
587 runBranchAction(async () => {
588 const previousBranch = resolvedActiveBranch;
589 setOptimisticBranch(name);
590 const checkoutKey = pickerCheckoutKey(environmentId, branchCwd);
591 pickerCheckouts.set(checkoutKey, null);
592 const createBranchResult = await createRefMutation({
593 environmentId,
594 input: {
595 cwd: branchCwd,
596 refName: name,
597 switchRef: true,
598 },
599 });
600 if (createBranchResult._tag === "Success") {
601 const nextBranchName = createBranchResult.value.refName;
602 pickerCheckouts.set(checkoutKey, nextBranchName);
603 const applied = setThreadBranch(nextBranchName, activeWorktreePath);
604 if (applied) {
605 setBranchHold({
606 branch: nextBranchName,
607 environmentId,
608 checkouts: [{ cwd: branchCwd, replaces: canonicalActiveBranch }],
609 });
610 }
611 setOptimisticBranch(applied ? nextBranchName : previousBranch);
612 return;
613 }
614 pickerCheckouts.delete(checkoutKey);
615 setOptimisticBranch(previousBranch);
616 if (!isAtomCommandInterrupted(createBranchResult)) {
617 toastManager.add(
618 stackedThreadToast({
619 type: "error",
620 title: gt("Failed to create and switch ref."),
621 description: toBranchActionErrorMessage(squashAtomCommandFailure(createBranchResult)),
622 }),
623 );
624 }
625 });
626 };
627​
628 const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
629 ? null
630 : resolveDefaultWorktreeBaseBranch(refs);
631​
632 const projectCloneDone = useProjectClone(activeProjectRef)?.phase === "done";
633 const refreshStaleRefs = useEffectEvent(() => {
634 if (branchCwd === null) return;
635 void refreshLocalStatusForPicker({
636 environmentId,
637 input: { cwd: branchCwd },
638 });
639 });
640 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refs listed while the project was cloning are empty; reload them past the server's snapshot when the clone finishes
641 useEffect(() => {
642 if (projectCloneDone) refreshStaleRefs();
643 }, [projectCloneDone]);
644 // A checkout made outside T3 Code, such as a clone finishing, leaves refs listed before it.
645 const statusBranch = branchStatusQuery.data?.refName ?? null;
646 const refreshRefsMissingStatusBranch = useEffectEvent((branch: string | null) => {
647 if (branch === null || branchCwd === null) return;
648 // Kept until the checkout reports another branch, so every selector on it skips the refresh.
649 const checkoutKey = pickerCheckoutKey(environmentId, branchCwd);
650 if (pickerCheckouts.has(checkoutKey)) {
651 const pickerBranch = pickerCheckouts.get(checkoutKey);
652 if (pickerBranch === null || pickerBranch === branch) return;
653 pickerCheckouts.delete(checkoutKey);
654 }
655 if (isInitialBranchesLoadPending) return;
656 if (branchByName.get(branch)?.current !== true) refreshStaleRefs();
657 });
658 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reloads refs from the server once per branch live status reports that they do not list as checked out
659 useEffect(() => {
660 refreshRefsMissingStatusBranch(statusBranch);
661 }, [statusBranch]);
662​
663 // The server sets started threads' branches; defaulting here would detach the agent from its worktree.
664 const threadStarted = serverSession !== null;
665 // 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
666 useEffect(() => {
667 if (
668 threadStarted ||
669 effectiveEnvMode !== "worktree" ||
670 activeWorktreePath ||
671 activeThreadBranch ||
672 !worktreeBaseBranchCandidate
673 ) {
674 return;
675 }
676 setThreadBranch(worktreeBaseBranchCandidate, null, true);
677 }, [
678 activeThreadBranch,
679 activeWorktreePath,
680 effectiveEnvMode,
681 setThreadBranch,
682 threadStarted,
683 worktreeBaseBranchCandidate,
684 ]);
685​
686 const handleOpenChange = (open: boolean) => {
687 setIsBranchMenuOpen(open);
688 if (open && !isBranchMenuOpen && branchCwd !== null) {
689 void refreshLocalStatusForPicker({
690 environmentId,
691 input: { cwd: branchCwd },
692 });
693 }
694 if (!open) {
695 setBranchQuery("");
696 }
697 };
698​
699 useImperativeHandle(
700 ref,
701 () => ({
702 open: () => {
703 if (isInitialBranchesLoadPending || isBranchActionPending) return;
704 handleOpenChange(true);
705 },
706 }),
707 [handleOpenChange, isBranchActionPending, isInitialBranchesLoadPending],
708 );
709​
710 const triggerLabel = resolveBranchTriggerLabel(
711 {
712 activeWorktreePath,
713 effectiveEnvMode,
714 resolvedActiveBranch,
715 resolvedActiveBranchIsRemote,
716 startFromOrigin,
717 },
718 messages,
719 );
720​
721 const branchPrBranch = resolveBranchToolbarPrBranch({
722 activeThreadBranch,
723 resolvedActiveBranch,
724 });
725 const branchPr = resolveDisplayedThreadPr({
726 threadBranch: branchPrBranch,
727 gitStatus: branchStatusQuery.data,
728 });
729 const {
730 badge: prBadge,
731 number: prNumber,
732 url: prUrl,
733 status: prStatus,
734 } = useThreadDisplayedPullRequest(
735 environmentId,
736 serverThread,
737 branchPr,
738 branchStatusQuery.data?.sourceControlProvider,
739 );
740 const openPrLink = useOpenPrLink(threadRef);
741 const linkedIssues = serverThread?.issues ?? [];
742​
743 function selectPickerItem(itemValue: string) {
744 if (itemValue === checkoutPullRequestItemValue && prReference && onCheckoutPullRequestRequest) {
745 latestSelectionIdRef.current++;
746 handleOpenChange(false);
747 onComposerFocusRequest?.();
748 onCheckoutPullRequestRequest(prReference);
749 } else if (itemValue === createBranchItemValue) {
750 createRef(trimmedBranchQuery);
751 } else {
752 const refName = branchByName.get(itemValue);
753 if (refName) void selectBranch(refName);
754 }
755 }
756​
757 function renderPickerItem(itemValue: string, index: number) {
758 if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
759 return (
760 <ComboboxItem
761 hideIndicator
762 key={itemValue}
763 index={index}
764 value={itemValue}
765 onClick={() => selectPickerItem(itemValue)}
766 >
767 <div className="flex min-w-0 items-center gap-2 py-1">
768 <SourceControlIcon className="size-3.5 shrink-0 text-muted-foreground" />
769 <span className="flex min-w-0 flex-col items-start">
770 <span className="truncate font-medium">
771 {gt(
772 "Checkout {term, select, mr {merge request} cr {change request} other {pull request}}",
773 { term: changeRequestTermKind(sourceControlPresentation.terminology) },
774 )}
775 </span>
776 <span className="truncate text-muted-foreground text-xs">{prReference}</span>
777 </span>
778 </div>
779 </ComboboxItem>
780 );
781 }
782 if (createBranchItemValue && itemValue === createBranchItemValue) {
783 return (
784 <ComboboxItem
785 hideIndicator
786 key={itemValue}
787 index={index}
788 value={itemValue}
789 onClick={() => selectPickerItem(itemValue)}
790 >
791 <span className="truncate">
792 <T>
793 Create new ref &quot;<Var>{newRefName}</Var>&quot;
794 </T>
795 </span>
796 </ComboboxItem>
797 );
798 }
799​
800 const refName = branchByName.get(itemValue);
801 if (!refName) return null;
802​
803 return (
804 <BranchPickerRefItem
805 branch={refName}
806 projectCwd={activeProjectCwd}
807 index={index}
808 value={itemValue}
809 disabled={
810 !canUpdateThreadBranch ||
811 (!canWriteSourceControl &&
812 !isSelectingWorktreeBase &&
813 (!activeProjectCwd ||
814 !resolveBranchSelectionTarget({
815 activeProjectCwd,
816 activeProjectCheckoutRoot,
817 activeWorktreePath,
818 refName,
819 }).reuseExistingWorktree)) ||
820 isWorktreeChangeBlockedForRef(refName)
821 }
822 onClick={() => selectPickerItem(itemValue)}
823 onContextMenu={(event) => handleBranchContextMenu(event, itemValue)}
824 />
825 );
826 }
827​
828 return (
829 <BranchPicker
830 items={branchPickerItems}
831 filteredItems={filteredBranchPickerItems}
832 open={isBranchMenuOpen}
833 onOpenChange={handleOpenChange}
834 onSelectItem={selectPickerItem}
835 value={resolvedActiveBranch}
836 query={branchQuery}
837 onQueryChange={setBranchQuery}
838 hasNextPage={hasNextPage}
839 isFetchingNextPage={isFetchingNextPage}
840 onLoadNext={branchRefState.loadNext}
841 statusText={branchStatusText}
842 notice={
843 refs.some((refName) => isWorktreeChangeBlockedForRef(refName))
844 ? messages(WORKTREE_CHANGE_BLOCKED_MESSAGE)
845 : null
846 }
847 renderItem={renderPickerItem}
848 getItemType={(item) =>
849 item === checkoutPullRequestItemValue
850 ? "checkout-pull-request"
851 : item === createBranchItemValue
852 ? "create-branch"
853 : "branch"
854 }
855 originControl={
856 isSelectingWorktreeBase
857 ? { checked: startFromOrigin, onCheckedChange: onStartFromOriginChange }
858 : undefined
859 }
860 popupProps={{
861 align: displayMode === "panel" ? "start" : "end",
862 side: displayMode === "panel" ? "bottom" : "top",
863 className: cn("flex flex-col", displayMode === "panel" ? "w-(--anchor-width)" : "w-80"),
864 ...(displayMode === "toolbar" ? composerFloatingLayerProps : {}),
865 }}
866 >
867 <div
868 className={cn(
869 "flex min-w-0",
870 displayMode === "panel" ? "w-full flex-col items-stretch" : "items-center gap-1",
871 className,
872 )}
873 >
874 {displayMode !== "panel" ? (
875 <ThreadPullRequestBadgeControl
876 render={<ComposerControl size="xs" />}
877 badge={prBadge}
878 pullRequests={serverThread?.pullRequests ?? []}
879 number={prNumber}
880 url={prUrl}
881 status={prStatus}
882 onOpenList={() => useRightPanelStore.getState().open(threadRef, "pull-requests")}
883 onOpenPullRequest={(event, targetUrl = prUrl) => {
884 if (targetUrl) openPrLink(event, targetUrl);
885 }}
886 />
887 ) : null}
888 <span
889 className="flex min-w-0"
890 onMouseDownCapture={(event) => {
891 if (event.button !== 0 || event.ctrlKey) {
892 event.stopPropagation();
893 }
894 }}
895 onContextMenu={(event) => handleBranchContextMenu(event, resolvedActiveBranch)}
896 >
897 <ComboboxTrigger
898 render={
899 displayMode === "panel" ? (
900 <ThreadDetailsControl part="select" />
901 ) : (
902 <ComposerControl size="xs" />
903 )
904 }
905 className="min-w-0 max-w-full active:scale-100"
906 disabled={isInitialBranchesLoadPending || isBranchActionPending}
907 // NVDA browse mode re-reads a combobox when its attributes change, not when its text does.
908 aria-label={gt("Branch: {branch}", { branch: triggerLabel })}
909 >
910 <GitBranchIcon
911 className={cn(
912 "size-3 shrink-0",
913 displayMode === "panel" && THREAD_DETAILS_PANEL_ICON_CLASS,
914 )}
915 />
916 <ComposerContextLabel displayMode={displayMode}>
917 <MiddleTruncate
918 value={triggerLabel}
919 variant="cap-aligned"
920 className="w-full"
921 aria-hidden
922 />
923 </ComposerContextLabel>
924 </ComboboxTrigger>
925 </span>
926 {displayMode === "panel" ? (
927 <ThreadDetailsThreadPrRows
928 threadRef={threadRef}
929 project={activeProject}
930 branchPr={branchPr}
931 branchSourceControlProvider={branchStatusQuery.data?.sourceControlProvider}
932 onActed={() => branchStatusQuery.refresh()}
933 />
934 ) : null}
935 {displayMode === "panel" ? (
936 <ThreadDetailsIssueRows links={linkedIssues} threadRef={threadRef} />
937 ) : null}
938 </div>
939 </BranchPicker>
940 );