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