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

BranchToolbar.tsx

899 lines34.0 KB

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