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