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