Open History to see the last commit
1import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
2import { readLocalApi } from "../localApi";
3import { stackedThreadToast, toastManager } from "./ui/toast";
4import { ComposerContextLabel } from "./ComposerContextLabel";
5import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
6import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
7import {
8 ChevronDownIcon,
9 FolderGit2Icon,
10 FolderGitIcon,
11 FolderIcon,
12 ScaleIcon,
13} from "lucide-react";
14import {
15 type Ref,
16 type MouseEvent as ReactMouseEvent,
17 memo,
18 useImperativeHandle,
19 useEffect,
20 useEffectEvent,
21 useLayoutEffect,
22 useRef,
23 useState,
24} from "react";
25
26import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
27import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
28import { useProject, useQuietThreadShell, useThreadShellsForProjectRefs } from "../state/entities";
29import {
30 type EnvMode,
31 type EnvironmentOption,
32 resolveContextStripLabelsCompact,
33 resolveCurrentWorkspaceLabel,
34 resolveEnvModeLabel,
35 resolveLockedWorkspaceLabel,
36 resolvePreviousWorktreeLabel,
37 resolvePreviousWorktreeSeed,
38 shouldShowEnvironmentIndicator,
39} from "./BranchToolbar.logic";
40import {
41 BranchToolbarBranchSelector,
42 type BranchToolbarBranchSelectorHandle,
43} from "./BranchToolbarBranchSelector";
44import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
45import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
46import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
47import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
48import {
49 THREAD_DETAILS_PANEL_ICON_CLASS,
50 THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
51} from "./chat/threadDetailsPanelStyles";
52import { ComposerControl } from "./chat/ComposerControl";
53import {
54 Menu,
55 MenuGroup,
56 MenuGroupLabel,
57 MenuPopup,
58 MenuRadioGroup,
59 MenuRadioItem,
60 MenuSeparator,
61 MenuTrigger,
62} from "./ui/menu";
63import { Separator } from "./ui/separator";
64import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
65import { MiddleTruncate } from "./ui/middle-truncate";
66import { ComposerSurface } from "./chat/ComposerSurface";
67import { useComposerMenuProps } from "./chat/composerEventScope";
68import { measureRestingComposerControls } from "./chat/restingComposerControlsMeasurement";
69import { resolveRestingComposerControlsNaturalWidth } from "./composerFooterLayout";
70import { cn } from "~/lib/utils";
71import { observeResize } from "~/lib/observeResize";
72
73export interface BranchToolbarHandle {
74 openBranchPicker: () => void;
75 usePreviousWorktree: () => void;
76}
77
78interface BranchToolbarProps {
79 layout?: "composer" | "panel";
80 panelSection?: "all" | "workspace" | "branch";
81 forceNewWorktree?: boolean;
82 ref?: Ref<BranchToolbarHandle>;
83 environmentId: EnvironmentId;
84 threadId: ThreadId;
85 showGitControls: boolean;
86 draftId?: DraftId;
87 onEnvModeChange: (mode: EnvMode) => void;
88 envMode: EnvMode;
89 activeThreadBranchOverride?: string | null;
90 onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
91 startFromOrigin: boolean;
92 onStartFromOriginChange: (startFromOrigin: boolean) => void;
93 autoEnvironmentLabel?: string | undefined;
94 onAutoEnvironment?: (() => void) | undefined;
95 envLocked: boolean;
96 onCheckoutPullRequestRequest?: (reference: string) => void;
97 onComposerFocusRequest?: () => void;
98 availableEnvironments?: readonly EnvironmentOption[];
99 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
100 composerControlsHostRef?: (element: HTMLDivElement | null) => void;
101 contextStripVisible?: boolean;
102}
103
104function showWorkspaceContextMenu(event: ReactMouseEvent, workspacePath: string) {
105 const api = readLocalApi();
106 if (!api) return;
107 event.preventDefault();
108 event.stopPropagation();
109 void api.contextMenu
110 .show([{ id: "copy-path", label: "Copy full path", icon: "copy" }], {
111 x: event.clientX,
112 y: event.clientY,
113 })
114 .then((action) => {
115 if (action !== "copy-path") return;
116 void writeTextToClipboard(workspacePath, "workspace path").then(
117 (didCopy) => {
118 if (didCopy) {
119 toastManager.add({
120 type: "success",
121 title: "Path copied",
122 description: workspacePath,
123 });
124 }
125 },
126 (error: unknown) => {
127 toastManager.add(
128 stackedThreadToast({
129 type: "error",
130 title: "Failed to copy path",
131 description: error instanceof Error ? error.message : "An error occurred.",
132 }),
133 );
134 },
135 );
136 });
137}
138
139interface RunContextSelectorProps {
140 displayMode?: "toolbar" | "panel";
141 workspaceRoot?: string;
142 forceNewWorktree: boolean;
143 autoEnvironmentLabel?: string | undefined;
144 onAutoEnvironment?: (() => void) | undefined;
145 envLocked: boolean;
146 envModeLocked: boolean;
147 environmentId: EnvironmentId;
148 availableEnvironments: readonly EnvironmentOption[] | undefined;
149 showEnvironmentPicker: boolean;
150 showEnvironmentIndicator: boolean;
151 onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
152 effectiveEnvMode: EnvMode;
153 activeWorktreePath: string | null;
154 onEnvModeChange: (mode: EnvMode) => void;
155 previousWorktreeLabel: string | null;
156 previousWorktreeBranch: string | null;
157 onUsePreviousWorktree: () => void;
158}
159
160const RunContextSelector = memo(function RunContextSelector({
161 displayMode = "toolbar",
162 workspaceRoot,
163 forceNewWorktree,
164 autoEnvironmentLabel,
165 onAutoEnvironment,
166 envLocked,
167 envModeLocked,
168 environmentId,
169 availableEnvironments,
170 showEnvironmentPicker,
171 showEnvironmentIndicator,
172 onEnvironmentChange,
173 effectiveEnvMode,
174 activeWorktreePath,
175 onEnvModeChange,
176 previousWorktreeLabel,
177 previousWorktreeBranch,
178 onUsePreviousWorktree,
179}: RunContextSelectorProps) {
180 const composerFloatingLayerProps = useComposerMenuProps();
181 const activeEnvironment =
182 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
183 const WorkspaceIcon =
184 effectiveEnvMode === "worktree"
185 ? FolderGit2Icon
186 : activeWorktreePath
187 ? FolderGitIcon
188 : FolderIcon;
189 const workspaceLabel = forceNewWorktree
190 ? resolveEnvModeLabel("worktree")
191 : envModeLocked
192 ? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode)
193 : effectiveEnvMode === "worktree"
194 ? resolveEnvModeLabel("worktree")
195 : resolveCurrentWorkspaceLabel(activeWorktreePath);
196 const isPanel = displayMode === "panel";
197 const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker));
198 const workspacePath =
199 forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath)
200 ? null
201 : (activeWorktreePath ?? workspaceRoot);
202 const handleContextMenu = (event: ReactMouseEvent) => {
203 if (isPanel && workspacePath) {
204 showWorkspaceContextMenu(event, workspacePath);
205 }
206 };
207 const workspaceIcon = (
208 <Tooltip>
209 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
210 <WorkspaceIcon
211 className={
212 isPanel
213 ? THREAD_DETAILS_PANEL_ICON_CLASS
214 : cn("size-3 shrink-0", showEnvironmentIndicator && "mx-0!")
215 }
216 />
217 </TooltipTrigger>
218 <TooltipPopup>
219 {isPanel
220 ? forceNewWorktree
221 ? "Each model starts in its own worktree."
222 : (workspacePath ?? workspaceLabel)
223 : workspaceLabel}
224 </TooltipPopup>
225 </Tooltip>
226 );
227 const icon = showEnvironmentIndicator ? (
228 // Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
229 // out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
230 <span className="inline-flex shrink-0 items-center gap-0.5">
231 <Tooltip>
232 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
233 {autoEnvironmentLabel ? (
234 <ScaleIcon
235 className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0 mx-0!"}
236 aria-hidden="true"
237 />
238 ) : (
239 <EnvironmentMachineIcon
240 kind={activeEnvironment?.machine ?? "server"}
241 className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0 mx-0!"}
242 />
243 )}
244 </TooltipTrigger>
245 <TooltipPopup>{autoEnvironmentLabel ?? activeEnvironment?.label ?? "Run on"}</TooltipPopup>
246 </Tooltip>
247 {workspaceIcon}
248 </span>
249 ) : (
250 workspaceIcon
251 );
252 const triggerContent = (
253 <>
254 {icon}
255 <ComposerContextLabel displayMode={displayMode}>
256 {autoEnvironmentLabel ??
257 (showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel)}
258 </ComposerContextLabel>
259 </>
260 );
261
262 if (isLocked) {
263 return (
264 <span
265 className={cn(
266 "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",
267 isPanel && "max-w-full",
268 isPanel && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
269 )}
270 onContextMenu={handleContextMenu}
271 aria-label={isPanel ? "Run context" : undefined}
272 data-composer-context-control
273 >
274 {triggerContent}
275 </span>
276 );
277 }
278
279 return (
280 <Menu>
281 <MenuTrigger
282 render={isPanel ? <ThreadDetailsControl part="select" /> : <ComposerControl size="xs" />}
283 className={isPanel ? undefined : "min-w-0 max-w-[48%] flex-initial justify-start"}
284 onContextMenu={handleContextMenu}
285 onMouseDownCapture={
286 isPanel
287 ? (event) => {
288 if (event.button !== 0 || event.ctrlKey) event.stopPropagation();
289 }
290 : undefined
291 }
292 aria-label={isPanel ? "Run context" : undefined}
293 data-composer-context-control
294 data-composer-shortcut={[
295 showEnvironmentPicker && !envLocked ? "composer.host" : "",
296 !envModeLocked ? "composer.workspace" : "",
297 ].join(" ")}
298 >
299 {triggerContent}
300 {!isPanel ? <ChevronDownIcon className="size-3 shrink-0 opacity-50" /> : null}
301 </MenuTrigger>
302 <MenuPopup
303 align="start"
304 side={isPanel ? "bottom" : "top"}
305 className={
306 isPanel
307 ? "w-(--anchor-width)"
308 : previousWorktreeLabel
309 ? "w-[min(21rem,calc(100vw-2rem))]"
310 : undefined
311 }
312 {...(!isPanel ? composerFloatingLayerProps : {})}
313 >
314 {showEnvironmentPicker && availableEnvironments && onEnvironmentChange ? (
315 <>
316 <MenuGroup>
317 <MenuGroupLabel>Run on</MenuGroupLabel>
318 <MenuRadioGroup
319 value={autoEnvironmentLabel ? "auto" : environmentId}
320 onValueChange={(value) =>
321 value === "auto"
322 ? onAutoEnvironment?.()
323 : onEnvironmentChange(value as EnvironmentId)
324 }
325 >
326 {onAutoEnvironment && (
327 <MenuRadioItem
328 value="auto"
329 disabled={envLocked}
330 closeOnClick
331 onClick={() => {
332 if (autoEnvironmentLabel) onAutoEnvironment?.();
333 }}
334 >
335 <span className="flex min-w-0 items-center gap-1.5">
336 <ScaleIcon className="size-3" aria-hidden="true" />
337 <span className="min-w-0 truncate">
338 {autoEnvironmentLabel ?? "Auto balance"}
339 </span>
340 </span>
341 </MenuRadioItem>
342 )}
343 {availableEnvironments.map((env) => (
344 <MenuRadioItem
345 key={env.environmentId}
346 disabled={envLocked}
347 value={env.environmentId}
348 closeOnClick
349 >
350 <span className="flex min-w-0 items-center gap-1.5">
351 <EnvironmentMachineIcon kind={env.machine} className="size-3" />
352 <span className="min-w-0 truncate">{env.label}</span>
353 </span>
354 </MenuRadioItem>
355 ))}
356 </MenuRadioGroup>
357 </MenuGroup>
358 <MenuSeparator />
359 </>
360 ) : null}
361 <MenuGroup>
362 <MenuGroupLabel>Workspace</MenuGroupLabel>
363 <MenuRadioGroup
364 value={effectiveEnvMode}
365 onValueChange={(value) => {
366 if (value === "previous-worktree") {
367 onUsePreviousWorktree();
368 return;
369 }
370 onEnvModeChange(value as EnvMode);
371 }}
372 >
373 <MenuRadioItem disabled={envModeLocked || forceNewWorktree} value="local" closeOnClick>
374 <span className="flex min-w-0 items-center gap-1.5">
375 {activeWorktreePath ? (
376 <FolderGitIcon className="size-3" />
377 ) : (
378 <FolderIcon className="size-3" />
379 )}
380 <MiddleTruncate value={resolveCurrentWorkspaceLabel(activeWorktreePath)} />
381 </span>
382 </MenuRadioItem>
383 <MenuRadioItem disabled={envModeLocked} value="worktree" closeOnClick>
384 <span className="flex min-w-0 items-center gap-1.5">
385 <FolderGit2Icon className="size-3" />
386 <span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
387 </span>
388 </MenuRadioItem>
389 {previousWorktreeLabel ? (
390 <MenuRadioItem disabled={envModeLocked} value="previous-worktree" closeOnClick>
391 <PreviousWorktreeItemContent branch={previousWorktreeBranch} />
392 </MenuRadioItem>
393 ) : null}
394 </MenuRadioGroup>
395 </MenuGroup>
396 </MenuPopup>
397 </Menu>
398 );
399});
400
401const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
402const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
403const COMPOSER_CONTEXT_LABEL_SELECTOR = "[data-composer-label]";
404
405/**
406 * Reading one element's scrollWidth drops the tail when the label is hidden or
407 * squeezed, and the strip then flips between labels and icons on every measure.
408 */
409function labelTextWidth(label: HTMLElement, range: Range): number {
410 const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
411 let width = 0;
412 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
413 range.selectNodeContents(node);
414 width += range.getBoundingClientRect().width;
415 }
416 const motion = label.querySelector<HTMLElement>("[data-composer-label-motion]");
417 const maxWidth = motion ? Number.parseFloat(getComputedStyle(motion).maxWidth) : Number.NaN;
418 return Number.isFinite(maxWidth) ? Math.min(width, maxWidth) : width;
419}
420
421function useLabelsOverflow(element: HTMLDivElement | null): boolean {
422 const [overflows, setOverflows] = useState(false);
423 const pendingLabelRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
424 const labelAnimationsRef = useRef(new Map<HTMLElement, Animation>());
425 const measure = useEffectEvent(() => {
426 const current = element;
427 const compact = overflows;
428 if (!current) return;
429 const available = current.clientWidth;
430 if (available === 0) return;
431 const contentWidth = (parent: Element): number => {
432 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
433 let width = 0;
434 let counted = 0;
435 for (const child of parent.children) {
436 if (!(child instanceof HTMLElement)) continue;
437 if (child.offsetWidth === 0) continue;
438 const style = getComputedStyle(child);
439 const position = style.position;
440 if (position === "absolute" || position === "fixed") continue;
441 width +=
442 child.offsetWidth +
443 (Number.parseFloat(style.marginInlineStart) || 0) +
444 (Number.parseFloat(style.marginInlineEnd) || 0);
445 counted += 1;
446 }
447 return width + gap * Math.max(0, counted - 1);
448 };
449 const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
450 let needed = 0;
451 let groups = 0;
452 for (const child of current.children) {
453 if (!(child instanceof HTMLElement)) continue;
454 // Reserve the natural width of the controls inside it, blocks in overflow
455 // included, so Git labels compact before squeezing out the model picker.
456 // Reserving only the visible controls would let the labels expand into
457 // room the composer just freed, shrink the host, and hide the controls
458 // again.
459 const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
460 ? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
461 : null;
462 const hostedMeasurement = hostedControls
463 ? measureRestingComposerControls(hostedControls)
464 : null;
465 const width = hostedMeasurement
466 ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
467 : contentWidth(hostedControls ?? child);
468 if (width <= 1) continue;
469 groups += 1;
470 needed += width;
471 }
472 needed += stripGap * Math.max(0, groups - 1);
473 const range = document.createRange();
474 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
475 needed += Math.max(0, labelTextWidth(label, range) - label.getBoundingClientRect().width);
476 }
477 const nextOverflows = resolveContextStripLabelsCompact({
478 compact,
479 neededWidth: needed,
480 availableWidth: available,
481 });
482 if (nextOverflows !== compact) {
483 pendingLabelRectsRef.current = new Map(
484 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
485 (label) => [label, label.getBoundingClientRect()],
486 ),
487 );
488 }
489 setOverflows(nextOverflows);
490 });
491
492 useLayoutEffect(() => {
493 const previousRects = pendingLabelRectsRef.current;
494 if (!previousRects) return;
495 pendingLabelRectsRef.current = null;
496
497 for (const animation of labelAnimationsRef.current.values()) {
498 animation.cancel();
499 }
500 labelAnimationsRef.current.clear();
501
502 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
503
504 for (const [label, previousRect] of previousRects) {
505 if (!label.isConnected) continue;
506 const nextWidth = label.getBoundingClientRect().width;
507 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
508
509 const animation = label.animate(
510 [
511 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
512 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
513 ],
514 {
515 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
516 easing: COMPOSER_CONTEXT_MOTION_EASING,
517 fill: "backwards",
518 },
519 );
520 labelAnimationsRef.current.set(label, animation);
521 animation.addEventListener(
522 "finish",
523 () => {
524 if (labelAnimationsRef.current.get(label) === animation) {
525 labelAnimationsRef.current.delete(label);
526 }
527 },
528 { once: true },
529 );
530 }
531 });
532
533 useEffect(
534 () => () => {
535 for (const animation of labelAnimationsRef.current.values()) {
536 animation.cancel();
537 }
538 },
539 [],
540 );
541
542 useLayoutEffect(() => {
543 // oxlint-disable-next-line react/set-state-in-effect -- The label mode comes from measuring the committed DOM, which render cannot read.
544 measure();
545 });
546
547 useEffect(() => {
548 if (!element) return;
549 const stopObserving = observeResize(element, measure);
550 document.fonts.addEventListener("loadingdone", measure);
551 return () => {
552 stopObserving();
553 document.fonts.removeEventListener("loadingdone", measure);
554 };
555 }, [element]);
556
557 return overflows;
558}
559
560export const BranchToolbar = memo(function BranchToolbar({
561 layout = "composer",
562 panelSection = "all",
563 forceNewWorktree = false,
564 ref,
565 environmentId,
566 threadId,
567 showGitControls,
568 draftId,
569 onEnvModeChange,
570 envMode,
571 activeThreadBranchOverride,
572 onActiveThreadBranchOverrideChange,
573 startFromOrigin,
574 onStartFromOriginChange,
575 autoEnvironmentLabel,
576 onAutoEnvironment,
577 envLocked,
578 onCheckoutPullRequestRequest,
579 onComposerFocusRequest,
580 availableEnvironments,
581 onEnvironmentChange,
582 composerControlsHostRef,
583 contextStripVisible = true,
584}: BranchToolbarProps) {
585 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
586 const threadRef = scopeThreadRef(environmentId, threadId);
587 const draftThread = useComposerDraftStore((store) =>
588 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
589 );
590 const serverThread = useQuietThreadShell(threadRef);
591 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
592 const activeProjectRef = serverThread
593 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
594 : draftThread
595 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
596 : null;
597 const activeProject = useProject(activeProjectRef);
598 const hasActiveThread = serverThread !== null || draftThread !== null;
599 const activeWorktreePath = forceNewWorktree
600 ? null
601 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
602 const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode;
603 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
604
605 const canUsePreviousWorktree =
606 draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree;
607 const projectRefsForWorktreeLookup =
608 canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : [];
609 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
610 const previousWorktreeSeed = canUsePreviousWorktree
611 ? resolvePreviousWorktreeSeed({
612 threads: projectThreads,
613 currentWorktreePath: activeWorktreePath,
614 })
615 : null;
616 const previousWorktreeLabel = previousWorktreeSeed
617 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
618 : null;
619 const onUsePreviousWorktree = () => {
620 if (!previousWorktreeSeed || !activeProjectRef) return;
621 setDraftThreadContext(draftId ?? threadRef, {
622 branch: previousWorktreeSeed.branch,
623 worktreePath: previousWorktreeSeed.worktreePath,
624 envMode: "worktree",
625 projectRef: activeProjectRef,
626 });
627 };
628
629 useImperativeHandle(
630 ref,
631 () => ({
632 openBranchPicker: () => branchSelectorRef.current?.open(),
633 usePreviousWorktree: () => {
634 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
635 onUsePreviousWorktree();
636 onComposerFocusRequest?.();
637 },
638 }),
639 [
640 canUsePreviousWorktree,
641 onComposerFocusRequest,
642 onUsePreviousWorktree,
643 previousWorktreeSeed,
644 showGitControls,
645 ],
646 );
647
648 const showEnvironmentPicker = Boolean(
649 availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
650 );
651 const activeEnvironmentOption =
652 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
653 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
654 activeEnvironment: activeEnvironmentOption,
655 canPickEnvironment: showEnvironmentPicker,
656 });
657 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
658 const labelsOverflow = useLabelsOverflow(stripElement);
659
660 if (!hasActiveThread || !activeProject) return null;
661
662 if (layout === "panel") {
663 return (
664 <div className="flex w-full flex-col" data-thread-panel-run-context>
665 {panelSection !== "branch" ? (
666 <RunContextSelector
667 displayMode="panel"
668 workspaceRoot={activeProject.workspaceRoot}
669 forceNewWorktree={forceNewWorktree}
670 autoEnvironmentLabel={autoEnvironmentLabel}
671 onAutoEnvironment={onAutoEnvironment}
672 envLocked={envLocked}
673 envModeLocked={envModeLocked}
674 environmentId={environmentId}
675 availableEnvironments={availableEnvironments}
676 showEnvironmentPicker={showEnvironmentPicker}
677 showEnvironmentIndicator={activeEnvironmentOption !== null}
678 onEnvironmentChange={onEnvironmentChange}
679 effectiveEnvMode={effectiveEnvMode}
680 activeWorktreePath={activeWorktreePath}
681 onEnvModeChange={onEnvModeChange}
682 previousWorktreeLabel={previousWorktreeLabel}
683 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
684 onUsePreviousWorktree={onUsePreviousWorktree}
685 />
686 ) : null}
687 {panelSection !== "workspace" ? (
688 <BranchToolbarBranchSelector
689 displayMode="panel"
690 className="w-full"
691 environmentId={environmentId}
692 threadId={threadId}
693 {...(draftId ? { draftId } : {})}
694 envLocked={envLocked}
695 effectiveEnvModeOverride={effectiveEnvMode}
696 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
697 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
698 startFromOrigin={startFromOrigin}
699 onStartFromOriginChange={onStartFromOriginChange}
700 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
701 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
702 />
703 ) : null}
704 </div>
705 );
706 }
707
708 return (
709 <ComposerSurface.ContextStrip
710 ref={setStripElement}
711 data-compact={labelsOverflow ? "" : undefined}
712 className={cn(
713 "gap-1 text-xs font-normal text-muted-foreground/70",
714 // A non-Git strip with no visible composer controls should occupy no
715 // space, but its host must retain a prospective width so controls can
716 // become visible again when the chat view grows.
717 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
718 )}
719 >
720 {showGitControls ? (
721 <div className="contents @3xl/composer-surface:hidden">
722 <RunContextSelector
723 forceNewWorktree={forceNewWorktree}
724 autoEnvironmentLabel={autoEnvironmentLabel}
725 onAutoEnvironment={onAutoEnvironment}
726 envLocked={envLocked}
727 envModeLocked={envModeLocked}
728 environmentId={environmentId}
729 availableEnvironments={availableEnvironments}
730 showEnvironmentPicker={showEnvironmentPicker}
731 showEnvironmentIndicator={showEnvironmentIndicator}
732 onEnvironmentChange={onEnvironmentChange}
733 effectiveEnvMode={effectiveEnvMode}
734 activeWorktreePath={activeWorktreePath}
735 onEnvModeChange={onEnvModeChange}
736 previousWorktreeLabel={previousWorktreeLabel}
737 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
738 onUsePreviousWorktree={onUsePreviousWorktree}
739 />
740 </div>
741 ) : null}
742 {showGitControls || showEnvironmentIndicator ? (
743 <div
744 className={cn(
745 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
746 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
747 composerControlsHostRef ? "shrink" : "flex-1",
748 )}
749 >
750 {showEnvironmentIndicator && availableEnvironments && (
751 <>
752 <BranchToolbarEnvironmentSelector
753 autoEnvironmentLabel={autoEnvironmentLabel}
754 onAutoEnvironment={onAutoEnvironment}
755 envLocked={envLocked}
756 environmentId={environmentId}
757 availableEnvironments={availableEnvironments}
758 {...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
759 />
760 {showGitControls ? (
761 <Separator
762 orientation="vertical"
763 className="mx-0.5 h-3.5!"
764 data-composer-context-control
765 />
766 ) : null}
767 </>
768 )}
769 {showGitControls ? (
770 <BranchToolbarEnvModeSelector
771 forceNewWorktree={forceNewWorktree}
772 envLocked={envModeLocked}
773 effectiveEnvMode={effectiveEnvMode}
774 activeWorktreePath={activeWorktreePath}
775 onEnvModeChange={onEnvModeChange}
776 previousWorktreeLabel={previousWorktreeLabel}
777 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
778 onUsePreviousWorktree={onUsePreviousWorktree}
779 />
780 ) : null}
781 </div>
782 ) : null}
783
784 {composerControlsHostRef ? (
785 <div
786 ref={composerControlsHostRef}
787 data-composer-context-control
788 data-chat-resting-composer-controls-host="true"
789 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
790 />
791 ) : null}
792
793 {showGitControls ? (
794 <BranchToolbarBranchSelector
795 forceNewWorktree={forceNewWorktree}
796 ref={branchSelectorRef}
797 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
798 environmentId={environmentId}
799 threadId={threadId}
800 {...(draftId ? { draftId } : {})}
801 envLocked={envLocked}
802 effectiveEnvModeOverride={effectiveEnvMode}
803 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
804 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
805 startFromOrigin={startFromOrigin}
806 onStartFromOriginChange={onStartFromOriginChange}
807 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
808 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
809 />
810 ) : null}
811 </ComposerSurface.ContextStrip>
812 );
813});