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

BranchToolbar.tsx

769 lines29.0 KB

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