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

BranchToolbar.tsx

819 lines30.0 KB

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;
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;
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 });
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;
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;
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 stripWidth = current.clientWidth;
430 if (stripWidth === 0) return;
431 const stripStyle = getComputedStyle(current);
432 const available =
433 stripWidth -
434 (Number.parseFloat(stripStyle.paddingInlineStart) || 0) -
435 (Number.parseFloat(stripStyle.paddingInlineEnd) || 0);
436 const contentWidth = (parent: Element): number => {
437 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
438 let width = 0;
439 let counted = 0;
440 for (const child of parent.children) {
441 if (!(child instanceof HTMLElement)) continue;
442 if (child.offsetWidth === 0) continue;
443 const style = getComputedStyle(child);
444 const position = style.position;
445 if (position === "absolute" || position === "fixed") continue;
446 width +=
447 child.offsetWidth +
448 (Number.parseFloat(style.marginInlineStart) || 0) +
449 (Number.parseFloat(style.marginInlineEnd) || 0);
450 counted += 1;
451 }
452 return width + gap * Math.max(0, counted - 1);
453 };
454 const stripGap = Number.parseFloat(stripStyle.columnGap) || 0;
455 let needed = 0;
456 let groups = 0;
457 for (const child of current.children) {
458 if (!(child instanceof HTMLElement)) continue;
459 // Reserve the natural width of the controls inside it, blocks in overflow
460 // included, so Git labels compact before squeezing out the model picker.
461 // Reserving only the visible controls would let the labels expand into
462 // room the composer just freed, shrink the host, and hide the controls
463 // again.
464 const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
465 ? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
466 : null;
467 const hostedMeasurement = hostedControls
468 ? measureRestingComposerControls(hostedControls)
469 : null;
470 const width = hostedMeasurement
471 ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
472 : contentWidth(hostedControls ?? child);
473 if (width <= 1) continue;
474 groups += 1;
475 needed += width;
476 }
477 needed += stripGap * Math.max(0, groups - 1);
478 const range = document.createRange();
479 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
480 needed += Math.max(0, labelTextWidth(label, range) - label.getBoundingClientRect().width);
481 }
482 const nextOverflows = resolveContextStripLabelsCompact({
483 compact,
484 neededWidth: needed,
485 availableWidth: available,
486 });
487 if (nextOverflows !== compact) {
488 pendingLabelRectsRef.current = new Map(
489 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
490 (label) => [label, label.getBoundingClientRect()],
491 ),
492 );
493 }
494 setOverflows(nextOverflows);
495 });
496​
497 useLayoutEffect(() => {
498 const previousRects = pendingLabelRectsRef.current;
499 if (!previousRects) return;
500 pendingLabelRectsRef.current = null;
501​
502 for (const animation of labelAnimationsRef.current.values()) {
503 animation.cancel();
504 }
505 labelAnimationsRef.current.clear();
506​
507 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
508​
509 for (const [label, previousRect] of previousRects) {
510 if (!label.isConnected) continue;
511 const nextWidth = label.getBoundingClientRect().width;
512 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
513​
514 const animation = label.animate(
515 [
516 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
517 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
518 ],
519 {
520 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
521 easing: COMPOSER_CONTEXT_MOTION_EASING,
522 fill: "backwards",
523 },
524 );
525 labelAnimationsRef.current.set(label, animation);
526 animation.addEventListener(
527 "finish",
528 () => {
529 if (labelAnimationsRef.current.get(label) === animation) {
530 labelAnimationsRef.current.delete(label);
531 }
532 },
533 { once: true },
534 );
535 }
536 });
537​
538 useEffect(
539 () => () => {
540 for (const animation of labelAnimationsRef.current.values()) {
541 animation.cancel();
542 }
543 },
544 [],
545 );
546​
547 useLayoutEffect(() => {
548 // oxlint-disable-next-line react/set-state-in-effect -- The label mode comes from measuring the committed DOM, which render cannot read.
549 measure();
550 });
551​
552 useEffect(() => {
553 if (!element) return;
554 const stopObserving = observeResize(element, measure);
555 document.fonts.addEventListener("loadingdone", measure);
556 return () => {
557 stopObserving();
558 document.fonts.removeEventListener("loadingdone", measure);
559 };
560 }, [element]);
561​
562 return overflows;
564​
565export const BranchToolbar = memo(function BranchToolbar({
566 layout = "composer",
567 panelSection = "all",
568 forceNewWorktree = false,
569 ref,
570 environmentId,
571 threadId,
572 showGitControls,
573 draftId,
574 onEnvModeChange,
575 envMode,
576 activeThreadBranchOverride,
577 onActiveThreadBranchOverrideChange,
578 startFromOrigin,
579 onStartFromOriginChange,
580 autoEnvironmentLabel,
581 onAutoEnvironment,
582 envLocked,
583 onCheckoutPullRequestRequest,
584 onComposerFocusRequest,
585 availableEnvironments,
586 onEnvironmentChange,
587 composerControlsHostRef,
588 contextStripVisible = true,
589}: BranchToolbarProps) {
590 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
591 const threadRef = scopeThreadRef(environmentId, threadId);
592 const draftThread = useComposerDraftStore((store) =>
593 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
594 );
595 const serverThread = useQuietThreadShell(threadRef);
596 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
597 const activeProjectRef = serverThread
598 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
599 : draftThread
600 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
601 : null;
602 const activeProject = useProject(activeProjectRef);
603 const hasActiveThread = serverThread !== null || draftThread !== null;
604 const activeWorktreePath = forceNewWorktree
605 ? null
606 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
607 const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode;
608 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
609​
610 const canUsePreviousWorktree =
611 draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree;
612 const projectRefsForWorktreeLookup =
613 canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : [];
614 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
615 const previousWorktreeSeed = canUsePreviousWorktree
616 ? resolvePreviousWorktreeSeed({
617 threads: projectThreads,
618 currentWorktreePath: activeWorktreePath,
619 })
620 : null;
621 const previousWorktreeLabel = previousWorktreeSeed
622 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
623 : null;
624 const onUsePreviousWorktree = () => {
625 if (!previousWorktreeSeed || !activeProjectRef) return;
626 setDraftThreadContext(draftId ?? threadRef, {
627 branch: previousWorktreeSeed.branch,
628 worktreePath: previousWorktreeSeed.worktreePath,
629 envMode: "worktree",
630 projectRef: activeProjectRef,
631 });
632 };
633​
634 useImperativeHandle(
635 ref,
636 () => ({
637 openBranchPicker: () => branchSelectorRef.current?.open(),
638 usePreviousWorktree: () => {
639 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
640 onUsePreviousWorktree();
641 onComposerFocusRequest?.();
642 },
643 }),
644 [
645 canUsePreviousWorktree,
646 onComposerFocusRequest,
647 onUsePreviousWorktree,
648 previousWorktreeSeed,
649 showGitControls,
650 ],
651 );
652​
653 const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1;
654 const showEnvironmentPicker = hasMultipleEnvironments && onEnvironmentChange !== undefined;
655 const activeEnvironmentOption =
656 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
657 // Started threads get no handler but still show which machine they run on,
658 // matching the strip visibility ChatView computes from the same inputs.
659 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
660 activeEnvironment: activeEnvironmentOption,
661 canPickEnvironment: hasMultipleEnvironments,
662 });
663 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
664 const labelsOverflow = useLabelsOverflow(stripElement);
665​
666 if (!hasActiveThread || !activeProject) return null;
667​
668 if (layout === "panel") {
669 return (
670 <div className="flex w-full flex-col" data-thread-panel-run-context>
671 {panelSection !== "branch" ? (
672 <RunContextSelector
673 displayMode="panel"
674 workspaceRoot={activeProject.workspaceRoot}
675 forceNewWorktree={forceNewWorktree}
676 autoEnvironmentLabel={autoEnvironmentLabel}
677 onAutoEnvironment={onAutoEnvironment}
678 envLocked={envLocked}
679 envModeLocked={envModeLocked}
680 environmentId={environmentId}
681 availableEnvironments={availableEnvironments}
682 showEnvironmentPicker={showEnvironmentPicker}
683 showEnvironmentIndicator={activeEnvironmentOption !== null}
684 onEnvironmentChange={onEnvironmentChange}
685 effectiveEnvMode={effectiveEnvMode}
686 activeWorktreePath={activeWorktreePath}
687 onEnvModeChange={onEnvModeChange}
688 previousWorktreeLabel={previousWorktreeLabel}
689 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
690 onUsePreviousWorktree={onUsePreviousWorktree}
691 />
692 ) : null}
693 {panelSection !== "workspace" ? (
694 <BranchToolbarBranchSelector
695 displayMode="panel"
696 className="w-full"
697 environmentId={environmentId}
698 threadId={threadId}
699 {...(draftId ? { draftId } : {})}
700 envLocked={envLocked}
701 effectiveEnvModeOverride={effectiveEnvMode}
702 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
703 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
704 startFromOrigin={startFromOrigin}
705 onStartFromOriginChange={onStartFromOriginChange}
706 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
707 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
708 />
709 ) : null}
710 </div>
711 );
712 }
713​
714 return (
715 <ComposerSurface.ContextStrip
716 ref={setStripElement}
717 data-compact={labelsOverflow ? "" : undefined}
718 className={cn(
719 "gap-1 text-xs font-normal text-muted-foreground/70",
720 // A non-Git strip with no visible composer controls should occupy no
721 // space, but its host must retain a prospective width so controls can
722 // become visible again when the chat view grows.
723 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
724 )}
725 >
726 {showGitControls ? (
727 <div className="contents @3xl/composer-surface:hidden">
728 <RunContextSelector
729 forceNewWorktree={forceNewWorktree}
730 autoEnvironmentLabel={autoEnvironmentLabel}
731 onAutoEnvironment={onAutoEnvironment}
732 envLocked={envLocked}
733 envModeLocked={envModeLocked}
734 environmentId={environmentId}
735 availableEnvironments={availableEnvironments}
736 showEnvironmentPicker={showEnvironmentPicker}
737 showEnvironmentIndicator={showEnvironmentIndicator}
738 onEnvironmentChange={onEnvironmentChange}
739 effectiveEnvMode={effectiveEnvMode}
740 activeWorktreePath={activeWorktreePath}
741 onEnvModeChange={onEnvModeChange}
742 previousWorktreeLabel={previousWorktreeLabel}
743 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
744 onUsePreviousWorktree={onUsePreviousWorktree}
745 />
746 </div>
747 ) : null}
748 {showGitControls || showEnvironmentIndicator ? (
749 <div
750 className={cn(
751 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
752 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
753 composerControlsHostRef ? "shrink" : "flex-1",
754 )}
755 >
756 {showEnvironmentIndicator && availableEnvironments && (
757 <>
758 <BranchToolbarEnvironmentSelector
759 autoEnvironmentLabel={autoEnvironmentLabel}
760 onAutoEnvironment={onAutoEnvironment}
761 envLocked={envLocked}
762 environmentId={environmentId}
763 availableEnvironments={availableEnvironments}
764 {...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
765 />
766 {showGitControls ? (
767 <Separator
768 orientation="vertical"
769 className="mx-0.5 h-3.5!"
770 data-composer-context-control
771 />
772 ) : null}
773 </>
774 )}
775 {showGitControls ? (
776 <BranchToolbarEnvModeSelector
777 forceNewWorktree={forceNewWorktree}
778 envLocked={envModeLocked}
779 effectiveEnvMode={effectiveEnvMode}
780 activeWorktreePath={activeWorktreePath}
781 onEnvModeChange={onEnvModeChange}
782 previousWorktreeLabel={previousWorktreeLabel}
783 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
784 onUsePreviousWorktree={onUsePreviousWorktree}
785 />
786 ) : null}
787 </div>
788 ) : null}
789​
790 {composerControlsHostRef ? (
791 <div
792 ref={composerControlsHostRef}
793 data-composer-context-control
794 data-chat-resting-composer-controls-host="true"
795 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
796 />
797 ) : null}
798​
799 {showGitControls ? (
800 <BranchToolbarBranchSelector
801 forceNewWorktree={forceNewWorktree}
802 ref={branchSelectorRef}
803 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
804 environmentId={environmentId}
805 threadId={threadId}
806 {...(draftId ? { draftId } : {})}
807 envLocked={envLocked}
808 effectiveEnvModeOverride={effectiveEnvMode}
809 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
810 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
811 startFromOrigin={startFromOrigin}
812 onStartFromOriginChange={onStartFromOriginChange}
813 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
814 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
815 />
816 ) : null}
817 </ComposerSurface.ContextStrip>
818 );
819});