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

BranchToolbar.tsx

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