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