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

BranchToolbar.tsx

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