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

BranchToolbar.tsx

862 lines32.0 KB

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