@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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