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