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

BranchToolbar.tsx

759 lines28.7 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 resolveLockedWorkspaceLabel,
33 resolvePreviousWorktreeLabel,
34 resolvePreviousWorktreeSeed,
35 shouldShowEnvironmentIndicator,
36} from "./BranchToolbar.logic";
37import {
38 BranchToolbarBranchSelector,
39 type BranchToolbarBranchSelectorHandle,
40} from "./BranchToolbarBranchSelector";
41import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
42import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
43import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
44import { ComposerControl } from "./chat/ComposerControl";
45import {
46 Menu,
47 MenuGroup,
48 MenuGroupLabel,
49 MenuPopup,
50 MenuRadioGroup,
51 MenuRadioItem,
52 MenuSeparator,
53 MenuTrigger,
54} from "./ui/menu";
55import { Separator } from "./ui/separator";
56import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
57import { MiddleTruncate } from "./ui/middle-truncate";
58import { ComposerSurface } from "./chat/ComposerSurface";
59import { useComposerMenuProps } from "./chat/composerEventScope";
60import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement";
61import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout";
62import { cn } from "~/lib/utils";
63​
64export interface BranchToolbarHandle {
65 openBranchPicker: () => void;
66 usePreviousWorktree: () => void;
68​
69interface BranchToolbarProps {
70 layout?: "composer" | "panel";
71 panelSection?: "all" | "workspace" | "branch";
72 forceNewWorktree?: boolean;
73 ref?: Ref<BranchToolbarHandle>;
74 environmentId: EnvironmentId;
75 threadId: ThreadId;
76 showGitControls: boolean;
77 draftId?: DraftId;
78 onEnvModeChange: (mode: EnvMode) => void;
79 /** The thread's env mode as ChatView resolves it. */
80 envMode: 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, effectiveEnvMode)
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 envMode,
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 = forceNewWorktree ? "worktree" : envMode;
547 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
548​
549 // "Previous worktree" hops a draft into the most recently active worktree
550 // of this project — the "keep going where I just was" follow-up flow. Only
551 // drafts can hop; started server threads have their workspace pinned.
552 const canUsePreviousWorktree =
553 draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree;
554 const projectRefsForWorktreeLookup = useMemo(
555 () => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
556 [canUsePreviousWorktree, activeProjectRef],
557 );
558 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
559 const previousWorktreeSeed = useMemo(
560 () =>
561 canUsePreviousWorktree
562 ? resolvePreviousWorktreeSeed({
563 threads: projectThreads,
564 currentWorktreePath: activeWorktreePath,
565 })
566 : null,
567 [activeWorktreePath, canUsePreviousWorktree, projectThreads],
568 );
569 const previousWorktreeLabel = previousWorktreeSeed
570 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
571 : null;
572 const onUsePreviousWorktree = useCallback(() => {
573 if (!previousWorktreeSeed || !activeProjectRef) return;
574 // Same shape the branch selector writes when picking a branch that
575 // already lives in a worktree: point the draft at the existing tree.
576 setDraftThreadContext(draftId ?? threadRef, {
577 branch: previousWorktreeSeed.branch,
578 worktreePath: previousWorktreeSeed.worktreePath,
579 envMode: "worktree",
580 projectRef: activeProjectRef,
581 });
582 }, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
583​
584 useImperativeHandle(
585 ref,
586 () => ({
587 openBranchPicker: () => branchSelectorRef.current?.open(),
588 usePreviousWorktree: () => {
589 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
590 onUsePreviousWorktree();
591 onComposerFocusRequest?.();
592 },
593 }),
594 [
595 canUsePreviousWorktree,
596 onComposerFocusRequest,
597 onUsePreviousWorktree,
598 previousWorktreeSeed,
599 showGitControls,
600 ],
601 );
602​
603 const showEnvironmentPicker = Boolean(
604 availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
605 );
606 const activeEnvironmentOption =
607 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
608 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
609 activeEnvironment: activeEnvironmentOption,
610 canPickEnvironment: showEnvironmentPicker,
611 });
612 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
613 const labelsOverflow = useLabelsOverflow(stripElement);
614​
615 if (!hasActiveThread || !activeProject) return null;
616​
617 if (layout === "panel") {
618 return (
619 <div className="flex w-full flex-col" data-thread-panel-run-context>
620 {panelSection !== "branch" ? (
621 <BranchToolbarEnvModeSelector
622 displayMode="panel"
623 envLocked={envModeLocked}
624 effectiveEnvMode={effectiveEnvMode}
625 activeWorktreePath={activeWorktreePath}
626 workspaceRoot={activeProject.workspaceRoot}
627 onEnvModeChange={onEnvModeChange}
628 />
629 ) : null}
630 {panelSection !== "workspace" ? (
631 <BranchToolbarBranchSelector
632 displayMode="panel"
633 className="w-full"
634 environmentId={environmentId}
635 threadId={threadId}
636 {...(draftId ? { draftId } : {})}
637 envLocked={envLocked}
638 effectiveEnvModeOverride={effectiveEnvMode}
639 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
640 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
641 startFromOrigin={startFromOrigin}
642 onStartFromOriginChange={onStartFromOriginChange}
643 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
644 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
645 />
646 ) : null}
647 </div>
648 );
649 }
650​
651 return (
652 <ComposerSurface.ContextStrip
653 ref={setStripElement}
654 data-compact={labelsOverflow ? "" : undefined}
655 className={cn(
656 "gap-1 text-xs font-normal text-muted-foreground/70",
657 // A non-Git strip with no visible composer controls should occupy no
658 // space, but its host must retain a prospective width so controls can
659 // become visible again when the chat view grows.
660 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
661 )}
662 >
663 {showGitControls ? (
664 <div className="contents @3xl/composer-surface:hidden">
665 <MobileRunContextSelector
666 forceNewWorktree={forceNewWorktree}
667 autoEnvironmentLabel={autoEnvironmentLabel}
668 onAutoEnvironment={onAutoEnvironment}
669 envLocked={envLocked}
670 envModeLocked={envModeLocked}
671 environmentId={environmentId}
672 availableEnvironments={availableEnvironments}
673 showEnvironmentPicker={showEnvironmentPicker}
674 showEnvironmentIndicator={showEnvironmentIndicator}
675 onEnvironmentChange={onEnvironmentChange}
676 effectiveEnvMode={effectiveEnvMode}
677 activeWorktreePath={activeWorktreePath}
678 onEnvModeChange={onEnvModeChange}
679 previousWorktreeLabel={previousWorktreeLabel}
680 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
681 onUsePreviousWorktree={onUsePreviousWorktree}
682 />
683 </div>
684 ) : null}
685 {showGitControls || showEnvironmentIndicator ? (
686 <div
687 className={cn(
688 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
689 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
690 composerControlsHostRef ? "shrink" : "flex-1",
691 )}
692 >
693 {showEnvironmentIndicator && availableEnvironments && (
694 <>
695 <BranchToolbarEnvironmentSelector
696 autoEnvironmentLabel={autoEnvironmentLabel}
697 onAutoEnvironment={onAutoEnvironment}
698 envLocked={envLocked}
699 environmentId={environmentId}
700 availableEnvironments={availableEnvironments}
701 {...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
702 />
703 {showGitControls ? (
704 <Separator
705 orientation="vertical"
706 className="mx-0.5 h-3.5!"
707 data-composer-context-control
708 />
709 ) : null}
710 </>
711 )}
712 {showGitControls ? (
713 <BranchToolbarEnvModeSelector
714 forceNewWorktree={forceNewWorktree}
715 envLocked={envModeLocked}
716 effectiveEnvMode={effectiveEnvMode}
717 activeWorktreePath={activeWorktreePath}
718 onEnvModeChange={onEnvModeChange}
719 previousWorktreeLabel={previousWorktreeLabel}
720 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
721 onUsePreviousWorktree={onUsePreviousWorktree}
722 />
723 ) : null}
724 </div>
725 ) : null}
726​
727 {composerControlsHostRef ? (
728 // The host takes whatever the workspace and branch controls leave
729 // over, in both strip layouts, so a collapsed composer can show its
730 // model and mode controls wherever they fit.
731 <div
732 ref={composerControlsHostRef}
733 data-composer-context-control
734 data-chat-resting-composer-controls-host="true"
735 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
736 />
737 ) : null}
738​
739 {showGitControls ? (
740 <BranchToolbarBranchSelector
741 forceNewWorktree={forceNewWorktree}
742 ref={branchSelectorRef}
743 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
744 environmentId={environmentId}
745 threadId={threadId}
746 {...(draftId ? { draftId } : {})}
747 envLocked={envLocked}
748 effectiveEnvModeOverride={effectiveEnvMode}
749 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
750 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
751 startFromOrigin={startFromOrigin}
752 onStartFromOriginChange={onStartFromOriginChange}
753 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
754 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
755 />
756 ) : null}
757 </ComposerSurface.ContextStrip>
758 );
759});