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

BranchToolbar.tsx

871 lines32.8 KB

1import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
2import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
3import { readLocalApi } from "../localApi";
4import { stackedThreadToast, toastManager } from "./ui/toast";
5import { ComposerContextLabel } from "./ComposerContextLabel";
6import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
7import type { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
8import {
9 ChevronDownIcon,
10 FolderGit2Icon,
11 FolderGitIcon,
12 FolderIcon,
13 PlusIcon,
14 ScaleIcon,
15} from "lucide-react";
16import {
17 type Ref,
18 type MouseEvent as ReactMouseEvent,
19 memo,
20 useImperativeHandle,
21 useRef,
22 useState,
23} from "react";
24import { flushSync } from "react-dom";
25​
26import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
27import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
28import { useProject, useThreadShellsForProjectRefs } from "../state/entities";
29import {
30 ADD_TO_MACHINE_LABEL_CLASS,
31 type EnvMode,
32 type EnvironmentOption,
33 resolveContextStripLabelsCompact,
34 resolveCurrentWorkspaceLabel,
35 resolveEnvModeLabel,
36 resolveLockedWorkspaceLabel,
37 resolvePreviousWorktreeLabel,
38 resolvePreviousWorktreeSeed,
39 shouldShowEnvironmentIndicator,
40} from "./BranchToolbar.logic";
41import {
42 BranchToolbarBranchSelector,
43 type BranchToolbarBranchSelectorHandle,
44} from "./BranchToolbarBranchSelector";
45import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
46import { openAddProjectToMachine } from "./AddProjectToMachineDialog";
47import { type AddProjectTarget, useAddProjectTargets } from "../hooks/useAddProjectTargets";
48import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
49import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
50import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
51import {
52 THREAD_DETAILS_PANEL_ICON_CLASS,
53 THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
54} from "./chat/threadDetailsPanelStyles";
55import { ComposerControl } from "./chat/ComposerControl";
56import {
57 Menu,
58 MenuGroup,
59 MenuGroupLabel,
60 MenuItem,
61 MenuPopup,
62 MenuRadioGroup,
63 MenuRadioItem,
64 MenuSeparator,
65 MenuSub,
66 MenuSubPopup,
67 MenuSubTrigger,
68 MenuTrigger,
69} from "./ui/menu";
70import { Separator } from "./ui/separator";
71import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
72import { MiddleTruncate } from "./ui/middle-truncate";
73import { ComposerSurface } from "./chat/ComposerSurface";
74import { useComposerMenuProps } from "./chat/composerEventScope";
75import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement";
76import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout";
77import { cn } from "~/lib/utils";
78import { observeResize } from "~/lib/observeResize";
79​
80export interface BranchToolbarHandle {
81 openBranchPicker: () => void;
82 usePreviousWorktree: () => void;
84​
85interface BranchToolbarProps {
86 layout?: "composer" | "panel";
87 panelSection?: "all" | "workspace" | "branch";
88 forceNewWorktree?: boolean;
89 ref?: Ref<BranchToolbarHandle>;
90 environmentId: EnvironmentId;
91 threadId: ThreadId;
92 projectId: ProjectId;
93 worktreePath: string | null;
94 isServerThread: boolean;
95 showGitControls: boolean;
96 draftId?: DraftId;
97 onEnvModeChange: (mode: EnvMode) => void;
98 envMode: EnvMode;
99 activeThreadBranchOverride?: string | null;
100 onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
101 startFromOrigin: boolean;
102 onStartFromOriginChange: (startFromOrigin: boolean) => void;
103 autoEnvironmentLabel?: string | undefined;
104 onAutoEnvironment?: (() => void) | undefined;
105 envLocked: boolean;
106 onCheckoutPullRequestRequest?: (reference: string) => void;
107 onComposerFocusRequest?: () => void;
108 availableEnvironments?: readonly EnvironmentOption[];
109 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
110 composerControlsHostRef?: (element: HTMLDivElement | null) => void;
111 contextStripVisible?: boolean;
113​
114function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) {
115 const api = readLocalApi();
116 if (!api) return;
117 event.preventDefault();
118 event.stopPropagation();
119 void api.contextMenu
120 .show([{ id: "copy-path", label: "Copy full path", icon: "copy" }], {
121 x: event.clientX,
122 y: event.clientY,
123 })
124 .then((action) => {
125 if (action !== "copy-path") return;
126 const clipboardPath = formatFilePathForClipboard(workspacePath);
127 void writeTextToClipboard(clipboardPath, "workspace path").then(
128 (didCopy) => {
129 if (didCopy) {
130 toastManager.add({
131 type: "success",
132 title: "Path copied",
133 description: clipboardPath,
134 });
135 }
136 },
137 (error: unknown) => {
138 toastManager.add(
139 stackedThreadToast({
140 type: "error",
141 title: "Failed to copy path",
142 description: error instanceof Error ? error.message : "An error occurred.",
143 }),
144 );
145 },
146 );
147 });
149​
150interface RunContextSelectorProps {
151 displayMode?: "toolbar" | "panel";
152 workspaceRoot?: string;
153 forceNewWorktree: boolean;
154 autoEnvironmentLabel?: string | undefined;
155 onAutoEnvironment?: (() => void) | undefined;
156 envLocked: boolean;
157 envModeLocked: boolean;
158 environmentId: EnvironmentId;
159 availableEnvironments: readonly EnvironmentOption[] | undefined;
160 showEnvironmentPicker: boolean;
161 showEnvironmentIndicator: boolean;
162 onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
163 effectiveEnvMode: EnvMode;
164 activeWorktreePath: string | null;
165 onEnvModeChange: (mode: EnvMode) => void;
166 previousWorktreeLabel: string | null;
167 previousWorktreeBranch: string | null;
168 onUsePreviousWorktree: () => void;
169 addTargets: readonly AddProjectTarget[];
170 onAddToMachine: (environmentId: EnvironmentId) => void;
172​
173const RunContextSelector = memo(function RunContextSelector({
174 displayMode = "toolbar",
175 workspaceRoot,
176 forceNewWorktree,
177 autoEnvironmentLabel,
178 onAutoEnvironment,
179 envLocked,
180 envModeLocked,
181 environmentId,
182 availableEnvironments,
183 showEnvironmentPicker,
184 showEnvironmentIndicator,
185 onEnvironmentChange,
186 effectiveEnvMode,
187 activeWorktreePath,
188 onEnvModeChange,
189 previousWorktreeLabel,
190 previousWorktreeBranch,
191 onUsePreviousWorktree,
192 addTargets,
193 onAddToMachine,
194}: RunContextSelectorProps) {
195 const composerFloatingLayerProps = useComposerMenuProps();
196 const activeEnvironment =
197 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
198 const WorkspaceIcon =
199 effectiveEnvMode === "worktree"
200 ? FolderGit2Icon
201 : activeWorktreePath
202 ? FolderGitIcon
203 : FolderIcon;
204 const workspaceLabel = forceNewWorktree
205 ? resolveEnvModeLabel("worktree")
206 : envModeLocked
207 ? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode)
208 : effectiveEnvMode === "worktree"
209 ? resolveEnvModeLabel("worktree")
210 : resolveCurrentWorkspaceLabel(activeWorktreePath);
211 const isPanel = displayMode === "panel";
212 const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker));
213 const workspacePath =
214 forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath)
215 ? null
216 : (activeWorktreePath ?? workspaceRoot);
217 const handleContextMenu = (event: ReactMouseEvent) => {
218 if (isPanel && workspacePath) {
219 showWorkspaceContextMenu(event, workspacePath);
220 }
221 };
222 const workspaceIcon = (
223 <Tooltip>
224 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
225 <WorkspaceIcon
226 className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0 mx-0!"}
227 />
228 </TooltipTrigger>
229 <TooltipPopup>
230 {isPanel
231 ? forceNewWorktree
232 ? "Each model starts in its own worktree."
233 : (workspacePath ?? workspaceLabel)
234 : workspaceLabel}
235 </TooltipPopup>
236 </Tooltip>
237 );
238 const environmentIcon = (
239 <Tooltip>
240 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
241 {autoEnvironmentLabel ? (
242 <ScaleIcon
243 className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0 mx-0!"}
244 aria-hidden="true"
245 />
246 ) : (
247 <EnvironmentMachineIcon
248 kind={activeEnvironment?.machine ?? "server"}
249 // Wide machine glyphs need a little more box to match the square row icons.
250 className={
251 isPanel
252 ? cn(THREAD_DETAILS_PANEL_ICON_CLASS, "-mx-px size-4.5")
253 : "size-3 shrink-0 mx-0!"
254 }
255 />
256 )}
257 </TooltipTrigger>
258 <TooltipPopup>{autoEnvironmentLabel ?? activeEnvironment?.label ?? "Run on"}</TooltipPopup>
259 </Tooltip>
260 );
261 const icon = !showEnvironmentIndicator ? (
262 workspaceIcon
263 ) : isPanel ? (
264 environmentIcon
265 ) : (
266 // Button's SVG margins consume 4px of the gap; mx-0! restores the intended 2px.
267 <span className="inline-flex shrink-0 items-center gap-0.5">
268 {environmentIcon}
269 {workspaceIcon}
270 </span>
271 );
272 const triggerContent = (
273 <>
274 {icon}
275 <ComposerContextLabel displayMode={displayMode}>
276 {autoEnvironmentLabel ??
277 (showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel)}
278 </ComposerContextLabel>
279 {/* Trailing in the panel, so every row label starts on the same edge. */}
280 {isPanel && showEnvironmentIndicator ? workspaceIcon : null}
281 </>
282 );
283​
284 if (isLocked) {
285 return (
286 <span
287 className={cn(
288 "inline-flex h-7 min-w-0 max-w-[48%] flex-initial items-center justify-start gap-1 rounded-md border border-transparent px-1.75 font-normal text-foreground/70 text-xs sm:h-6 dark:text-muted-foreground",
289 isPanel && "max-w-full",
290 isPanel && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
291 )}
292 onContextMenu={handleContextMenu}
293 aria-label={isPanel ? "Run context" : undefined}
294 data-composer-context-control
295 >
296 {triggerContent}
297 </span>
298 );
299 }
300​
301 return (
302 <Menu>
303 <MenuTrigger
304 render={isPanel ? <ThreadDetailsControl part="select" /> : <ComposerControl size="xs" />}
305 className={isPanel ? undefined : "min-w-0 max-w-[48%] flex-initial justify-start"}
306 onContextMenu={handleContextMenu}
307 onMouseDownCapture={
308 isPanel
309 ? (event) => {
310 if (event.button !== 0 || event.ctrlKey) event.stopPropagation();
311 }
312 : undefined
313 }
314 aria-label={isPanel ? "Run context" : undefined}
315 data-composer-context-control
316 data-composer-shortcut={[
317 showEnvironmentPicker && !envLocked ? "composer.host" : "",
318 !envModeLocked ? "composer.workspace" : "",
319 ].join(" ")}
320 >
321 {triggerContent}
322 {!isPanel ? <ChevronDownIcon className="size-3 shrink-0 mx-0!" /> : null}
323 </MenuTrigger>
324 <MenuPopup
325 align="start"
326 side={isPanel ? "bottom" : "top"}
327 className={
328 isPanel
329 ? "w-(--anchor-width)"
330 : previousWorktreeLabel
331 ? "w-[min(21rem,calc(100vw-2rem))]"
332 : undefined
333 }
334 {...(!isPanel ? composerFloatingLayerProps : {})}
335 >
336 {availableEnvironments &&
337 ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) ? (
338 <>
339 <MenuGroup>
340 <MenuGroupLabel>Run on</MenuGroupLabel>
341 <MenuRadioGroup
342 value={autoEnvironmentLabel ? "auto" : environmentId}
343 onValueChange={(value) =>
344 value === "auto"
345 ? onAutoEnvironment?.()
346 : onEnvironmentChange?.(value as EnvironmentId)
347 }
348 >
349 {onAutoEnvironment && (
350 <MenuRadioItem
351 value="auto"
352 disabled={envLocked}
353 closeOnClick
354 onClick={() => {
355 if (autoEnvironmentLabel) onAutoEnvironment?.();
356 }}
357 >
358 <span className="flex min-w-0 items-center gap-1.5">
359 <ScaleIcon className="size-3" aria-hidden="true" />
360 <span className="min-w-0 truncate">
361 {autoEnvironmentLabel ?? "Auto balance"}
362 </span>
363 </span>
364 </MenuRadioItem>
365 )}
366 {availableEnvironments.map((env) => (
367 <MenuRadioItem
368 key={env.environmentId}
369 disabled={
370 envLocked || (!onEnvironmentChange && env.environmentId !== environmentId)
371 }
372 value={env.environmentId}
373 closeOnClick
374 >
375 <span className="flex min-w-0 items-center gap-1.5">
376 <EnvironmentMachineIcon kind={env.machine} className="size-3" />
377 <span className="min-w-0 truncate">{env.label}</span>
378 </span>
379 </MenuRadioItem>
380 ))}
381 </MenuRadioGroup>
382 {addTargets.length > 0 ? (
383 <MenuSub>
384 <MenuSubTrigger>
385 <span className={ADD_TO_MACHINE_LABEL_CLASS}>
386 <PlusIcon className="size-3" />
387 <span className="min-w-0 truncate">Add to another machine</span>
388 </span>
389 </MenuSubTrigger>
390 <MenuSubPopup {...(!isPanel ? composerFloatingLayerProps : {})}>
391 {addTargets.map((target) => (
392 <MenuItem
393 key={target.environmentId}
394 onClick={() => onAddToMachine(target.environmentId)}
395 >
396 <span className="flex min-w-0 items-center gap-1.5">
397 <EnvironmentMachineIcon kind={target.machine} className="size-3" />
398 <span className="min-w-0 truncate">{target.label}</span>
399 </span>
400 </MenuItem>
401 ))}
402 </MenuSubPopup>
403 </MenuSub>
404 ) : null}
405 </MenuGroup>
406 <MenuSeparator />
407 </>
408 ) : null}
409 <MenuGroup>
410 <MenuGroupLabel>Workspace</MenuGroupLabel>
411 <MenuRadioGroup
412 value={effectiveEnvMode}
413 onValueChange={(value) => {
414 if (value === "previous-worktree") {
415 onUsePreviousWorktree();
416 return;
417 }
418 onEnvModeChange(value as EnvMode);
419 }}
420 >
421 <MenuRadioItem disabled={envModeLocked || forceNewWorktree} value="local" closeOnClick>
422 <span className="flex min-w-0 items-center gap-1.5">
423 {activeWorktreePath ? (
424 <FolderGitIcon className="size-3" />
425 ) : (
426 <FolderIcon className="size-3" />
427 )}
428 <MiddleTruncate value={resolveCurrentWorkspaceLabel(activeWorktreePath)} />
429 </span>
430 </MenuRadioItem>
431 <MenuRadioItem disabled={envModeLocked} value="worktree" closeOnClick>
432 <span className="flex min-w-0 items-center gap-1.5">
433 <FolderGit2Icon className="size-3" />
434 <span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
435 </span>
436 </MenuRadioItem>
437 {previousWorktreeLabel ? (
438 <MenuRadioItem disabled={envModeLocked} value="previous-worktree" closeOnClick>
439 <PreviousWorktreeItemContent branch={previousWorktreeBranch} />
440 </MenuRadioItem>
441 ) : null}
442 </MenuRadioGroup>
443 </MenuGroup>
444 </MenuPopup>
445 </Menu>
446 );
447});
448​
449const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
450const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
451const COMPOSER_CONTEXT_LABEL_SELECTOR = "[data-composer-label]";
452​
453/** A hidden or squeezed label's scrollWidth loses its tail, causing label/icon flapping. */
454function labelTextWidth(label: HTMLElement, range: Range): number {
455 const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
456 let width = 0;
457 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
458 range.selectNodeContents(node);
459 width += range.getBoundingClientRect().width;
460 }
461 const motion = label.querySelector<HTMLElement>("[data-composer-label-motion]");
462 const maxWidth = motion ? Number.parseFloat(getComputedStyle(motion).maxWidth) : Number.NaN;
463 return Number.isFinite(maxWidth) ? Math.min(width, maxWidth) : width;
465​
466function animateLabelWidths(
467 previousRects: ReadonlyMap<HTMLElement, DOMRect>,
468 animations: Map<HTMLElement, Animation>,
469) {
470 for (const animation of animations.values()) animation.cancel();
471 animations.clear();
472 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
473​
474 for (const [label, previousRect] of previousRects) {
475 if (!label.isConnected) continue;
476 const nextWidth = label.getBoundingClientRect().width;
477 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
478​
479 const animation = label.animate(
480 [
481 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
482 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
483 ],
484 {
485 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
486 easing: COMPOSER_CONTEXT_MOTION_EASING,
487 fill: "backwards",
488 },
489 );
490 animations.set(label, animation);
491 animation.addEventListener(
492 "finish",
493 () => {
494 if (animations.get(label) === animation) animations.delete(label);
495 },
496 { once: true },
497 );
498 }
500​
501/**
502 * Whether the strip's labels must collapse to icons. The strip is measured when
503 * it, a control group or a hosted control resizes, when its text or children
504 * change, and when fonts load, which covers everything the widths depend on.
505 */
506function useLabelsOverflow(): readonly [
507 attach: (element: HTMLDivElement | null) => (() => void) | undefined,
508 overflows: boolean,
509] {
510 const [overflows, setOverflows] = useState(false);
511​
512 const attach = (current: HTMLDivElement | null) => {
513 if (!current) return;
514 const labelAnimations = new Map<HTMLElement, Animation>();
515​
516 const measure = () => {
517 // The committed attribute, not render state, so a stale closure cannot misread it.
518 const compact = current.hasAttribute("data-compact");
519 const stripWidth = current.clientWidth;
520 if (stripWidth === 0) return;
521 const stripStyle = getComputedStyle(current);
522 const available =
523 stripWidth -
524 (Number.parseFloat(stripStyle.paddingInlineStart) || 0) -
525 (Number.parseFloat(stripStyle.paddingInlineEnd) || 0);
526 const contentWidth = (parent: Element): number => {
527 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
528 let width = 0;
529 let counted = 0;
530 for (const child of parent.children) {
531 if (!(child instanceof HTMLElement)) continue;
532 if (child.offsetWidth === 0) continue;
533 const style = getComputedStyle(child);
534 const position = style.position;
535 if (position === "absolute" || position === "fixed") continue;
536 width +=
537 child.offsetWidth +
538 (Number.parseFloat(style.marginInlineStart) || 0) +
539 (Number.parseFloat(style.marginInlineEnd) || 0);
540 counted += 1;
541 }
542 return width + gap * Math.max(0, counted - 1);
543 };
544 const stripGap = Number.parseFloat(stripStyle.columnGap) || 0;
545 let needed = 0;
546 let groups = 0;
547 for (const child of current.children) {
548 if (!(child instanceof HTMLElement)) continue;
549 // Reserve overflowed controls' width to prevent repeated hiding and expansion.
550 const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
551 ? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
552 : null;
553 const hostedMeasurement = hostedControls
554 ? measureRestingComposerControls(hostedControls)
555 : null;
556 const width = hostedMeasurement
557 ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
558 : contentWidth(hostedControls ?? child);
559 if (width <= 1) continue;
560 groups += 1;
561 needed += width;
562 }
563 needed += stripGap * Math.max(0, groups - 1);
564 const range = document.createRange();
565 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
566 needed += Math.max(0, labelTextWidth(label, range) - label.getBoundingClientRect().width);
567 }
568 const nextOverflows = resolveContextStripLabelsCompact({
569 compact,
570 neededWidth: needed,
571 availableWidth: available,
572 });
573 if (nextOverflows === compact) return;
574 const previousRects = new Map(
575 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
576 (label) => [label, label.getBoundingClientRect()] as const,
577 ),
578 );
579 flushSync(() => setOverflows(nextOverflows));
580 animateLabelWidths(previousRects, labelAnimations);
581 };
582​
583 let stopResize = () => {};
584 const observeSizes = () => {
585 stopResize();
586 stopResize = observeResize(
587 [
588 current,
589 ...Array.from(current.children),
590 ...Array.from(current.querySelectorAll("[data-chat-composer-resting-controls='true']")),
591 ...Array.from(current.querySelectorAll(COMPOSER_CONTEXT_LABEL_SELECTOR)),
592 ],
593 measure,
594 );
595 };
596 observeSizes();
597 // Text and control changes alter natural widths without resizing a hidden
598 // or squeezed label, so they re-measure too. Only added or removed elements
599 // can change the observed set; re-subscribing delivers a measure itself.
600 const mutations = new MutationObserver((records) => {
601 const elementsChanged = records.some((record) =>
602 [...record.addedNodes, ...record.removedNodes].some((node) => node instanceof Element),
603 );
604 if (elementsChanged) observeSizes();
605 else measure();
606 });
607 mutations.observe(current, { childList: true, characterData: true, subtree: true });
608 document.fonts.addEventListener("loadingdone", measure);
609 return () => {
610 stopResize();
611 mutations.disconnect();
612 document.fonts.removeEventListener("loadingdone", measure);
613 for (const animation of labelAnimations.values()) animation.cancel();
614 };
615 };
616​
617 return [attach, overflows] as const;
619​
620export const BranchToolbar = memo(function BranchToolbar({
621 layout = "composer",
622 panelSection = "all",
623 forceNewWorktree = false,
624 ref,
625 environmentId,
626 threadId,
627 projectId,
628 worktreePath,
629 isServerThread,
630 showGitControls,
631 draftId,
632 onEnvModeChange,
633 envMode,
634 activeThreadBranchOverride,
635 onActiveThreadBranchOverrideChange,
636 startFromOrigin,
637 onStartFromOriginChange,
638 autoEnvironmentLabel,
639 onAutoEnvironment,
640 envLocked,
641 onCheckoutPullRequestRequest,
642 onComposerFocusRequest,
643 availableEnvironments,
644 onEnvironmentChange,
645 composerControlsHostRef,
646 contextStripVisible = true,
647}: BranchToolbarProps) {
648 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
649 const threadRef = scopeThreadRef(environmentId, threadId);
650 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
651 // The composer retains resolved thread details while bootstrap cleanup can remove its shell.
652 const activeProjectRef = scopeProjectRef(environmentId, projectId);
653 const activeProject = useProject(activeProjectRef);
654 const activeWorktreePath = forceNewWorktree ? null : worktreePath;
655 const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode;
656 const envModeLocked = envLocked || (isServerThread && activeWorktreePath !== null);
657​
658 const canUsePreviousWorktree = !isServerThread && !envModeLocked && !forceNewWorktree;
659 const projectRefsForWorktreeLookup = canUsePreviousWorktree ? [activeProjectRef] : [];
660 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
661 const previousWorktreeSeed = canUsePreviousWorktree
662 ? resolvePreviousWorktreeSeed({
663 threads: projectThreads,
664 currentWorktreePath: activeWorktreePath,
665 })
666 : null;
667 const previousWorktreeLabel = previousWorktreeSeed
668 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
669 : null;
670 const onUsePreviousWorktree = () => {
671 if (!previousWorktreeSeed) return;
672 setDraftThreadContext(draftId ?? threadRef, {
673 branch: previousWorktreeSeed.branch,
674 worktreePath: previousWorktreeSeed.worktreePath,
675 envMode: "worktree",
676 projectRef: activeProjectRef,
677 });
678 };
679​
680 useImperativeHandle(
681 ref,
682 () => ({
683 openBranchPicker: () => branchSelectorRef.current?.open(),
684 usePreviousWorktree: () => {
685 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
686 onUsePreviousWorktree();
687 onComposerFocusRequest?.();
688 },
689 }),
690 [
691 canUsePreviousWorktree,
692 onComposerFocusRequest,
693 onUsePreviousWorktree,
694 previousWorktreeSeed,
695 showGitControls,
696 ],
697 );
698​
699 const addTargets = useAddProjectTargets(activeProject, availableEnvironments);
700 const onAddToMachine = (targetEnvironmentId: EnvironmentId | null) =>
701 openAddProjectToMachine({ projectRef: activeProjectRef, targetEnvironmentId });
702 // A project on one machine still gets the picker when it can be added to another.
703 const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1 || addTargets.length > 0;
704 const showEnvironmentPicker = hasMultipleEnvironments && onEnvironmentChange !== undefined;
705 const activeEnvironmentOption =
706 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
707 // Started threads get no handler but still show which machine they run on,
708 // matching the strip visibility ChatView computes from the same inputs.
709 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
710 activeEnvironment: activeEnvironmentOption,
711 canPickEnvironment: hasMultipleEnvironments,
712 });
713 const [attachStrip, labelsOverflow] = useLabelsOverflow();
714​
715 if (!activeProject) return null;
716​
717 if (layout === "panel") {
718 return (
719 <div className="flex w-full flex-col" data-thread-panel-run-context>
720 {panelSection !== "branch" ? (
721 <RunContextSelector
722 displayMode="panel"
723 workspaceRoot={activeProject.workspaceRoot}
724 forceNewWorktree={forceNewWorktree}
725 autoEnvironmentLabel={autoEnvironmentLabel}
726 onAutoEnvironment={onAutoEnvironment}
727 envLocked={envLocked}
728 envModeLocked={envModeLocked}
729 environmentId={environmentId}
730 availableEnvironments={availableEnvironments}
731 showEnvironmentPicker={showEnvironmentPicker}
732 showEnvironmentIndicator={activeEnvironmentOption !== null}
733 onEnvironmentChange={onEnvironmentChange}
734 effectiveEnvMode={effectiveEnvMode}
735 activeWorktreePath={activeWorktreePath}
736 onEnvModeChange={onEnvModeChange}
737 previousWorktreeLabel={previousWorktreeLabel}
738 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
739 onUsePreviousWorktree={onUsePreviousWorktree}
740 addTargets={addTargets}
741 onAddToMachine={onAddToMachine}
742 />
743 ) : null}
744 {panelSection !== "workspace" ? (
745 <BranchToolbarBranchSelector
746 displayMode="panel"
747 className="w-full"
748 environmentId={environmentId}
749 threadId={threadId}
750 {...(draftId ? { draftId } : {})}
751 envLocked={envLocked}
752 effectiveEnvModeOverride={effectiveEnvMode}
753 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
754 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
755 startFromOrigin={startFromOrigin}
756 onStartFromOriginChange={onStartFromOriginChange}
757 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
758 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
759 />
760 ) : null}
761 </div>
762 );
763 }
764​
765 return (
766 <ComposerSurface.ContextStrip
767 ref={attachStrip}
768 data-compact={labelsOverflow ? "" : undefined}
769 className={cn(
770 "gap-1 text-xs font-normal text-foreground/70 dark:text-muted-foreground",
771 // Hide empty non-Git strips while retaining host width so controls can reappear as the chat grows.
772 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
773 )}
774 >
775 {showGitControls ? (
776 <div className="contents @3xl/composer-surface:hidden">
777 <RunContextSelector
778 forceNewWorktree={forceNewWorktree}
779 autoEnvironmentLabel={autoEnvironmentLabel}
780 onAutoEnvironment={onAutoEnvironment}
781 envLocked={envLocked}
782 envModeLocked={envModeLocked}
783 environmentId={environmentId}
784 availableEnvironments={availableEnvironments}
785 showEnvironmentPicker={showEnvironmentPicker}
786 showEnvironmentIndicator={showEnvironmentIndicator}
787 onEnvironmentChange={onEnvironmentChange}
788 effectiveEnvMode={effectiveEnvMode}
789 activeWorktreePath={activeWorktreePath}
790 onEnvModeChange={onEnvModeChange}
791 previousWorktreeLabel={previousWorktreeLabel}
792 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
793 onUsePreviousWorktree={onUsePreviousWorktree}
794 addTargets={addTargets}
795 onAddToMachine={onAddToMachine}
796 />
797 </div>
798 ) : null}
799 {showGitControls || showEnvironmentIndicator ? (
800 <div
801 className={cn(
802 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
803 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
804 composerControlsHostRef ? "shrink" : "flex-1",
805 )}
806 >
807 {showEnvironmentIndicator && availableEnvironments && (
808 <>
809 <BranchToolbarEnvironmentSelector
810 autoEnvironmentLabel={autoEnvironmentLabel}
811 onAutoEnvironment={onAutoEnvironment}
812 envLocked={envLocked}
813 environmentId={environmentId}
814 availableEnvironments={availableEnvironments}
815 {...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
816 {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
817 />
818 {showGitControls ? (
819 <Separator
820 orientation="vertical"
821 className="mx-0.5 h-3.5!"
822 data-composer-context-control
823 />
824 ) : null}
825 </>
826 )}
827 {showGitControls ? (
828 <BranchToolbarEnvModeSelector
829 forceNewWorktree={forceNewWorktree}
830 envLocked={envModeLocked}
831 effectiveEnvMode={effectiveEnvMode}
832 activeWorktreePath={activeWorktreePath}
833 onEnvModeChange={onEnvModeChange}
834 previousWorktreeLabel={previousWorktreeLabel}
835 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
836 onUsePreviousWorktree={onUsePreviousWorktree}
837 />
838 ) : null}
839 </div>
840 ) : null}
841​
842 {composerControlsHostRef ? (
843 <div
844 ref={composerControlsHostRef}
845 data-composer-context-control
846 data-chat-resting-composer-controls-host="true"
847 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
848 />
849 ) : null}
850​
851 {showGitControls ? (
852 <BranchToolbarBranchSelector
853 forceNewWorktree={forceNewWorktree}
854 ref={branchSelectorRef}
855 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
856 environmentId={environmentId}
857 threadId={threadId}
858 {...(draftId ? { draftId } : {})}
859 envLocked={envLocked}
860 effectiveEnvModeOverride={effectiveEnvMode}
861 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
862 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
863 startFromOrigin={startFromOrigin}
864 onStartFromOriginChange={onStartFromOriginChange}
865 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
866 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
867 />
868 ) : null}
869 </ComposerSurface.ContextStrip>
870 );
871});