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

BranchToolbar.tsx

713 lines26.8 KB

1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import {
4 ChevronDownIcon,
5 FolderGit2Icon,
6 FolderGitIcon,
7 FolderIcon,
8 HistoryIcon,
9 ScaleIcon,
10} from "lucide-react";
11import {
12 type Ref,
13 memo,
14 useImperativeHandle,
15 useCallback,
16 useEffect,
17 useLayoutEffect,
18 useMemo,
19 useRef,
20 useState,
21} from "react";
22​
23import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
24import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
25import { useProject, useThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
26import {
27 type EnvMode,
28 type EnvironmentOption,
29 resolveContextStripLabelsCompact,
30 resolveCurrentWorkspaceLabel,
31 resolveEnvModeLabel,
32 resolveEffectiveEnvMode,
33 resolveLockedWorkspaceLabel,
34 resolvePreviousWorktreeLabel,
35 resolvePreviousWorktreeSeed,
36 shouldShowEnvironmentIndicator,
37} from "./BranchToolbar.logic";
38import {
39 BranchToolbarBranchSelector,
40 type BranchToolbarBranchSelectorHandle,
41} from "./BranchToolbarBranchSelector";
42import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
43import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
44import { Button } from "./ui/button";
45import {
46 Menu,
47 MenuGroup,
48 MenuGroupLabel,
49 MenuPopup,
50 MenuRadioGroup,
51 MenuRadioItem,
52 MenuSeparator,
53 MenuTrigger,
54} from "./ui/menu";
55import { Separator } from "./ui/separator";
56import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
57import { ComposerSurface } from "./chat/ComposerSurface";
58import { useComposerMenuProps } from "./chat/composerEventScope";
59import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement";
60import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout";
61import { cn } from "~/lib/utils";
62​
63export interface BranchToolbarHandle {
64 openBranchPicker: () => void;
65 usePreviousWorktree: () => void;
67​
68interface BranchToolbarProps {
69 forceNewWorktree?: boolean;
70 ref?: Ref<BranchToolbarHandle>;
71 environmentId: EnvironmentId;
72 threadId: ThreadId;
73 showGitControls: boolean;
74 draftId?: DraftId;
75 onEnvModeChange: (mode: EnvMode) => void;
76 effectiveEnvModeOverride?: EnvMode;
77 activeThreadBranchOverride?: string | null;
78 onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
79 startFromOrigin: boolean;
80 onStartFromOriginChange: (startFromOrigin: boolean) => void;
81 autoEnvironmentLabel?: string | undefined;
82 onAutoEnvironment?: (() => void) | undefined;
83 envLocked: boolean;
84 onCheckoutPullRequestRequest?: (reference: string) => void;
85 onComposerFocusRequest?: () => void;
86 availableEnvironments?: readonly EnvironmentOption[];
87 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
88 composerControlsHostRef?: (element: HTMLDivElement | null) => void;
89 contextStripVisible?: boolean;
91​
92interface MobileRunContextSelectorProps {
93 forceNewWorktree: boolean;
94 autoEnvironmentLabel?: string | undefined;
95 onAutoEnvironment?: (() => void) | undefined;
96 envLocked: boolean;
97 envModeLocked: boolean;
98 environmentId: EnvironmentId;
99 availableEnvironments: readonly EnvironmentOption[] | undefined;
100 showEnvironmentPicker: boolean;
101 showEnvironmentIndicator: boolean;
102 onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
103 effectiveEnvMode: EnvMode;
104 activeWorktreePath: string | null;
105 onEnvModeChange: (mode: EnvMode) => void;
106 previousWorktreeLabel: string | null;
107 onUsePreviousWorktree: () => void;
109​
110const MobileRunContextSelector = memo(function MobileRunContextSelector({
111 forceNewWorktree,
112 autoEnvironmentLabel,
113 onAutoEnvironment,
114 envLocked,
115 envModeLocked,
116 environmentId,
117 availableEnvironments,
118 showEnvironmentPicker,
119 showEnvironmentIndicator,
120 onEnvironmentChange,
121 effectiveEnvMode,
122 activeWorktreePath,
123 onEnvModeChange,
124 previousWorktreeLabel,
125 onUsePreviousWorktree,
126}: MobileRunContextSelectorProps) {
127 const composerFloatingLayerProps = useComposerMenuProps();
128 const activeEnvironment = useMemo(
129 () => availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null,
130 [availableEnvironments, environmentId],
131 );
132 const WorkspaceIcon =
133 effectiveEnvMode === "worktree"
134 ? FolderGit2Icon
135 : activeWorktreePath
136 ? FolderGitIcon
137 : FolderIcon;
138 const workspaceLabel = forceNewWorktree
139 ? resolveEnvModeLabel("worktree")
140 : envModeLocked
141 ? resolveLockedWorkspaceLabel(activeWorktreePath)
142 : effectiveEnvMode === "worktree"
143 ? resolveEnvModeLabel("worktree")
144 : resolveCurrentWorkspaceLabel(activeWorktreePath);
145 const isLocked = envLocked || envModeLocked;
146 const workspaceIcon = (
147 <Tooltip>
148 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
149 <WorkspaceIcon className={cn("size-3 shrink-0", showEnvironmentIndicator && "mx-0!")} />
150 </TooltipTrigger>
151 <TooltipPopup>{workspaceLabel}</TooltipPopup>
152 </Tooltip>
153 );
154 const icon = showEnvironmentIndicator ? (
155 // Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
156 // out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
157 <span className="inline-flex shrink-0 items-center gap-0.5">
158 <Tooltip>
159 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
160 {autoEnvironmentLabel ? (
161 <ScaleIcon className="size-3 shrink-0 mx-0!" aria-hidden="true" />
162 ) : (
163 <EnvironmentMachineIcon
164 kind={activeEnvironment?.machine ?? "server"}
165 className="size-3 shrink-0 mx-0!"
166 />
167 )}
168 </TooltipTrigger>
169 <TooltipPopup>{autoEnvironmentLabel ?? activeEnvironment?.label ?? "Run on"}</TooltipPopup>
170 </Tooltip>
171 {workspaceIcon}
172 </span>
173 ) : (
174 workspaceIcon
175 );
176 const triggerContent = (
177 <>
178 {icon}
179 <span
180 data-composer-label
181 className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
182 >
183 <span
184 data-composer-label-motion
185 className="block w-full min-w-0 max-w-[240px] truncate transition-opacity duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transition-none"
186 >
187 {autoEnvironmentLabel ??
188 (showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel)}
189 </span>
190 </span>
191 </>
192 );
193​
194 if (isLocked) {
195 return (
196 <span
197 className="inline-flex h-7 min-w-0 max-w-[48%] flex-initial items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] font-normal text-muted-foreground/70 text-xs sm:h-6"
198 data-composer-context-control
199 >
200 {triggerContent}
201 </span>
202 );
203 }
204​
205 return (
206 <Menu>
207 <MenuTrigger
208 render={<Button variant="ghost" size="xs" />}
209 className="min-w-0 max-w-[48%] flex-initial justify-start font-normal text-muted-foreground/70 text-xs! hover:text-foreground/80"
210 data-composer-context-control
211 data-composer-shortcut={[
212 showEnvironmentPicker && !envLocked ? "composer.host" : "",
213 !envModeLocked ? "composer.workspace" : "",
214 ].join(" ")}
215 >
216 {triggerContent}
217 <ChevronDownIcon className="size-3 shrink-0 opacity-50" />
218 </MenuTrigger>
219 <MenuPopup align="start" side="top" className="w-64" {...composerFloatingLayerProps}>
220 {showEnvironmentPicker && availableEnvironments && onEnvironmentChange ? (
221 <>
222 <MenuGroup>
223 <MenuGroupLabel>Run on</MenuGroupLabel>
224 <MenuRadioGroup
225 value={autoEnvironmentLabel ? "auto" : environmentId}
226 onValueChange={(value) =>
227 value === "auto"
228 ? onAutoEnvironment?.()
229 : onEnvironmentChange(value as EnvironmentId)
230 }
231 >
232 {onAutoEnvironment && (
233 <MenuRadioItem
234 value="auto"
235 disabled={envLocked}
236 onClick={() => {
237 if (autoEnvironmentLabel) onAutoEnvironment?.();
238 }}
239 >
240 <span className="flex min-w-0 items-center gap-1.5">
241 <ScaleIcon className="size-3" aria-hidden="true" />
242 <span className="min-w-0 truncate">
243 {autoEnvironmentLabel ?? "Auto balance"}
244 </span>
245 </span>
246 </MenuRadioItem>
247 )}
248 {availableEnvironments.map((env) => (
249 <MenuRadioItem
250 key={env.environmentId}
251 disabled={envLocked}
252 value={env.environmentId}
253 >
254 <span className="flex min-w-0 items-center gap-1.5">
255 <EnvironmentMachineIcon kind={env.machine} className="size-3" />
256 <span className="min-w-0 truncate">{env.label}</span>
257 </span>
258 </MenuRadioItem>
259 ))}
260 </MenuRadioGroup>
261 </MenuGroup>
262 <MenuSeparator />
263 </>
264 ) : null}
265 <MenuGroup>
266 <MenuGroupLabel>Workspace</MenuGroupLabel>
267 <MenuRadioGroup
268 value={effectiveEnvMode}
269 onValueChange={(value) => {
270 if (value === "previous-worktree") {
271 onUsePreviousWorktree();
272 return;
273 }
274 onEnvModeChange(value as EnvMode);
275 }}
276 >
277 <MenuRadioItem disabled={envModeLocked || forceNewWorktree} value="local">
278 <span className="flex min-w-0 items-center gap-1.5">
279 {activeWorktreePath ? (
280 <FolderGitIcon className="size-3" />
281 ) : (
282 <FolderIcon className="size-3" />
283 )}
284 <span className="min-w-0 truncate">
285 {resolveCurrentWorkspaceLabel(activeWorktreePath)}
286 </span>
287 </span>
288 </MenuRadioItem>
289 <MenuRadioItem disabled={envModeLocked} value="worktree">
290 <span className="flex min-w-0 items-center gap-1.5">
291 <FolderGit2Icon className="size-3" />
292 <span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
293 </span>
294 </MenuRadioItem>
295 {previousWorktreeLabel ? (
296 <MenuRadioItem disabled={envModeLocked} value="previous-worktree">
297 <span className="flex min-w-0 items-center gap-1.5">
298 <HistoryIcon className="size-3" />
299 <span className="min-w-0 truncate">{previousWorktreeLabel}</span>
300 </span>
301 </MenuRadioItem>
302 ) : null}
303 </MenuRadioGroup>
304 </MenuGroup>
305 </MenuPopup>
306 </Menu>
307 );
308});
309​
310/**
311 * Collapse the strip's labels to icons only when the text no longer fits.
312 *
313 * Hidden labels stay measurable because their inner text keeps its natural
314 * width while the outer layout box collapses. This lets every pass recompute
315 * the expanded width without remembered values that could go stale or latch
316 * the strip compact. A small hysteresis keeps the boundary from flapping.
317 */
318const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
319const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
320const COMPOSER_CONTEXT_LABEL_SELECTOR = "[data-composer-label]";
321​
322function useLabelsOverflow(element: HTMLDivElement | null): boolean {
323 const [overflows, setOverflows] = useState(false);
324 const pendingLabelRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
325 const labelAnimationsRef = useRef(new Map<HTMLElement, Animation>());
326 // A render-synced mirror instead of useEffectEvent: the compiler memoizes
327 // the event callback, which left observers reading the first render's null
328 // element forever.
329 const stateRef = useRef({ element, overflows });
330 stateRef.current = { element, overflows };
331​
332 const measure = useCallback(() => {
333 const { element: current, overflows: compact } = stateRef.current;
334 if (!current) return;
335 const available = current.clientWidth;
336 if (available === 0) return;
337 // flex-1 stretches the groups to fill the strip, so their own boxes always
338 // measure "full". Sum the laid-out content instead, skipping hidden form
339 // artifacts and other out-of-flow nodes.
340 const contentWidth = (parent: Element): number => {
341 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
342 let width = 0;
343 let counted = 0;
344 for (const child of parent.children) {
345 if (!(child instanceof HTMLElement)) continue;
346 if (child.offsetWidth === 0) continue;
347 const style = getComputedStyle(child);
348 const position = style.position;
349 if (position === "absolute" || position === "fixed") continue;
350 width +=
351 child.offsetWidth +
352 (Number.parseFloat(style.marginInlineStart) || 0) +
353 (Number.parseFloat(style.marginInlineEnd) || 0);
354 counted += 1;
355 }
356 return width + gap * Math.max(0, counted - 1);
357 };
358 const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
359 let needed = 0;
360 let groups = 0;
361 for (const child of current.children) {
362 if (!(child instanceof HTMLElement)) continue;
363 // The host itself flexes into all remaining room. Reserve the natural
364 // width of the controls inside it, blocks in overflow included, so Git
365 // labels compact before squeezing out the model picker. Reserving only
366 // the visible controls would let the labels expand into room the
367 // composer just freed, shrink the host, and hide the controls again.
368 const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
369 ? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
370 : null;
371 const hostedMeasurement = hostedControls
372 ? measureRestingComposerControls(hostedControls)
373 : null;
374 const width = hostedMeasurement
375 ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
376 : contentWidth(hostedControls ?? child);
377 if (width <= 1) continue;
378 groups += 1;
379 needed += width;
380 }
381 needed += stripGap * Math.max(0, groups - 1);
382 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
383 // The clipping can happen below the marker (SelectValue truncates
384 // internally), where the outer span's scrollWidth matches its clipped
385 // box. The text's real width is the largest scrollWidth in the subtree.
386 let textWidth = label.scrollWidth;
387 for (const inner of label.querySelectorAll<HTMLElement>("*")) {
388 textWidth = Math.max(textWidth, inner.scrollWidth);
389 }
390 // Subtract the visible width even during an animation. The content
391 // sum already includes it; only the hidden text needs reserving.
392 needed += Math.max(0, textWidth - label.getBoundingClientRect().width);
393 }
394 const nextOverflows = resolveContextStripLabelsCompact({
395 compact,
396 neededWidth: needed,
397 availableWidth: available,
398 });
399 if (nextOverflows !== compact) {
400 pendingLabelRectsRef.current = new Map(
401 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
402 (label) => [label, label.getBoundingClientRect()],
403 ),
404 );
405 }
406 setOverflows(nextOverflows);
407 }, []);
408​
409 useLayoutEffect(() => {
410 const previousRects = pendingLabelRectsRef.current;
411 if (!previousRects) return;
412 pendingLabelRectsRef.current = null;
413​
414 for (const animation of labelAnimationsRef.current.values()) {
415 animation.cancel();
416 }
417 labelAnimationsRef.current.clear();
418​
419 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
420​
421 for (const [label, previousRect] of previousRects) {
422 if (!label.isConnected) continue;
423 const nextWidth = label.getBoundingClientRect().width;
424 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
425​
426 // Animate the space occupied by each label so flex layout keeps the
427 // trailing controls anchored. Translating the whole group after its
428 // width snaps sends expanded text beyond the strip's right edge.
429 const animation = label.animate(
430 [
431 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
432 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
433 ],
434 {
435 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
436 easing: COMPOSER_CONTEXT_MOTION_EASING,
437 fill: "backwards",
438 },
439 );
440 labelAnimationsRef.current.set(label, animation);
441 animation.addEventListener(
442 "finish",
443 () => {
444 if (labelAnimationsRef.current.get(label) === animation) {
445 labelAnimationsRef.current.delete(label);
446 }
447 },
448 { once: true },
449 );
450 }
451 }, [overflows]);
452​
453 useEffect(
454 () => () => {
455 for (const animation of labelAnimationsRef.current.values()) {
456 animation.cancel();
457 }
458 },
459 [],
460 );
461​
462 // Label widths can change without the strip box moving (font family or
463 // size preferences), so re-measure on every render as well as on resize
464 // and font loads.
465 useLayoutEffect(() => {
466 measure();
467 });
468​
469 useEffect(() => {
470 if (!element) return;
471 const observer = new ResizeObserver(measure);
472 observer.observe(element);
473 document.fonts.addEventListener("loadingdone", measure);
474 return () => {
475 observer.disconnect();
476 document.fonts.removeEventListener("loadingdone", measure);
477 };
478 }, [element, measure]);
479​
480 return overflows;
482​
483export const BranchToolbar = memo(function BranchToolbar({
484 forceNewWorktree = false,
485 ref,
486 environmentId,
487 threadId,
488 showGitControls,
489 draftId,
490 onEnvModeChange,
491 effectiveEnvModeOverride,
492 activeThreadBranchOverride,
493 onActiveThreadBranchOverrideChange,
494 startFromOrigin,
495 onStartFromOriginChange,
496 autoEnvironmentLabel,
497 onAutoEnvironment,
498 envLocked,
499 onCheckoutPullRequestRequest,
500 onComposerFocusRequest,
501 availableEnvironments,
502 onEnvironmentChange,
503 composerControlsHostRef,
504 contextStripVisible = true,
505}: BranchToolbarProps) {
506 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
507 const threadRef = useMemo(
508 () => scopeThreadRef(environmentId, threadId),
509 [environmentId, threadId],
510 );
511 const draftThread = useComposerDraftStore((store) =>
512 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
513 );
514 const serverThread = useThreadShell(threadRef);
515 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
516 const activeProjectRef = serverThread
517 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
518 : draftThread
519 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
520 : null;
521 const activeProject = useProject(activeProjectRef);
522 const hasActiveThread = serverThread !== null || draftThread !== null;
523 const activeWorktreePath = forceNewWorktree
524 ? null
525 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
526 const effectiveEnvMode =
527 (forceNewWorktree ? "worktree" : effectiveEnvModeOverride) ??
528 resolveEffectiveEnvMode({
529 activeWorktreePath,
530 hasServerThread: serverThread !== null,
531 draftThreadEnvMode: draftThread?.envMode,
532 });
533 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
534​
535 // "Previous worktree" hops a draft into the most recently active worktree
536 // of this project — the "keep going where I just was" follow-up flow. Only
537 // drafts can hop; started server threads have their workspace pinned.
538 const canUsePreviousWorktree =
539 draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree;
540 const projectRefsForWorktreeLookup = useMemo(
541 () => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
542 [canUsePreviousWorktree, activeProjectRef],
543 );
544 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
545 const previousWorktreeSeed = useMemo(
546 () =>
547 canUsePreviousWorktree
548 ? resolvePreviousWorktreeSeed({
549 threads: projectThreads,
550 currentWorktreePath: activeWorktreePath,
551 })
552 : null,
553 [activeWorktreePath, canUsePreviousWorktree, projectThreads],
554 );
555 const previousWorktreeLabel = previousWorktreeSeed
556 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
557 : null;
558 const onUsePreviousWorktree = useCallback(() => {
559 if (!previousWorktreeSeed || !activeProjectRef) return;
560 // Same shape the branch selector writes when picking a branch that
561 // already lives in a worktree: point the draft at the existing tree.
562 setDraftThreadContext(draftId ?? threadRef, {
563 branch: previousWorktreeSeed.branch,
564 worktreePath: previousWorktreeSeed.worktreePath,
565 envMode: "worktree",
566 projectRef: activeProjectRef,
567 });
568 }, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
569​
570 useImperativeHandle(
571 ref,
572 () => ({
573 openBranchPicker: () => branchSelectorRef.current?.open(),
574 usePreviousWorktree: () => {
575 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
576 onUsePreviousWorktree();
577 onComposerFocusRequest?.();
578 },
579 }),
580 [
581 canUsePreviousWorktree,
582 onComposerFocusRequest,
583 onUsePreviousWorktree,
584 previousWorktreeSeed,
585 showGitControls,
586 ],
587 );
588​
589 const showEnvironmentPicker = Boolean(
590 availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
591 );
592 const activeEnvironmentOption =
593 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
594 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
595 activeEnvironment: activeEnvironmentOption,
596 canPickEnvironment: showEnvironmentPicker,
597 });
598 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
599 const labelsOverflow = useLabelsOverflow(stripElement);
600​
601 if (!hasActiveThread || !activeProject) return null;
602​
603 return (
604 <ComposerSurface.ContextStrip
605 ref={setStripElement}
606 data-compact={labelsOverflow ? "" : undefined}
607 className={cn(
608 "gap-1 text-xs font-normal text-muted-foreground/70",
609 // A non-Git strip with no visible composer controls should occupy no
610 // space, but its host must retain a prospective width so controls can
611 // become visible again when the chat view grows.
612 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
613 )}
614 >
615 {showGitControls ? (
616 <div className="contents @3xl/composer-surface:hidden">
617 <MobileRunContextSelector
618 forceNewWorktree={forceNewWorktree}
619 autoEnvironmentLabel={autoEnvironmentLabel}
620 onAutoEnvironment={onAutoEnvironment}
621 envLocked={envLocked}
622 envModeLocked={envModeLocked}
623 environmentId={environmentId}
624 availableEnvironments={availableEnvironments}
625 showEnvironmentPicker={showEnvironmentPicker}
626 showEnvironmentIndicator={showEnvironmentIndicator}
627 onEnvironmentChange={onEnvironmentChange}
628 effectiveEnvMode={effectiveEnvMode}
629 activeWorktreePath={activeWorktreePath}
630 onEnvModeChange={onEnvModeChange}
631 previousWorktreeLabel={previousWorktreeLabel}
632 onUsePreviousWorktree={onUsePreviousWorktree}
633 />
634 </div>
635 ) : null}
636 {showGitControls || showEnvironmentIndicator ? (
637 <div
638 className={cn(
639 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
640 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
641 composerControlsHostRef ? "shrink" : "flex-1",
642 )}
643 >
644 {showEnvironmentIndicator && availableEnvironments && (
645 <>
646 <BranchToolbarEnvironmentSelector
647 autoEnvironmentLabel={autoEnvironmentLabel}
648 onAutoEnvironment={onAutoEnvironment}
649 envLocked={envLocked}
650 environmentId={environmentId}
651 availableEnvironments={availableEnvironments}
652 {...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
653 />
654 {showGitControls ? (
655 <Separator
656 orientation="vertical"
657 className="mx-0.5 h-3.5!"
658 data-composer-context-control
659 />
660 ) : null}
661 </>
662 )}
663 {showGitControls ? (
664 <BranchToolbarEnvModeSelector
665 forceNewWorktree={forceNewWorktree}
666 envLocked={envModeLocked}
667 effectiveEnvMode={effectiveEnvMode}
668 activeWorktreePath={activeWorktreePath}
669 onEnvModeChange={onEnvModeChange}
670 previousWorktreeLabel={previousWorktreeLabel}
671 onUsePreviousWorktree={onUsePreviousWorktree}
672 />
673 ) : null}
674 </div>
675 ) : null}
676​
677 {composerControlsHostRef ? (
678 // The host takes whatever the workspace and branch controls leave
679 // over, in both strip layouts, so a collapsed composer can show its
680 // model and mode controls wherever they fit.
681 <div
682 ref={composerControlsHostRef}
683 data-composer-context-control
684 data-chat-resting-composer-controls-host="true"
685 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
686 />
687 ) : null}
688​
689 {showGitControls ? (
690 <BranchToolbarBranchSelector
691 forceNewWorktree={forceNewWorktree}
692 ref={branchSelectorRef}
693 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
694 environmentId={environmentId}
695 threadId={threadId}
696 {...(draftId ? { draftId } : {})}
697 envLocked={envLocked}
698 {...(forceNewWorktree
699 ? { effectiveEnvModeOverride: "worktree" }
700 : effectiveEnvModeOverride
701 ? { effectiveEnvModeOverride }
702 : {})}
703 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
704 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
705 startFromOrigin={startFromOrigin}
706 onStartFromOriginChange={onStartFromOriginChange}
707 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
708 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
709 />
710 ) : null}
711 </ComposerSurface.ContextStrip>
712 );
713});