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