Open History to see the last commit
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 { FolderGit2Icon, FolderGitIcon, FolderIcon, PlusIcon, ScaleIcon } from "lucide-react";
9import {
10 type Ref,
11 type MouseEvent as ReactMouseEvent,
12 type ReactNode,
13 memo,
14 useImperativeHandle,
15 useRef,
16 useState,
17} from "react";
18import { flushSync } from "react-dom";
19
20import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
21import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
22import { useProject, useThreadShellsForProjectRefs } from "../state/entities";
23import {
24 ADD_TO_MACHINE_LABEL_CLASS,
25 type EnvMode,
26 type EnvironmentOption,
27 resolveContextStripLabelsCompact,
28 resolveCurrentWorkspaceLabel,
29 resolveEnvModeLabel,
30 resolveLockedWorkspaceLabel,
31 resolvePreviousWorktreeLabel,
32 resolvePreviousWorktreeSeed,
33 shouldShowEnvironmentIndicator,
34} from "./BranchToolbar.logic";
35import {
36 BranchToolbarBranchSelector,
37 type BranchToolbarBranchSelectorHandle,
38} from "./BranchToolbarBranchSelector";
39import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
40import { openAddProjectToMachine } from "./AddProjectToMachineDialog";
41import { type AddProjectTarget, useAddProjectTargets } from "../hooks/useAddProjectTargets";
42import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
43import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
44import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
45import {
46 THREAD_DETAILS_PANEL_ICON_CLASS,
47 THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
48} from "./chat/threadDetailsPanelStyles";
49import { ComposerControl } from "./chat/ComposerControl";
50import {
51 Menu,
52 MenuGroup,
53 MenuGroupLabel,
54 MenuItem,
55 MenuPopup,
56 MenuRadioGroup,
57 MenuRadioItem,
58 MenuSeparator,
59 MenuSub,
60 MenuSubPopup,
61 MenuSubTrigger,
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 { cn } from "~/lib/utils";
70import { observeResize } from "~/lib/observeResize";
71
72export interface BranchToolbarHandle {
73 openBranchPicker: () => void;
74 usePreviousWorktree: () => void;
75}
76
77interface BranchToolbarProps {
78 layout?: "composer" | "panel";
79 panelSection?: "all" | "workspace" | "branch";
80 forceNewWorktree?: boolean;
81 ref?: Ref<BranchToolbarHandle>;
82 environmentId: EnvironmentId;
83 threadId: ThreadId;
84 projectId: ProjectId;
85 worktreePath: string | null;
86 isServerThread: boolean;
87 showGitControls: boolean;
88 draftId?: DraftId;
89 onEnvModeChange: (mode: EnvMode) => void;
90 envMode: EnvMode;
91 activeThreadBranchOverride?: string | null;
92 onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
93 startFromOrigin: boolean;
94 onStartFromOriginChange: (startFromOrigin: boolean) => void;
95 autoEnvironmentLabel?: string | undefined;
96 onAutoEnvironment?: (() => void) | undefined;
97 envLocked: boolean;
98 onCheckoutPullRequestRequest?: (reference: string) => void;
99 onComposerFocusRequest?: () => void;
100 /** Shown at the end of the composer strip, such as the new thread's permissions. */
101 trailing?: ReactNode;
102 availableEnvironments?: readonly EnvironmentOption[];
103 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
104}
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 const clipboardPath = formatFilePathForClipboard(workspacePath);
119 void writeTextToClipboard(clipboardPath, "workspace path").then(
120 undefined,
121 (error: unknown) => {
122 toastManager.add(
123 stackedThreadToast({
124 type: "error",
125 title: "Failed to copy path",
126 description: error instanceof Error ? error.message : "An error occurred.",
127 }),
128 );
129 },
130 );
131 });
132}
133
134interface RunContextSelectorProps {
135 displayMode?: "toolbar" | "panel";
136 workspaceRoot?: string;
137 forceNewWorktree: boolean;
138 autoEnvironmentLabel?: string | undefined;
139 onAutoEnvironment?: (() => void) | undefined;
140 envLocked: boolean;
141 envModeLocked: boolean;
142 environmentId: EnvironmentId;
143 availableEnvironments: readonly EnvironmentOption[] | undefined;
144 showEnvironmentPicker: boolean;
145 showEnvironmentIndicator: boolean;
146 onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
147 effectiveEnvMode: EnvMode;
148 activeWorktreePath: string | null;
149 onEnvModeChange: (mode: EnvMode) => void;
150 previousWorktreeLabel: string | null;
151 previousWorktreeBranch: string | null;
152 onUsePreviousWorktree: () => void;
153 addTargets: readonly AddProjectTarget[];
154 onAddToMachine: (environmentId: EnvironmentId) => void;
155}
156
157const RunContextSelector = memo(function RunContextSelector({
158 displayMode = "toolbar",
159 workspaceRoot,
160 forceNewWorktree,
161 autoEnvironmentLabel,
162 onAutoEnvironment,
163 envLocked,
164 envModeLocked,
165 environmentId,
166 availableEnvironments,
167 showEnvironmentPicker,
168 showEnvironmentIndicator,
169 onEnvironmentChange,
170 effectiveEnvMode,
171 activeWorktreePath,
172 onEnvModeChange,
173 previousWorktreeLabel,
174 previousWorktreeBranch,
175 onUsePreviousWorktree,
176 addTargets,
177 onAddToMachine,
178}: RunContextSelectorProps) {
179 const composerFloatingLayerProps = useComposerMenuProps();
180 const activeEnvironment =
181 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
182 const WorkspaceIcon =
183 effectiveEnvMode === "worktree"
184 ? FolderGit2Icon
185 : activeWorktreePath
186 ? FolderGitIcon
187 : FolderIcon;
188 const workspaceLabel = forceNewWorktree
189 ? resolveEnvModeLabel("worktree")
190 : envModeLocked
191 ? resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode)
192 : effectiveEnvMode === "worktree"
193 ? resolveEnvModeLabel("worktree")
194 : resolveCurrentWorkspaceLabel(activeWorktreePath);
195 const isPanel = displayMode === "panel";
196 const isLocked = envLocked || (envModeLocked && (!isPanel || !showEnvironmentPicker));
197 const workspacePath =
198 forceNewWorktree || (effectiveEnvMode === "worktree" && !activeWorktreePath)
199 ? null
200 : (activeWorktreePath ?? workspaceRoot);
201 const handleContextMenu = (event: ReactMouseEvent) => {
202 if (isPanel && workspacePath) {
203 showWorkspaceContextMenu(event, workspacePath);
204 }
205 };
206 const workspaceIcon = (
207 <Tooltip>
208 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
209 <WorkspaceIcon className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0"} />
210 </TooltipTrigger>
211 <TooltipPopup>
212 {isPanel
213 ? forceNewWorktree
214 ? "Each model starts in its own worktree."
215 : (workspacePath ?? workspaceLabel)
216 : workspaceLabel}
217 </TooltipPopup>
218 </Tooltip>
219 );
220 const environmentIcon = (
221 <Tooltip>
222 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
223 {autoEnvironmentLabel ? (
224 <ScaleIcon
225 className={isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3 shrink-0"}
226 aria-hidden="true"
227 />
228 ) : (
229 <EnvironmentMachineIcon
230 kind={activeEnvironment?.machine ?? "server"}
231 // Wide machine glyphs need a little more box to match the square row icons.
232 className={
233 isPanel ? cn(THREAD_DETAILS_PANEL_ICON_CLASS, "-mx-px size-4.5") : "size-3 shrink-0"
234 }
235 />
236 )}
237 </TooltipTrigger>
238 <TooltipPopup>{autoEnvironmentLabel ?? activeEnvironment?.label ?? "Run on"}</TooltipPopup>
239 </Tooltip>
240 );
241 const icon = showEnvironmentIndicator ? environmentIcon : workspaceIcon;
242 const triggerContent = (
243 <>
244 {icon}
245 <ComposerContextLabel displayMode={displayMode}>
246 {autoEnvironmentLabel ??
247 (showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel)}
248 </ComposerContextLabel>
249 {/* Trailing in the panel, so every row label starts on the same edge. */}
250 {isPanel && showEnvironmentIndicator ? workspaceIcon : null}
251 </>
252 );
253
254 if (isLocked) {
255 return (
256 <span
257 className={cn(
258 "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-foreground/70 text-sm sm:h-6 sm:text-xs dark:text-muted-foreground",
259 isPanel && "max-w-full",
260 isPanel && THREAD_DETAILS_PANEL_LOCKED_ROW_CLASS,
261 )}
262 onContextMenu={handleContextMenu}
263 aria-label={
264 isPanel
265 ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`
266 : undefined
267 }
268 data-composer-context-control
269 >
270 {triggerContent}
271 </span>
272 );
273 }
274
275 return (
276 <Menu>
277 <MenuTrigger
278 render={isPanel ? <ThreadDetailsControl part="select" /> : <ComposerControl size="xs" />}
279 className={isPanel ? undefined : "min-w-0 max-w-[48%] flex-initial justify-start"}
280 onContextMenu={handleContextMenu}
281 onMouseDownCapture={
282 isPanel
283 ? (event) => {
284 if (event.button !== 0 || event.ctrlKey) event.stopPropagation();
285 }
286 : undefined
287 }
288 aria-label={
289 isPanel
290 ? `Run context: ${[autoEnvironmentLabel ?? activeEnvironment?.label, workspaceLabel].filter(Boolean).join(", ")}`
291 : undefined
292 }
293 data-composer-context-control
294 data-composer-shortcut={[
295 showEnvironmentPicker && !envLocked ? "composer.host" : "",
296 !envModeLocked ? "composer.workspace" : "",
297 ].join(" ")}
298 >
299 {triggerContent}
300 </MenuTrigger>
301 <MenuPopup
302 align="start"
303 side={isPanel ? "bottom" : "top"}
304 className={
305 isPanel
306 ? "w-(--anchor-width)"
307 : previousWorktreeLabel
308 ? "w-[min(21rem,calc(100vw-2rem))]"
309 : undefined
310 }
311 {...(!isPanel ? composerFloatingLayerProps : {})}
312 >
313 {availableEnvironments &&
314 ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) ? (
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={
347 envLocked || (!onEnvironmentChange && env.environmentId !== environmentId)
348 }
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 {addTargets.length > 0 ? (
360 <MenuSub>
361 <MenuSubTrigger>
362 <span className={ADD_TO_MACHINE_LABEL_CLASS}>
363 <PlusIcon className="size-3" />
364 <span className="min-w-0 truncate">Add to another machine</span>
365 </span>
366 </MenuSubTrigger>
367 <MenuSubPopup {...(!isPanel ? composerFloatingLayerProps : {})}>
368 {addTargets.map((target) => (
369 <MenuItem
370 key={target.environmentId}
371 onClick={() => onAddToMachine(target.environmentId)}
372 >
373 <span className="flex min-w-0 items-center gap-1.5">
374 <EnvironmentMachineIcon kind={target.machine} className="size-3" />
375 <span className="min-w-0 truncate">{target.label}</span>
376 </span>
377 </MenuItem>
378 ))}
379 </MenuSubPopup>
380 </MenuSub>
381 ) : null}
382 </MenuGroup>
383 <MenuSeparator />
384 </>
385 ) : null}
386 <MenuGroup>
387 <MenuGroupLabel>Workspace</MenuGroupLabel>
388 <MenuRadioGroup
389 value={effectiveEnvMode}
390 onValueChange={(value) => {
391 if (value === "previous-worktree") {
392 onUsePreviousWorktree();
393 return;
394 }
395 onEnvModeChange(value as EnvMode);
396 }}
397 >
398 <MenuRadioItem disabled={envModeLocked || forceNewWorktree} value="local" closeOnClick>
399 <span className="flex min-w-0 items-center gap-1.5">
400 {activeWorktreePath ? (
401 <FolderGitIcon className="size-3" />
402 ) : (
403 <FolderIcon className="size-3" />
404 )}
405 <MiddleTruncate value={resolveCurrentWorkspaceLabel(activeWorktreePath)} />
406 </span>
407 </MenuRadioItem>
408 <MenuRadioItem disabled={envModeLocked} value="worktree" closeOnClick>
409 <span className="flex min-w-0 items-center gap-1.5">
410 <FolderGit2Icon className="size-3" />
411 <span className="min-w-0 truncate">{resolveEnvModeLabel("worktree")}</span>
412 </span>
413 </MenuRadioItem>
414 {previousWorktreeLabel ? (
415 <MenuRadioItem disabled={envModeLocked} value="previous-worktree" closeOnClick>
416 <PreviousWorktreeItemContent branch={previousWorktreeBranch} />
417 </MenuRadioItem>
418 ) : null}
419 </MenuRadioGroup>
420 </MenuGroup>
421 </MenuPopup>
422 </Menu>
423 );
424});
425
426const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
427const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
428const COMPOSER_CONTEXT_LABEL_SELECTOR = "[data-composer-label]";
429
430/** A hidden or squeezed label's scrollWidth loses its tail, causing label/icon flapping. */
431function labelTextWidth(label: HTMLElement, range: Range): number {
432 const walker = document.createTreeWalker(label, NodeFilter.SHOW_TEXT);
433 let width = 0;
434 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
435 range.selectNodeContents(node);
436 width += range.getBoundingClientRect().width;
437 }
438 const motion = label.querySelector<HTMLElement>("[data-composer-label-motion]");
439 const maxWidth = motion ? Number.parseFloat(getComputedStyle(motion).maxWidth) : Number.NaN;
440 return Number.isFinite(maxWidth) ? Math.min(width, maxWidth) : width;
441}
442
443function animateLabelWidths(
444 previousRects: ReadonlyMap<HTMLElement, DOMRect>,
445 animations: Map<HTMLElement, Animation>,
446) {
447 for (const animation of animations.values()) animation.cancel();
448 animations.clear();
449 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
450
451 for (const [label, previousRect] of previousRects) {
452 if (!label.isConnected) continue;
453 const nextWidth = label.getBoundingClientRect().width;
454 if (Math.abs(previousRect.width - nextWidth) < 0.5) continue;
455
456 const animation = label.animate(
457 [
458 { width: `${previousRect.width}px`, maxWidth: `${previousRect.width}px` },
459 { width: `${nextWidth}px`, maxWidth: `${nextWidth}px` },
460 ],
461 {
462 duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
463 easing: COMPOSER_CONTEXT_MOTION_EASING,
464 fill: "backwards",
465 },
466 );
467 animations.set(label, animation);
468 animation.addEventListener(
469 "finish",
470 () => {
471 if (animations.get(label) === animation) animations.delete(label);
472 },
473 { once: true },
474 );
475 }
476}
477
478/**
479 * Whether the strip's labels must collapse to icons. The strip is measured when
480 * it, a control group or a hosted control resizes, when its text or children
481 * change, and when fonts load, which covers everything the widths depend on.
482 */
483function useLabelsOverflow(): readonly [
484 attach: (element: HTMLDivElement | null) => (() => void) | undefined,
485 overflows: boolean,
486] {
487 const [overflows, setOverflows] = useState(false);
488
489 const attach = (current: HTMLDivElement | null) => {
490 if (!current) return;
491 const labelAnimations = new Map<HTMLElement, Animation>();
492
493 const measure = () => {
494 // The committed attribute, not render state, so a stale closure cannot misread it.
495 const compact = current.hasAttribute("data-compact");
496 const stripWidth = current.clientWidth;
497 if (stripWidth === 0) return;
498 const stripStyle = getComputedStyle(current);
499 const available =
500 stripWidth -
501 (Number.parseFloat(stripStyle.paddingInlineStart) || 0) -
502 (Number.parseFloat(stripStyle.paddingInlineEnd) || 0);
503 const contentWidth = (parent: Element): number => {
504 const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
505 let width = 0;
506 let counted = 0;
507 for (const child of parent.children) {
508 if (!(child instanceof HTMLElement)) continue;
509 if (child.offsetWidth === 0) continue;
510 const style = getComputedStyle(child);
511 const position = style.position;
512 if (position === "absolute" || position === "fixed") continue;
513 width +=
514 child.offsetWidth +
515 (Number.parseFloat(style.marginInlineStart) || 0) +
516 (Number.parseFloat(style.marginInlineEnd) || 0);
517 counted += 1;
518 }
519 return width + gap * Math.max(0, counted - 1);
520 };
521 const stripGap = Number.parseFloat(stripStyle.columnGap) || 0;
522 let needed = 0;
523 let groups = 0;
524 for (const child of current.children) {
525 if (!(child instanceof HTMLElement)) continue;
526 const width = contentWidth(child);
527 if (width <= 1) continue;
528 groups += 1;
529 needed += width;
530 }
531 needed += stripGap * Math.max(0, groups - 1);
532 const range = document.createRange();
533 for (const label of current.querySelectorAll<HTMLElement>("[data-composer-label]")) {
534 needed += Math.max(0, labelTextWidth(label, range) - label.getBoundingClientRect().width);
535 }
536 const nextOverflows = resolveContextStripLabelsCompact({
537 compact,
538 neededWidth: needed,
539 availableWidth: available,
540 });
541 if (nextOverflows === compact) return;
542 const previousRects = new Map(
543 Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_LABEL_SELECTOR)).map(
544 (label) => [label, label.getBoundingClientRect()] as const,
545 ),
546 );
547 flushSync(() => setOverflows(nextOverflows));
548 animateLabelWidths(previousRects, labelAnimations);
549 };
550
551 let stopResize = () => {};
552 const observeSizes = () => {
553 stopResize();
554 stopResize = observeResize(
555 [
556 current,
557 ...Array.from(current.children),
558 ...Array.from(current.querySelectorAll(COMPOSER_CONTEXT_LABEL_SELECTOR)),
559 ],
560 measure,
561 );
562 };
563 observeSizes();
564 // Text and control changes alter natural widths without resizing a hidden
565 // or squeezed label, so they re-measure too. Only added or removed elements
566 // can change the observed set; re-subscribing delivers a measure itself.
567 const mutations = new MutationObserver((records) => {
568 const elementsChanged = records.some((record) =>
569 [...record.addedNodes, ...record.removedNodes].some((node) => node instanceof Element),
570 );
571 if (elementsChanged) observeSizes();
572 else measure();
573 });
574 mutations.observe(current, { childList: true, characterData: true, subtree: true });
575 document.fonts.addEventListener("loadingdone", measure);
576 return () => {
577 stopResize();
578 mutations.disconnect();
579 document.fonts.removeEventListener("loadingdone", measure);
580 for (const animation of labelAnimations.values()) animation.cancel();
581 };
582 };
583
584 return [attach, overflows] as const;
585}
586
587export const BranchToolbar = memo(function BranchToolbar({
588 layout = "composer",
589 panelSection = "all",
590 forceNewWorktree = false,
591 ref,
592 environmentId,
593 threadId,
594 projectId,
595 worktreePath,
596 isServerThread,
597 showGitControls,
598 draftId,
599 onEnvModeChange,
600 envMode,
601 activeThreadBranchOverride,
602 onActiveThreadBranchOverrideChange,
603 startFromOrigin,
604 onStartFromOriginChange,
605 autoEnvironmentLabel,
606 onAutoEnvironment,
607 envLocked,
608 onCheckoutPullRequestRequest,
609 onComposerFocusRequest,
610 availableEnvironments,
611 onEnvironmentChange,
612 trailing,
613}: BranchToolbarProps) {
614 const branchSelectorRef = useRef<BranchToolbarBranchSelectorHandle>(null);
615 const threadRef = scopeThreadRef(environmentId, threadId);
616 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
617 // The composer retains resolved thread details while bootstrap cleanup can remove its shell.
618 const activeProjectRef = scopeProjectRef(environmentId, projectId);
619 const activeProject = useProject(activeProjectRef);
620 const activeWorktreePath = forceNewWorktree ? null : worktreePath;
621 const effectiveEnvMode = forceNewWorktree ? "worktree" : envMode;
622 const envModeLocked = envLocked || (isServerThread && activeWorktreePath !== null);
623
624 const canUsePreviousWorktree = !isServerThread && !envModeLocked && !forceNewWorktree;
625 const projectRefsForWorktreeLookup = canUsePreviousWorktree ? [activeProjectRef] : [];
626 const projectThreads = useThreadShellsForProjectRefs(projectRefsForWorktreeLookup);
627 const previousWorktreeSeed = canUsePreviousWorktree
628 ? resolvePreviousWorktreeSeed({
629 threads: projectThreads,
630 currentWorktreePath: activeWorktreePath,
631 })
632 : null;
633 const previousWorktreeLabel = previousWorktreeSeed
634 ? resolvePreviousWorktreeLabel(previousWorktreeSeed)
635 : null;
636 const onUsePreviousWorktree = () => {
637 if (!previousWorktreeSeed) return;
638 setDraftThreadContext(draftId ?? threadRef, {
639 branch: previousWorktreeSeed.branch,
640 worktreePath: previousWorktreeSeed.worktreePath,
641 envMode: "worktree",
642 projectRef: activeProjectRef,
643 });
644 };
645
646 useImperativeHandle(
647 ref,
648 () => ({
649 openBranchPicker: () => branchSelectorRef.current?.open(),
650 usePreviousWorktree: () => {
651 if (!showGitControls || !canUsePreviousWorktree || !previousWorktreeSeed) return;
652 onUsePreviousWorktree();
653 onComposerFocusRequest?.();
654 },
655 }),
656 [
657 canUsePreviousWorktree,
658 onComposerFocusRequest,
659 onUsePreviousWorktree,
660 previousWorktreeSeed,
661 showGitControls,
662 ],
663 );
664
665 const addTargets = useAddProjectTargets(activeProject, availableEnvironments);
666 const onAddToMachine = (targetEnvironmentId: EnvironmentId | null) =>
667 openAddProjectToMachine({ projectRef: activeProjectRef, targetEnvironmentId });
668 // A project on one machine still gets the picker when it can be added to another.
669 const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1 || addTargets.length > 0;
670 const showEnvironmentPicker = hasMultipleEnvironments && onEnvironmentChange !== undefined;
671 const activeEnvironmentOption =
672 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
673 // Started threads get no handler but still show which machine they run on,
674 // matching the strip visibility ChatView computes from the same inputs.
675 const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
676 activeEnvironment: activeEnvironmentOption,
677 canPickEnvironment: hasMultipleEnvironments,
678 });
679 const [attachStrip, labelsOverflow] = useLabelsOverflow();
680
681 if (!activeProject) return null;
682
683 if (layout === "panel") {
684 return (
685 <div className="flex w-full flex-col" data-thread-panel-run-context>
686 {panelSection !== "branch" ? (
687 <RunContextSelector
688 displayMode="panel"
689 workspaceRoot={activeProject.workspaceRoot}
690 forceNewWorktree={forceNewWorktree}
691 autoEnvironmentLabel={autoEnvironmentLabel}
692 onAutoEnvironment={onAutoEnvironment}
693 envLocked={envLocked}
694 envModeLocked={envModeLocked}
695 environmentId={environmentId}
696 availableEnvironments={availableEnvironments}
697 showEnvironmentPicker={showEnvironmentPicker}
698 showEnvironmentIndicator={activeEnvironmentOption !== null}
699 onEnvironmentChange={onEnvironmentChange}
700 effectiveEnvMode={effectiveEnvMode}
701 activeWorktreePath={activeWorktreePath}
702 onEnvModeChange={onEnvModeChange}
703 previousWorktreeLabel={previousWorktreeLabel}
704 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
705 onUsePreviousWorktree={onUsePreviousWorktree}
706 addTargets={addTargets}
707 onAddToMachine={onAddToMachine}
708 />
709 ) : null}
710 {panelSection !== "workspace" ? (
711 <BranchToolbarBranchSelector
712 displayMode="panel"
713 className="w-full"
714 environmentId={environmentId}
715 threadId={threadId}
716 {...(draftId ? { draftId } : {})}
717 envLocked={envLocked}
718 effectiveEnvModeOverride={effectiveEnvMode}
719 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
720 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
721 startFromOrigin={startFromOrigin}
722 onStartFromOriginChange={onStartFromOriginChange}
723 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
724 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
725 />
726 ) : null}
727 </div>
728 );
729 }
730
731 return (
732 <ComposerSurface.ContextStrip
733 ref={attachStrip}
734 data-compact={labelsOverflow ? "" : undefined}
735 className={cn("gap-1 text-xs font-normal text-foreground/70 dark:text-muted-foreground")}
736 >
737 {showGitControls ? (
738 <div className="contents @xl/composer-surface:hidden">
739 <RunContextSelector
740 forceNewWorktree={forceNewWorktree}
741 autoEnvironmentLabel={autoEnvironmentLabel}
742 onAutoEnvironment={onAutoEnvironment}
743 envLocked={envLocked}
744 envModeLocked={envModeLocked}
745 environmentId={environmentId}
746 availableEnvironments={availableEnvironments}
747 showEnvironmentPicker={showEnvironmentPicker}
748 showEnvironmentIndicator={showEnvironmentIndicator}
749 onEnvironmentChange={onEnvironmentChange}
750 effectiveEnvMode={effectiveEnvMode}
751 activeWorktreePath={activeWorktreePath}
752 onEnvModeChange={onEnvModeChange}
753 previousWorktreeLabel={previousWorktreeLabel}
754 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
755 onUsePreviousWorktree={onUsePreviousWorktree}
756 addTargets={addTargets}
757 onAddToMachine={onAddToMachine}
758 />
759 </div>
760 ) : null}
761 {showGitControls || showEnvironmentIndicator ? (
762 <div
763 className={cn(
764 "min-h-7 min-w-10 items-center gap-1 sm:min-h-6",
765 showGitControls ? "hidden @xl/composer-surface:flex" : "flex",
766 "flex-1",
767 )}
768 >
769 {showEnvironmentIndicator && availableEnvironments && (
770 <>
771 <BranchToolbarEnvironmentSelector
772 autoEnvironmentLabel={autoEnvironmentLabel}
773 onAutoEnvironment={onAutoEnvironment}
774 envLocked={envLocked}
775 environmentId={environmentId}
776 availableEnvironments={availableEnvironments}
777 {...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
778 {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
779 />
780 {showGitControls ? (
781 <Separator
782 orientation="vertical"
783 className="mx-0.5 h-3.5!"
784 data-composer-context-control
785 />
786 ) : null}
787 </>
788 )}
789 {showGitControls ? (
790 <BranchToolbarEnvModeSelector
791 forceNewWorktree={forceNewWorktree}
792 envLocked={envModeLocked}
793 effectiveEnvMode={effectiveEnvMode}
794 activeWorktreePath={activeWorktreePath}
795 onEnvModeChange={onEnvModeChange}
796 previousWorktreeLabel={previousWorktreeLabel}
797 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
798 onUsePreviousWorktree={onUsePreviousWorktree}
799 />
800 ) : null}
801 </div>
802 ) : null}
803
804 {showGitControls ? (
805 <BranchToolbarBranchSelector
806 forceNewWorktree={forceNewWorktree}
807 ref={branchSelectorRef}
808 className="min-w-0 flex-initial justify-end @xl/composer-surface:ml-auto"
809 environmentId={environmentId}
810 threadId={threadId}
811 {...(draftId ? { draftId } : {})}
812 envLocked={envLocked}
813 effectiveEnvModeOverride={effectiveEnvMode}
814 {...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
815 {...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
816 startFromOrigin={startFromOrigin}
817 onStartFromOriginChange={onStartFromOriginChange}
818 {...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
819 {...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
820 />
821 ) : null}
822 {trailing}
823 </ComposerSurface.ContextStrip>
824 );
825});