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