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";
72
73export interface BranchToolbarHandle {
74 openBranchPicker: () => void;
75 usePreviousWorktree: () => void;
76}
77
78interface BranchToolbarProps {
79 layout?: "composer" | "panel";
80 panelSection?: "all" | "workspace" | "branch";
81 forceNewWorktree?: boolean;
82 ref?: Ref<BranchToolbarHandle>;
83 environmentId: EnvironmentId;
84 threadId: ThreadId;
85 showGitControls: boolean;
86 draftId?: DraftId;
87 onEnvModeChange: (mode: EnvMode) => void;
88 /** The thread's env mode as ChatView resolves it. */
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 * The width a label takes when shown, clipped parts included.
410 *
411 * Text keeps its full width when its box clips it, so each text run measures
412 * whole. A label can hold more than one run (MiddleTruncate splits a branch
413 * into a head and a tail), so the runs are added. Reading one element's
414 * scrollWidth drops the tail when the label is hidden or squeezed, and the
415 * strip then flips between labels and icons on every measure.
416 *
417 * A shown label never grows past its motion span's max width, so longer text
418 * reserves only that much.
419 */
420function labelTextWidth(label: HTMLElement, range: Range): number {
421 const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
422 let width = 0;
423 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
424 range.selectNodeContents(node);
425 width += range.getBoundingClientRect().width;
426 }
427 const motion = label.querySelector<HTMLElement>("[data-composer-label-motion]");
428 const maxWidth = motion ? Number.parseFloat(getComputedStyle(motion).maxWidth) : Number.NaN;
429 return Number.isFinite(maxWidth) ? Math.min(width, maxWidth) : width;
430}
431
432/**
433 * Collapse the strip's labels to icons only when the text no longer fits.
434 *
435 * Hidden labels stay measurable because their inner text keeps its natural
436 * width while the outer layout box collapses. This lets every pass recompute
437 * the expanded width without remembered values that could go stale or latch
438 * the strip compact. A small hysteresis keeps the boundary from flapping.
439 */
440function useLabelsOverflow(element: HTMLDivElement | null): boolean {
441 const [overflows, setOverflows] = useState(false);
442 const pendingLabelRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
443 const labelAnimationsRef = useRef(new Map<HTMLElement, Animation>());
444 // A render-synced mirror instead of useEffectEvent: the compiler memoizes
445 // the event callback, which left observers reading the first render's null
446 // element forever.
447 const stateRef = useRef({ element, overflows });
448 stateRef.current = { element, overflows };
449
450 const measure = useCallback(() => {
451 const { element: current, overflows: compact } = stateRef.current;
452 if (!current) return;
453 const available = current.clientWidth;
454 if (available === 0) return;
455 // flex-1 stretches the groups to fill the strip, so their own boxes always
456 // measure "full". Sum the laid-out content instead, skipping hidden form
457 // artifacts and other out-of-flow nodes.
458 const contentWidth = (parent: Element): number => {
459 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
460 let width = 0;
461 let counted = 0;
462 for (const child of parent.children) {
463 if (!(child instanceof HTMLElement)) continue;
464 if (child.offsetWidth === 0) continue;
465 const style = getComputedStyle(child);
466 const position = style.position;
467 if (position === "absolute" || position === "fixed") continue;
468 width +=
469 child.offsetWidth +
470 (Number.parseFloat(style.marginInlineStart) || 0) +
471 (Number.parseFloat(style.marginInlineEnd) || 0);
472 counted += 1;
473 }
474 return width + gap * Math.max(0, counted - 1);
475 };
476 const stripGap = Number.parseFloat(getComputedStyle(current).columnGap) || 0;
477 let needed = 0;
478 let groups = 0;
479 for (const child of current.children) {
480 if (!(child instanceof HTMLElement)) continue;
481 // The host itself flexes into all remaining room. Reserve the natural
482 // width of the controls inside it, blocks in overflow included, so Git
483 // labels compact before squeezing out the model picker. Reserving only
484 // the visible controls would let the labels expand into room the
485 // composer just freed, shrink the host, and hide the controls again.
486 const hostedControls = child.matches('[data-chat-resting-composer-controls-host="true"]')
487 ? child.querySelector<HTMLElement>('[data-chat-composer-resting-controls="true"]')
488 : null;
489 const hostedMeasurement = hostedControls
490 ? measureRestingComposerControls(hostedControls)
491 : null;
492 const width = hostedMeasurement
493 ? resolveRestingComposerControlsNaturalWidth(hostedMeasurement)
494 : contentWidth(hostedControls ?? child);
495 if (width <= 1) continue;
496 groups += 1;
497 needed += width;
498 }
499 needed += stripGap * Math.max(0, groups - 1);
500 const range = document.createRange();
501 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
502 // Subtract the visible width even during an animation. The content
503 // sum already includes it; only the hidden text needs reserving.
504 needed += Math.max(0, labelTextWidth(label, range) - label.getBoundingClientRect().width);
505 }
506 const nextOverflows = resolveContextStripLabelsCompact({
507 compact,
508 neededWidth: needed,
509 availableWidth: available,
510 });
511 if (nextOverflows !== compact) {
512 pendingLabelRectsRef.current = new Map(
513 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
514 (label) => [label, label.getBoundingClientRect()],
515 ),
516 );
517 }
518 setOverflows(nextOverflows);
519 }, []);
520
521 useLayoutEffect(() => {
522 const previousRects = pendingLabelRectsRef.current;
523 if (!previousRects) return;
524 pendingLabelRectsRef.current = null;
525
526 for (const animation of labelAnimationsRef.current.values()) {
527 animation.cancel();
528 }
529 labelAnimationsRef.current.clear();
530
531 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
532
533 for (const [label, previousRect] of previousRects) {
534 if (!label.isConnected) continue;
535 const nextWidth = label.getBoundingClientRect().width;
536 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
537
538 // Animate the space occupied by each label so flex layout keeps the
539 // trailing controls anchored. Translating the whole group after its
540 // width snaps sends expanded text beyond the strip's right edge.
541 const animation = label.animate(
542 [
543 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
544 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
545 ],
546 {
547 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
548 easing: COMPOSER_CONTEXT_MOTION_EASING,
549 fill: "backwards",
550 },
551 );
552 labelAnimationsRef.current.set(label, animation);
553 animation.addEventListener(
554 "finish",
555 () => {
556 if (labelAnimationsRef.current.get(label) === animation) {
557 labelAnimationsRef.current.delete(label);
558 }
559 },
560 { once: true },
561 );
562 }
563 }, [overflows]);
564
565 useEffect(
566 () => () => {
567 for (const animation of labelAnimationsRef.current.values()) {
568 animation.cancel();
569 }
570 },
571 [],
572 );
573
574 // Label widths can change without the strip box moving (font family or
575 // size preferences), so re-measure on every render as well as on resize
576 // and font loads.
577 useLayoutEffect(() => {
578 measure();
579 });
580
581 useEffect(() => {
582 if (!element) return;
583 const observer = new ResizeObserver(measure);
584 observer.observe(element);
585 document.fonts.addEventListener("loadingdone", measure);
586 return () => {
587 observer.disconnect();
588 document.fonts.removeEventListener("loadingdone", measure);
589 };
590 }, [element, measure]);
591
592 return overflows;
593}
594
595export const BranchToolbar = memo(function BranchToolbar({
596 layout = "composer",
597 panelSection = "all",
598 forceNewWorktree = false,
599 ref,
600 environmentId,
601 threadId,
602 showGitControls,
603 draftId,
604 onEnvModeChange,
605 envMode,
606 activeThreadBranchOverride,
607 onActiveThreadBranchOverrideChange,
608 startFromOrigin,
609 onStartFromOriginChange,
610 autoEnvironmentLabel,
611 onAutoEnvironment,
612 envLocked,
613 onCheckoutPullRequestRequest,
614 onComposerFocusRequest,
615 availableEnvironments,
616 onEnvironmentChange,
617 composerControlsHostRef,
618 contextStripVisible = true,
619}: BranchToolbarProps) {
620 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
621 const threadRef = useMemo(
622 () => scopeThreadRef(environmentId, threadId),
623 [environmentId, threadId],
624 );
625 const draftThread = useComposerDraftStore((store) =>
626 draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
627 );
628 const serverThread = useThreadShell(threadRef);
629 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
630 const activeProjectRef = serverThread
631 ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)
632 : draftThread
633 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
634 : null;
635 const activeProject = useProject(activeProjectRef);
636 const hasActiveThread = serverThread !== null || draftThread !== null;
637 const activeWorktreePath = forceNewWorktree
638 ? null
639 : (serverThread?.worktreePath ?? draftThread?.worktreePath ?? null);
640 const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode;
641 const envModeLocked = envLocked || (serverThread !== null && activeWorktreePath !== null);
642
643 // "Previous worktree" hops a draft into the most recently active worktree
644 // of this project — the "keep going where I just was" follow-up flow. Only
645 // drafts can hop; started server threads have their workspace pinned.
646 const canUsePreviousWorktree =
647 draftThread !== null && serverThread === null && !envModeLocked && !forceNewWorktree;
648 const projectRefsForWorktreeLookup = useMemo(
649 () => (canUsePreviousWorktree && activeProjectRef ? [activeProjectRef] : []),
650 [canUsePreviousWorktree, activeProjectRef],
651 );
652 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
653 const previousWorktreeSeed = useMemo(
654 () =>
655 canUsePreviousWorktree
656 ? resolvePreviousWorktreeSeed({
657 threads: projectThreads,
658 currentWorktreePath: activeWorktreePath,
659 })
660 : null,
661 [activeWorktreePath, canUsePreviousWorktree, projectThreads],
662 );
663 const previousWorktreeLabel = previousWorktreeSeed
664 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
665 : null;
666 const onUsePreviousWorktree = useCallback(() => {
667 if (!previousWorktreeSeed || !activeProjectRef) return;
668 // Same shape the branch selector writes when picking a branch that
669 // already lives in a worktree: point the draft at the existing tree.
670 setDraftThreadContext(draftId ?? threadRef, {
671 branch: previousWorktreeSeed.branch,
672 worktreePath: previousWorktreeSeed.worktreePath,
673 envMode: "worktree",
674 projectRef: activeProjectRef,
675 });
676 }, [activeProjectRef, draftId, previousWorktreeSeed, setDraftThreadContext, threadRef]);
677
678 useImperativeHandle(
679 ref,
680 () => ({
681 openBranchPicker: () => branchSelectorRef.current?.open(),
682 usePreviousWorktree: () => {
683 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
684 onUsePreviousWorktree();
685 onComposerFocusRequest?.();
686 },
687 }),
688 [
689 canUsePreviousWorktree,
690 onComposerFocusRequest,
691 onUsePreviousWorktree,
692 previousWorktreeSeed,
693 showGitControls,
694 ],
695 );
696
697 const showEnvironmentPicker = Boolean(
698 availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
699 );
700 const activeEnvironmentOption =
701 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
702 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
703 activeEnvironment: activeEnvironmentOption,
704 canPickEnvironment: showEnvironmentPicker,
705 });
706 const [stripElement, setStripElement] = useState<HTMLDivElement | null>(null);
707 const labelsOverflow = useLabelsOverflow(stripElement);
708
709 if (!hasActiveThread || !activeProject) return null;
710
711 if (layout === "panel") {
712 return (
713 <div className="flex w-full flex-col" data-thread-panel-run-context>
714 {panelSection !== "branch" ? (
715 <RunContextSelector
716 displayMode="panel"
717 workspaceRoot={activeProject.workspaceRoot}
718 forceNewWorktree={forceNewWorktree}
719 autoEnvironmentLabel={autoEnvironmentLabel}
720 onAutoEnvironment={onAutoEnvironment}
721 envLocked={envLocked}
722 envModeLocked={envModeLocked}
723 environmentId={environmentId}
724 availableEnvironments={availableEnvironments}
725 showEnvironmentPicker={showEnvironmentPicker}
726 showEnvironmentIndicator={activeEnvironmentOption !== null}
727 onEnvironmentChange={onEnvironmentChange}
728 effectiveEnvMode={effectiveEnvMode}
729 activeWorktreePath={activeWorktreePath}
730 onEnvModeChange={onEnvModeChange}
731 previousWorktreeLabel={previousWorktreeLabel}
732 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
733 onUsePreviousWorktree={onUsePreviousWorktree}
734 />
735 ) : null}
736 {panelSection !== "workspace" ? (
737 <BranchToolbarBranchSelector
738 displayMode="panel"
739 className="w-full"
740 environmentId={environmentId}
741 threadId={threadId}
742 {...(draftId ? { draftId } : {})}
743 envLocked={envLocked}
744 effectiveEnvModeOverride={effectiveEnvMode}
745 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
746 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
747 startFromOrigin={startFromOrigin}
748 onStartFromOriginChange={onStartFromOriginChange}
749 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
750 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
751 />
752 ) : null}
753 </div>
754 );
755 }
756
757 return (
758 <ComposerSurface.ContextStrip
759 ref={setStripElement}
760 data-compact={labelsOverflow ? "" : undefined}
761 className={cn(
762 "gap-1 text-xs font-normal text-muted-foreground/70",
763 // A non-Git strip with no visible composer controls should occupy no
764 // space, but its host must retain a prospective width so controls can
765 // become visible again when the chat view grows.
766 !contextStripVisible && "pointer-events-none invisible absolute inset-x-0 top-full",
767 )}
768 >
769 {showGitControls ? (
770 <div className="contents @3xl/composer-surface:hidden">
771 <RunContextSelector
772 forceNewWorktree={forceNewWorktree}
773 autoEnvironmentLabel={autoEnvironmentLabel}
774 onAutoEnvironment={onAutoEnvironment}
775 envLocked={envLocked}
776 envModeLocked={envModeLocked}
777 environmentId={environmentId}
778 availableEnvironments={availableEnvironments}
779 showEnvironmentPicker={showEnvironmentPicker}
780 showEnvironmentIndicator={showEnvironmentIndicator}
781 onEnvironmentChange={onEnvironmentChange}
782 effectiveEnvMode={effectiveEnvMode}
783 activeWorktreePath={activeWorktreePath}
784 onEnvModeChange={onEnvModeChange}
785 previousWorktreeLabel={previousWorktreeLabel}
786 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
787 onUsePreviousWorktree={onUsePreviousWorktree}
788 />
789 </div>
790 ) : null}
791 {showGitControls || showEnvironmentIndicator ? (
792 <div
793 className={cn(
794 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
795 showGitControls ? "hidden @3xl/composer-surface:flex" : "flex",
796 composerControlsHostRef ? "shrink" : "flex-1",
797 )}
798 >
799 {showEnvironmentIndicator && availableEnvironments && (
800 <>
801 <BranchToolbarEnvironmentSelector
802 autoEnvironmentLabel={autoEnvironmentLabel}
803 onAutoEnvironment={onAutoEnvironment}
804 envLocked={envLocked}
805 environmentId={environmentId}
806 availableEnvironments={availableEnvironments}
807 {...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
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 // The host takes whatever the workspace and branch controls leave
835 // over, in both strip layouts, so a collapsed composer can show its
836 // model and mode controls wherever they fit.
837 <div
838 ref={composerControlsHostRef}
839 data-composer-context-control
840 data-chat-resting-composer-controls-host="true"
841 className="flex min-w-0 flex-1 items-center justify-start overflow-x-clip overflow-y-visible"
842 />
843 ) : null}
844
845 {showGitControls ? (
846 <BranchToolbarBranchSelector
847 forceNewWorktree={forceNewWorktree}
848 ref={branchSelectorRef}
849 className="min-w-0 flex-initial justify-end @3xl/composer-surface:ml-auto"
850 environmentId={environmentId}
851 threadId={threadId}
852 {...(draftId ? { draftId } : {})}
853 envLocked={envLocked}
854 effectiveEnvModeOverride={effectiveEnvMode}
855 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
856 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
857 startFromOrigin={startFromOrigin}
858 onStartFromOriginChange={onStartFromOriginChange}
859 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
860 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
861 />
862 ) : null}
863 </ComposerSurface.ContextStrip>
864 );
865});