The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { workspaceAreaProps } from "../lib/workspaceFocus"; |
| 3 | import { useAtomMount, useAtomValue } from "@effect/atom-react"; |
| 4 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 5 | import { m } from "../i18n/messages"; |
| 6 | import { |
| 7 | isAtomCommandInterrupted, |
| 8 | executeAtomQuery, |
| 9 | squashAtomCommandFailure, |
| 10 | } from "@t3tools/client-runtime/state/runtime"; |
| 11 | import { |
| 12 | INITIAL_TERMINAL_OUTPUT_CURSOR, |
| 13 | readTerminalOutputUpdate, |
| 14 | type TerminalOutputCursor, |
| 15 | type TerminalOutputUpdate, |
| 16 | type TerminalSessionState, |
| 17 | } from "@t3tools/client-runtime/state/terminal"; |
| 18 | import { |
| 19 | Plus, |
| 20 | Square, |
| 21 | SquareSplitHorizontal, |
| 22 | SquareSplitVertical, |
| 23 | TerminalSquare, |
| 24 | Trash2, |
| 25 | } from "lucide-react"; |
| 26 | import { |
| 27 | AuthPreviewOperateScope, |
| 28 | AuthFilesystemReadScope, |
| 29 | AuthOrchestrationOperateScope, |
| 30 | AuthTerminalOperateScope, |
| 31 | type ContextMenuItem, |
| 32 | type ProviderInstanceId, |
| 33 | type ResolvedKeybindingsConfig, |
| 34 | type ScopedThreadRef, |
| 35 | type ThreadId, |
| 36 | } from "@t3tools/contracts"; |
| 37 | import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy"; |
| 38 | import * as Schema from "effect/Schema"; |
| 39 | import { AsyncResult } from "effect/reactivity"; |
| 40 | import { |
| 41 | type PointerEvent as ReactPointerEvent, |
| 42 | type ReactNode, |
| 43 | useEffect, |
| 44 | useContext, |
| 45 | useEffectEvent, |
| 46 | useLayoutEffect, |
| 47 | useRef, |
| 48 | useState, |
| 49 | } from "react"; |
| 50 | import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; |
| 51 | import { Button } from "~/components/ui/button"; |
| 52 | import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button"; |
| 53 | import { stackedThreadToast, toastManager } from "~/components/ui/toast"; |
| 54 | import { readTextFromClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard"; |
| 55 | import { cn } from "~/lib/utils"; |
| 56 | import { type TerminalContextSelection } from "~/lib/terminalContext"; |
| 57 | import { |
| 58 | GhosttyTerminalSurface, |
| 59 | type GhosttyTerminalSurfaceOptions, |
| 60 | } from "~/terminal/ghostty/surface"; |
| 61 | import { type GhosttyColor, type GhosttyTheme } from "~/terminal/ghostty/core"; |
| 62 | import { useOpenInPreferredEditor } from "../editorPreferences"; |
| 63 | import { isTerminalUrl, resolveTerminalLinkTarget } from "../terminal-links"; |
| 64 | import { |
| 65 | isDiffToggleShortcut, |
| 66 | isTerminalClearShortcut, |
| 67 | isTerminalNewShortcut, |
| 68 | isTerminalSplitShortcut, |
| 69 | isTerminalSplitVerticalShortcut, |
| 70 | isTerminalToggleShortcut, |
| 71 | isThreadNavigationShortcut, |
| 72 | terminalDeleteShortcutData, |
| 73 | terminalNavigationShortcutData, |
| 74 | } from "../keybindings"; |
| 75 | import { |
| 76 | DEFAULT_THREAD_TERMINAL_HEIGHT, |
| 77 | MAX_TERMINALS_PER_GROUP, |
| 78 | type ThreadTerminalGroup, |
| 79 | } from "../types"; |
| 80 | import { readLocalApi } from "~/localApi"; |
| 81 | import { confirmTerminalClose } from "~/lib/terminalCloseConfirm"; |
| 82 | import { useClientSettings } from "../hooks/useSettings"; |
| 83 | import { getFileMetadataQueryAtom } from "../hooks/useFileMetadata"; |
| 84 | import { FileMetadataThreadContext } from "../hooks/FileMetadataThreadProvider"; |
| 85 | import { useLocalStorage } from "../hooks/useLocalStorage"; |
| 86 | import { attachedTerminalSessionAtom } from "../state/terminalSessions"; |
| 87 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 88 | import { serverEnvironment } from "../state/server"; |
| 89 | import { previewEnvironment } from "../state/preview"; |
| 90 | import { readEnvironmentScope } from "../state/session"; |
| 91 | import { terminalEnvironment } from "../state/terminal"; |
| 92 | import { useEnvironmentScope } from "../state/session"; |
| 93 | import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview"; |
| 94 | import { terminalInputWriter } from "./terminal/terminalInputWriter"; |
| 95 | import { useAtomCommand } from "../state/use-atom-command"; |
| 96 | import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; |
| 97 | import { observeResize } from "../lib/observeResize"; |
| 98 | import { threadShortcutContext } from "./Sidebar.logic"; |
| 99 | import { |
| 100 | consumePendingTerminalFocus, |
| 101 | focusTerminal, |
| 102 | focusTerminalViewport, |
| 103 | registerTerminalFocusTarget, |
| 104 | } from "../lib/terminalFocus"; |
| 105 | import { |
| 106 | resolveTerminalFontPreference, |
| 107 | resolveTerminalFontSizePreference, |
| 108 | TYPOGRAPHY_ADVANCED_STORAGE_KEY, |
| 109 | } from "../appearanceFonts"; |
| 110 | |
| 111 | const MIN_DRAWER_HEIGHT = 180; |
| 112 | const MAX_DRAWER_HEIGHT_RATIO = 0.75; |
| 113 | |
| 114 | interface DrawerLayout { |
| 115 | viewportHeight: number; |
| 116 | chatColumnHeight?: number; |
| 117 | headerHeight?: number; |
| 118 | composerHeight?: number; |
| 119 | } |
| 120 | |
| 121 | function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number { |
| 122 | const windowCap = Math.max( |
| 123 | MIN_DRAWER_HEIGHT, |
| 124 | Math.floor(input.viewportHeight * MAX_DRAWER_HEIGHT_RATIO), |
| 125 | ); |
| 126 | if (input.chatColumnHeight === undefined) return windowCap; |
| 127 | // The composer overlays the timeline, so flex layout cannot reserve its |
| 128 | // height; without this cap a tall drawer pushes it into the header. |
| 129 | return Math.min( |
| 130 | windowCap, |
| 131 | Math.max(0, input.chatColumnHeight - (input.headerHeight ?? 0) - (input.composerHeight ?? 0)), |
| 132 | ); |
| 133 | } |
| 134 | |
| 135 | const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height"; |
| 136 | |
| 137 | function clampDrawerHeight(height: number, maxHeight: number): number { |
| 138 | const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT; |
| 139 | return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight); |
| 140 | } |
| 141 | |
| 142 | function chatColumnOf(drawer: HTMLElement | null): HTMLElement | null { |
| 143 | return drawer?.closest<HTMLElement>("[data-chat-column]") ?? null; |
| 144 | } |
| 145 | |
| 146 | function readDrawerLayout(column: HTMLElement | null): Omit<DrawerLayout, "composerHeight"> { |
| 147 | const viewportHeight = typeof window === "undefined" ? 0 : window.innerHeight; |
| 148 | if (!column) return { viewportHeight }; |
| 149 | return { |
| 150 | viewportHeight, |
| 151 | chatColumnHeight: column.clientHeight, |
| 152 | headerHeight: column.querySelector<HTMLElement>("[data-chat-header]")?.offsetHeight ?? 0, |
| 153 | }; |
| 154 | } |
| 155 | |
| 156 | function writeSystemMessage( |
| 157 | terminal: Pick<GhosttyTerminalSurface, "write">, |
| 158 | message: string, |
| 159 | ): void { |
| 160 | terminal.write(`\r\n[terminal] ${message}\r\n`); |
| 161 | } |
| 162 | |
| 163 | export function writeTerminalOutputUpdate( |
| 164 | terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write">, |
| 165 | update: TerminalOutputUpdate, |
| 166 | ): void { |
| 167 | if (update.type === "reset") { |
| 168 | terminal.resetAndWrite(update.data); |
| 169 | } else if (update.type === "append") { |
| 170 | terminal.write(update.data); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // Avoid formatting unbounded scrollback selections on every output update. |
| 175 | const MAX_COMPARED_SELECTION_CELLS = 3_000; |
| 176 | |
| 177 | export function synchronizeTerminalOutput( |
| 178 | terminal: Pick< |
| 179 | GhosttyTerminalSurface, |
| 180 | "resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection" |
| 181 | >, |
| 182 | session: Pick<TerminalSessionState, "output" | "version">, |
| 183 | cursor: TerminalOutputCursor, |
| 184 | ): TerminalOutputCursor { |
| 185 | if (session.version === 0) return cursor; |
| 186 | const update = readTerminalOutputUpdate(session.output, cursor); |
| 187 | if (update.type === "none") return update.cursor; |
| 188 | const cells = terminal.getSelectionCellCount(); |
| 189 | const compared = cells <= MAX_COMPARED_SELECTION_CELLS; |
| 190 | const selection = cells > 0 && compared ? terminal.getSelection() : ""; |
| 191 | writeTerminalOutputUpdate(terminal, update); |
| 192 | if (!compared || (cells > 0 && terminal.getSelection() !== selection)) { |
| 193 | terminal.clearSelection({ source: "output" }); |
| 194 | } |
| 195 | return update.cursor; |
| 196 | } |
| 197 | |
| 198 | /** Writes what changed between two session notifications: new output, then the error, again after a reset. */ |
| 199 | export function synchronizeTerminalSession( |
| 200 | terminal: Parameters<typeof synchronizeTerminalOutput>[0], |
| 201 | previous: Pick<TerminalSessionState, "output" | "version" | "error">, |
| 202 | session: Pick<TerminalSessionState, "output" | "version" | "error">, |
| 203 | cursor: TerminalOutputCursor, |
| 204 | ): TerminalOutputCursor { |
| 205 | const nextCursor = |
| 206 | session.version === previous.version && session.output === previous.output |
| 207 | ? cursor |
| 208 | : synchronizeTerminalOutput(terminal, session, cursor); |
| 209 | // An attach failure can change only the error, keeping the last buffer. |
| 210 | if ( |
| 211 | session.error !== null && |
| 212 | (session.error !== previous.error || |
| 213 | nextCursor.generation !== cursor.generation || |
| 214 | nextCursor.resetVersion !== cursor.resetVersion) |
| 215 | ) { |
| 216 | writeSystemMessage(terminal, session.error); |
| 217 | } |
| 218 | return nextCursor; |
| 219 | } |
| 220 | |
| 221 | function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor { |
| 222 | if (typeof document === "undefined") return fallback; |
| 223 | |
| 224 | const canvas = document.createElement("canvas"); |
| 225 | canvas.width = 1; |
| 226 | canvas.height = 1; |
| 227 | const context = canvas.getContext("2d", { willReadFrequently: true }); |
| 228 | if (!context) return fallback; |
| 229 | |
| 230 | context.clearRect(0, 0, 1, 1); |
| 231 | context.fillStyle = value; |
| 232 | context.fillRect(0, 0, 1, 1); |
| 233 | const [red, green, blue, alpha] = context.getImageData(0, 0, 1, 1).data; |
| 234 | if (alpha === 0) return fallback; |
| 235 | |
| 236 | return { |
| 237 | r: red ?? fallback.r, |
| 238 | g: green ?? fallback.g, |
| 239 | b: blue ?? fallback.b, |
| 240 | }; |
| 241 | } |
| 242 | |
| 243 | function hexToGhosttyColor(hex: string): GhosttyColor { |
| 244 | const value = Number.parseInt(hex.slice(1), 16); |
| 245 | return { r: (value >> 16) & 255, g: (value >> 8) & 255, b: value & 255 }; |
| 246 | } |
| 247 | |
| 248 | const TERMINAL_PALETTES = { |
| 249 | light: [ |
| 250 | "#000000", |
| 251 | "#cd3131", |
| 252 | "#107c10", |
| 253 | "#949800", |
| 254 | "#0451a5", |
| 255 | "#bc05bc", |
| 256 | "#0598bc", |
| 257 | "#555555", |
| 258 | "#666666", |
| 259 | "#cd3131", |
| 260 | "#14ce14", |
| 261 | "#b5ba00", |
| 262 | "#0451a5", |
| 263 | "#bc05bc", |
| 264 | "#0598bc", |
| 265 | "#a5a5a5", |
| 266 | ].map(hexToGhosttyColor), |
| 267 | dark: [ |
| 268 | "#000000", |
| 269 | "#cd3131", |
| 270 | "#0dbc79", |
| 271 | "#e5e510", |
| 272 | "#2472c8", |
| 273 | "#bc3fbc", |
| 274 | "#11a8cd", |
| 275 | "#e5e5e5", |
| 276 | "#666666", |
| 277 | "#f14c4c", |
| 278 | "#23d18b", |
| 279 | "#f5f543", |
| 280 | "#3b8eea", |
| 281 | "#d670d6", |
| 282 | "#29b8db", |
| 283 | "#e5e5e5", |
| 284 | ].map(hexToGhosttyColor), |
| 285 | }; |
| 286 | |
| 287 | // Read visibility when WASM finishes loading, not when setup starts. |
| 288 | function withLiveVisibility( |
| 289 | visibleRef: { readonly current: boolean }, |
| 290 | options: Omit<GhosttyTerminalSurfaceOptions, "visible">, |
| 291 | ): GhosttyTerminalSurfaceOptions { |
| 292 | return { |
| 293 | ...options, |
| 294 | get visible() { |
| 295 | return visibleRef.current; |
| 296 | }, |
| 297 | }; |
| 298 | } |
| 299 | |
| 300 | function runtimeEnvSignature(runtimeEnv: Record<string, string> | undefined): string { |
| 301 | if (!runtimeEnv) return ""; |
| 302 | return JSON.stringify( |
| 303 | Object.entries(runtimeEnv) |
| 304 | .filter(([key, value]) => key.length > 0 && typeof value === "string") |
| 305 | .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)), |
| 306 | ); |
| 307 | } |
| 308 | |
| 309 | function normalizeComputedColor(value: string | null | undefined, fallback: string): string { |
| 310 | const normalizedValue = value?.trim().toLowerCase(); |
| 311 | if ( |
| 312 | !normalizedValue || |
| 313 | normalizedValue === "transparent" || |
| 314 | normalizedValue === "rgba(0, 0, 0, 0)" || |
| 315 | normalizedValue === "rgba(0 0 0 / 0)" |
| 316 | ) { |
| 317 | return fallback; |
| 318 | } |
| 319 | return value ?? fallback; |
| 320 | } |
| 321 | |
| 322 | function readThemeColor(styles: CSSStyleDeclaration, variable: string, fallback: string): string { |
| 323 | return normalizeComputedColor(styles.getPropertyValue(variable), fallback); |
| 324 | } |
| 325 | |
| 326 | function terminalFontOptions(family: string, size: number): { family?: string; size: number } { |
| 327 | const trimmed = family.trim(); |
| 328 | return trimmed.length > 0 ? { family: trimmed, size } : { size }; |
| 329 | } |
| 330 | |
| 331 | export function terminalThemeFromApp(mountElement?: HTMLElement | null): GhosttyTheme { |
| 332 | const drawerSurface = |
| 333 | mountElement?.closest("[data-thread-terminal-drawer]") ?? |
| 334 | document.querySelector("[data-thread-terminal-drawer]") ?? |
| 335 | document.body; |
| 336 | const drawerStyles = getComputedStyle(drawerSurface); |
| 337 | const themeStyles = mountElement ? getComputedStyle(mountElement) : drawerStyles; |
| 338 | const colorScheme = themeStyles.colorScheme; |
| 339 | const isDark = |
| 340 | colorScheme === "dark" |
| 341 | ? true |
| 342 | : colorScheme === "light" |
| 343 | ? false |
| 344 | : document.documentElement.classList.contains("dark"); |
| 345 | const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"; |
| 346 | const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)"; |
| 347 | const bodyStyles = getComputedStyle(document.body); |
| 348 | const rootThemeStyles = getComputedStyle(document.documentElement); |
| 349 | const background = normalizeComputedColor( |
| 350 | drawerStyles.backgroundColor, |
| 351 | normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground), |
| 352 | ); |
| 353 | const foreground = normalizeComputedColor( |
| 354 | drawerStyles.color, |
| 355 | normalizeComputedColor(bodyStyles.color, fallbackForeground), |
| 356 | ); |
| 357 | const terminalBackground = readThemeColor( |
| 358 | themeStyles, |
| 359 | "--terminal-background", |
| 360 | readThemeColor(rootThemeStyles, "--terminal-background", background), |
| 361 | ); |
| 362 | const terminalForeground = readThemeColor( |
| 363 | themeStyles, |
| 364 | "--terminal-foreground", |
| 365 | readThemeColor(rootThemeStyles, "--terminal-foreground", foreground), |
| 366 | ); |
| 367 | const terminalCursor = readThemeColor( |
| 368 | themeStyles, |
| 369 | "--terminal-cursor", |
| 370 | isDark ? "rgb(180, 203, 255)" : "rgb(38, 56, 78)", |
| 371 | ); |
| 372 | const terminalSelection = readThemeColor( |
| 373 | themeStyles, |
| 374 | "--terminal-selection-background", |
| 375 | isDark ? "rgba(180, 203, 255, 0.25)" : "rgba(37, 63, 99, 0.2)", |
| 376 | ); |
| 377 | return { |
| 378 | background: parseTerminalColor( |
| 379 | terminalBackground, |
| 380 | isDark ? { r: 14, g: 18, b: 24 } : { r: 255, g: 255, b: 255 }, |
| 381 | ), |
| 382 | foreground: parseTerminalColor( |
| 383 | terminalForeground, |
| 384 | isDark ? { r: 237, g: 241, b: 247 } : { r: 28, g: 33, b: 41 }, |
| 385 | ), |
| 386 | cursor: parseTerminalColor( |
| 387 | terminalCursor, |
| 388 | isDark ? { r: 180, g: 203, b: 255 } : { r: 38, g: 56, b: 78 }, |
| 389 | ), |
| 390 | palette: TERMINAL_PALETTES[isDark ? "dark" : "light"], |
| 391 | selectionBackground: terminalSelection, |
| 392 | }; |
| 393 | } |
| 394 | |
| 395 | function terminalSelectionLineRange(position: { start: { y: number }; end: { y: number } }): { |
| 396 | lineStart: number; |
| 397 | lineEnd: number; |
| 398 | } { |
| 399 | const lineStart = position.start.y + 1; |
| 400 | return { |
| 401 | lineStart, |
| 402 | lineEnd: Math.max(lineStart, position.end.y + 1), |
| 403 | }; |
| 404 | } |
| 405 | |
| 406 | export type TerminalContextMenuAction = |
| 407 | | "add-to-chat" |
| 408 | | "copy" |
| 409 | | "paste" |
| 410 | | "select-all" |
| 411 | | "scroll-to-bottom"; |
| 412 | |
| 413 | function terminalSelectionMenuItems(options?: { |
| 414 | canAddToChat?: boolean; |
| 415 | }): ContextMenuItem<"add-to-chat" | "copy">[] { |
| 416 | return [ |
| 417 | ...(options?.canAddToChat === false |
| 418 | ? [] |
| 419 | : ([ |
| 420 | { id: "add-to-chat", label: m(msg("Add to chat")) }, |
| 421 | ] satisfies ContextMenuItem<"add-to-chat">[])), |
| 422 | { id: "copy", label: m(msg("Copy")) }, |
| 423 | ]; |
| 424 | } |
| 425 | |
| 426 | function terminalContextMenuItems(options: { |
| 427 | hasSelection: boolean; |
| 428 | canAddToChat?: boolean; |
| 429 | readOnly?: boolean; |
| 430 | }): ContextMenuItem<TerminalContextMenuAction>[] { |
| 431 | const { hasSelection, canAddToChat = true } = options; |
| 432 | return [ |
| 433 | ...terminalSelectionMenuItems({ canAddToChat }).map((item) => ({ |
| 434 | ...item, |
| 435 | disabled: !hasSelection, |
| 436 | })), |
| 437 | { id: "paste", label: m(msg("Paste")), ...(options.readOnly ? { disabled: true } : {}) }, |
| 438 | { id: "select-all", label: m(msg("Select all", { $context: "select all terminal text" })) }, |
| 439 | { id: "scroll-to-bottom", label: m(msg("Jump to latest")) }, |
| 440 | ]; |
| 441 | } |
| 442 | |
| 443 | /** |
| 444 | * A writable session's output generation. A new one is a fresh PTY (or a |
| 445 | * reconnect) that has not seen the surface's grid yet. |
| 446 | */ |
| 447 | function writableSessionGeneration( |
| 448 | session: TerminalSessionState, |
| 449 | canOperate: boolean, |
| 450 | ): number | null { |
| 451 | return canOperate && session.version > 0 && session.status === "running" |
| 452 | ? session.output.generation |
| 453 | : null; |
| 454 | } |
| 455 | |
| 456 | export function shouldHandleTerminalExit( |
| 457 | current: TerminalSessionState["status"], |
| 458 | synchronized: TerminalSessionState["status"], |
| 459 | alreadyHandled: boolean, |
| 460 | version: number, |
| 461 | ): boolean { |
| 462 | return ( |
| 463 | version > 0 && |
| 464 | (current === "closed" || current === "exited") && |
| 465 | current !== synchronized && |
| 466 | !alreadyHandled |
| 467 | ); |
| 468 | } |
| 469 | |
| 470 | interface TerminalViewportProps { |
| 471 | advancedTypography: boolean; |
| 472 | threadRef: ScopedThreadRef; |
| 473 | threadId: ThreadId; |
| 474 | terminalId: string; |
| 475 | terminalLabel: string; |
| 476 | cwd: string; |
| 477 | worktreePath?: string | null; |
| 478 | runtimeEnv?: Record<string, string>; |
| 479 | providerInstanceId?: ProviderInstanceId; |
| 480 | onSessionExited: () => void; |
| 481 | onAddTerminalContext?: (selection: TerminalContextSelection) => void; |
| 482 | /** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */ |
| 483 | autoFocus?: boolean; |
| 484 | visible: boolean; |
| 485 | keybindings: ResolvedKeybindingsConfig; |
| 486 | } |
| 487 | |
| 488 | interface TerminalLaunchLocation { |
| 489 | readonly cwd: string; |
| 490 | readonly worktreePath?: string | null; |
| 491 | readonly runtimeEnv?: Record<string, string>; |
| 492 | } |
| 493 | |
| 494 | export function TerminalViewport(props: TerminalViewportProps) { |
| 495 | const sessionKey = JSON.stringify([ |
| 496 | props.threadRef.environmentId, |
| 497 | props.threadId, |
| 498 | props.terminalId, |
| 499 | props.cwd, |
| 500 | props.worktreePath ?? null, |
| 501 | runtimeEnvSignature(props.runtimeEnv), |
| 502 | ]); |
| 503 | return <TerminalSessionViewport key={sessionKey} {...props} />; |
| 504 | } |
| 505 | |
| 506 | function TerminalSessionViewport({ |
| 507 | advancedTypography, |
| 508 | threadRef, |
| 509 | threadId, |
| 510 | terminalId, |
| 511 | terminalLabel, |
| 512 | cwd, |
| 513 | worktreePath, |
| 514 | runtimeEnv, |
| 515 | providerInstanceId, |
| 516 | onSessionExited, |
| 517 | onAddTerminalContext, |
| 518 | autoFocus = false, |
| 519 | visible, |
| 520 | keybindings, |
| 521 | }: TerminalViewportProps) { |
| 522 | const containerRef = useRef<HTMLDivElement>(null); |
| 523 | const autoFocusedRef = useRef(false); |
| 524 | const terminalRef = useRef<GhosttyTerminalSurface | null>(null); |
| 525 | const visibleRef = useRef(visible); |
| 526 | const environmentId = threadRef.environmentId; |
| 527 | const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); |
| 528 | const hasTerminalWriteAccess = useEffectEvent(() => |
| 529 | readEnvironmentScope(environmentId, AuthTerminalOperateScope), |
| 530 | ); |
| 531 | const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); |
| 532 | const canReadFilesystem = useEnvironmentScope(environmentId, AuthFilesystemReadScope); |
| 533 | const [linkPath, setLinkPath] = useState<string | null>(null); |
| 534 | const metadataThreadRef = useContext(FileMetadataThreadContext); |
| 535 | const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId)); |
| 536 | const hostname = serverConfig?.hostname; |
| 537 | const readHostname = useEffectEvent(() => hostname); |
| 538 | const linkMetadataQuery = |
| 539 | linkPath !== null && canOpenHostEditor && canReadFilesystem |
| 540 | ? getFileMetadataQueryAtom( |
| 541 | environmentId, |
| 542 | resolveTerminalLinkTarget(linkPath, cwd, hostname), |
| 543 | cwd, |
| 544 | metadataThreadRef, |
| 545 | ) |
| 546 | : null; |
| 547 | const canActivateTerminalLink = useEffectEvent((text: string) => { |
| 548 | if (isTerminalUrl(text)) return true; |
| 549 | if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; |
| 550 | if (text !== linkPath || !linkMetadataQuery) return false; |
| 551 | const metadata = AsyncResult.getOrElse(appAtomRegistry.get(linkMetadataQuery), () => null); |
| 552 | return metadata?.kind === "file" || metadata?.kind === "directory"; |
| 553 | }); |
| 554 | const validateTerminalLink = useEffectEvent(async (text: string) => { |
| 555 | if (isTerminalUrl(text)) return true; |
| 556 | if ( |
| 557 | !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || |
| 558 | !readEnvironmentScope(environmentId, AuthFilesystemReadScope) |
| 559 | ) |
| 560 | return false; |
| 561 | const query = getFileMetadataQueryAtom( |
| 562 | environmentId, |
| 563 | resolveTerminalLinkTarget(text, cwd, hostname), |
| 564 | cwd, |
| 565 | metadataThreadRef, |
| 566 | ); |
| 567 | if (!query) return false; |
| 568 | const result = await executeAtomQuery(appAtomRegistry, query, { reportFailure: false }); |
| 569 | return ( |
| 570 | result._tag === "Success" && |
| 571 | (result.value?.kind === "file" || result.value?.kind === "directory") |
| 572 | ); |
| 573 | }); |
| 574 | const openInPreferredEditor = useOpenInPreferredEditor( |
| 575 | environmentId, |
| 576 | serverConfig?.availableEditors ?? [], |
| 577 | worktreePath ?? cwd, |
| 578 | ); |
| 579 | const openTerminalPath = useEffectEvent((target: string) => openInPreferredEditor(target)); |
| 580 | const openPreview = useAtomCommand(previewEnvironment.open, { |
| 581 | reportFailure: false, |
| 582 | }); |
| 583 | const runTerminalWrite = useAtomCommand(terminalEnvironment.write, { |
| 584 | reportFailure: false, |
| 585 | }); |
| 586 | // Recovery keeps the original registry-bound command after this viewport unmounts. |
| 587 | const retainedTerminalWrite = useRef(runTerminalWrite); |
| 588 | const runTerminalResize = useAtomCommand(terminalEnvironment.resize, { |
| 589 | reportFailure: false, |
| 590 | }); |
| 591 | const hasHandledExitRef = useRef(false); |
| 592 | const selectionActionRequestIdRef = useRef(0); |
| 593 | const readKeybindings = useEffectEvent(() => keybindings); |
| 594 | const readThreadShortcutContext = useEffectEvent(() => threadShortcutContext(threadRef)); |
| 595 | const handleSessionExited = useEffectEvent(() => { |
| 596 | if (hasTerminalWriteAccess()) onSessionExited(); |
| 597 | }); |
| 598 | const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => { |
| 599 | onAddTerminalContext?.(selection); |
| 600 | }); |
| 601 | const canAddSelectionToChat = useEffectEvent(() => onAddTerminalContext !== undefined); |
| 602 | const readTerminalLabel = useEffectEvent(() => terminalLabel); |
| 603 | const terminalFontFamily = useClientSettings((settings) => |
| 604 | resolveTerminalFontPreference({ |
| 605 | advanced: advancedTypography, |
| 606 | code: settings.fontFamilyCode, |
| 607 | terminal: settings.fontFamilyTerminal, |
| 608 | }), |
| 609 | ); |
| 610 | const terminalFontSize = useClientSettings((settings) => |
| 611 | resolveTerminalFontSizePreference({ |
| 612 | advanced: advancedTypography, |
| 613 | code: settings.fontSizeCode, |
| 614 | terminal: settings.fontSizeTerminal, |
| 615 | }), |
| 616 | ); |
| 617 | const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize }); |
| 618 | // Keyed by the launch (see TerminalViewport), so the atom is fixed for this surface. |
| 619 | const terminalSessionAtom = attachedTerminalSessionAtom(environmentId, { |
| 620 | threadId, |
| 621 | terminalId, |
| 622 | cwd, |
| 623 | ...(worktreePath !== undefined ? { worktreePath } : {}), |
| 624 | ...(runtimeEnv ? { env: runtimeEnv } : {}), |
| 625 | ...(providerInstanceId ? { providerInstanceId } : {}), |
| 626 | }); |
| 627 | // Attaching starts with the viewport, while the WASM surface is still loading; |
| 628 | // the surface reads the session itself, so output chunks never re-render here. |
| 629 | useAtomMount(terminalSessionAtom); |
| 630 | const readTerminalSession = useEffectEvent(() => appAtomRegistry.get(terminalSessionAtom)); |
| 631 | const subscribeTerminalSession = useEffectEvent( |
| 632 | (listener: (session: TerminalSessionState) => void) => |
| 633 | appAtomRegistry.subscribe(terminalSessionAtom, listener), |
| 634 | ); |
| 635 | // The surface reports a resent grid like any other, so the next report is the retry. |
| 636 | const resizeRetryGenerationRef = useRef<number | null>(null); |
| 637 | const resizeTerminal = useEffectEvent(async (cols: number, rows: number) => { |
| 638 | const generation = writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()); |
| 639 | const retry = generation !== null && generation === resizeRetryGenerationRef.current; |
| 640 | resizeRetryGenerationRef.current = null; |
| 641 | if (generation === null) return; |
| 642 | const result = await runTerminalResize({ |
| 643 | environmentId, |
| 644 | input: { threadId, terminalId, cols, rows }, |
| 645 | }); |
| 646 | // Resend the current grid, not this one: a newer resize may already be queued behind it. |
| 647 | if (!retry && result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 648 | resizeRetryGenerationRef.current = generation; |
| 649 | terminalRef.current?.resendSize(); |
| 650 | } |
| 651 | }); |
| 652 | const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR); |
| 653 | const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed"); |
| 654 | const synchronizeTerminalStatus = useEffectEvent( |
| 655 | (terminal: GhosttyTerminalSurface, status: TerminalSessionState["status"], version: number) => { |
| 656 | const synchronized = synchronizedStatusRef.current; |
| 657 | if (version > 0 && status === "running") { |
| 658 | hasHandledExitRef.current = false; |
| 659 | } else if ( |
| 660 | shouldHandleTerminalExit(status, synchronized, hasHandledExitRef.current, version) |
| 661 | ) { |
| 662 | hasHandledExitRef.current = true; |
| 663 | writeSystemMessage( |
| 664 | terminal, |
| 665 | status === "closed" ? m(msg("Terminal closed")) : m(msg("Process exited")), |
| 666 | ); |
| 667 | window.setTimeout(() => { |
| 668 | if (hasHandledExitRef.current) { |
| 669 | handleSessionExited(); |
| 670 | } |
| 671 | }, 0); |
| 672 | } |
| 673 | if (version > 0) synchronizedStatusRef.current = status; |
| 674 | }, |
| 675 | ); |
| 676 | const openLinkInPreview = useEffectEvent( |
| 677 | (url: string, forceBrowser: boolean, fallbackToBrowser: () => void) => |
| 678 | openTerminalLinkInPreview({ url, threadRef, openPreview, fallbackToBrowser, forceBrowser }), |
| 679 | ); |
| 680 | |
| 681 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- sets the terminal input's readOnly from the operate grant and consumes a pending focus request |
| 682 | useLayoutEffect(() => { |
| 683 | if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal; |
| 684 | if (canOperateTerminal && visibleRef.current) |
| 685 | consumePendingTerminalFocus(threadRef, terminalId); |
| 686 | }, [canOperateTerminal, terminalId, threadRef]); |
| 687 | |
| 688 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the imperative terminal's hovered link after filesystem metadata or editor permissions change |
| 689 | useEffect(() => { |
| 690 | if (!linkMetadataQuery) { |
| 691 | terminalRef.current?.refreshLinkActivation(); |
| 692 | return; |
| 693 | } |
| 694 | return appAtomRegistry.subscribe( |
| 695 | linkMetadataQuery, |
| 696 | () => terminalRef.current?.refreshLinkActivation(), |
| 697 | { immediate: true }, |
| 698 | ); |
| 699 | }, [linkMetadataQuery]); |
| 700 | |
| 701 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes visibility into the terminal surface before paint and consumes focus requests made while hidden |
| 702 | useLayoutEffect(() => { |
| 703 | visibleRef.current = visible; |
| 704 | terminalRef.current?.setVisible(visible); |
| 705 | // A request made while this viewport was hidden could not focus it. |
| 706 | if (visible) consumePendingTerminalFocus(threadRef, terminalId); |
| 707 | }, [terminalId, threadRef, visible]); |
| 708 | |
| 709 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies font family and size changes to the live Ghostty terminal surface |
| 710 | useEffect(() => { |
| 711 | const current = terminalFontRef.current; |
| 712 | if (current.family === terminalFontFamily && current.size === terminalFontSize) return; |
| 713 | terminalFontRef.current = { family: terminalFontFamily, size: terminalFontSize }; |
| 714 | void terminalRef.current?.setFont(terminalFontOptions(terminalFontFamily, terminalFontSize)); |
| 715 | }, [terminalFontFamily, terminalFontSize]); |
| 716 | |
| 717 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates the Ghostty terminal in the mount node and subscribes it to the terminal session |
| 718 | useEffect(() => { |
| 719 | const mount = containerRef.current; |
| 720 | if (!mount) return; |
| 721 | |
| 722 | const localApi = readLocalApi(); |
| 723 | let cancelled = false; |
| 724 | let teardown: (() => void) | null = null; |
| 725 | let setupTerminal: GhosttyTerminalSurface | null = null; |
| 726 | let setupCleanups: Array<() => void> = []; |
| 727 | |
| 728 | const setup = async (): Promise<(() => void) | null> => { |
| 729 | const setupFont = terminalFontRef.current; |
| 730 | const terminalOptions = withLiveVisibility(visibleRef, { |
| 731 | theme: terminalThemeFromApp(mount), |
| 732 | font: terminalFontOptions(setupFont.family, setupFont.size), |
| 733 | onData: (data) => handleData(data), |
| 734 | onBinary: (data) => void sendTerminalInput(data, m(msg("Terminal write failed")), "binary"), |
| 735 | onReply: (data) => void sendTerminalInput(data, m(msg("Terminal write failed")), "reply"), |
| 736 | onResize: (cols, rows) => void resizeTerminal(cols, rows), |
| 737 | onSelectionChange: () => {}, |
| 738 | beforeKey: (event) => handleBeforeKey(event), |
| 739 | onLinkActivate: (text, event) => handleLinkActivate(text, event), |
| 740 | canActivateLink: (text) => canActivateTerminalLink(text), |
| 741 | validateLink: (text) => validateTerminalLink(text), |
| 742 | onLinkHover: (text) => setLinkPath(text !== null && !isTerminalUrl(text) ? text : null), |
| 743 | // Surface listeners start before WASM loading finishes and the terminal handler exists. |
| 744 | onContextMenu: (event) => { |
| 745 | if (terminalRef.current) void showTerminalContextMenu(event); |
| 746 | }, |
| 747 | }); |
| 748 | const terminal = await GhosttyTerminalSurface.create(mount, terminalOptions); |
| 749 | if (cancelled) { |
| 750 | terminal.dispose(); |
| 751 | return null; |
| 752 | } |
| 753 | terminal.setVisible(visibleRef.current); |
| 754 | // Re-read theme changes during WASM loading, before the observer was installed. |
| 755 | terminal.setTheme(terminalThemeFromApp(mount)); |
| 756 | setupTerminal = terminal; |
| 757 | terminalRef.current = terminal; |
| 758 | terminal.input.setAttribute("data-workspace-focus-default", ""); |
| 759 | terminal.input.readOnly = !hasTerminalWriteAccess(); |
| 760 | // Reapply font settings hydrated during loading, when terminalRef was null. |
| 761 | const currentFont = terminalFontRef.current; |
| 762 | if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) { |
| 763 | void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size)); |
| 764 | } |
| 765 | const latestSession = readTerminalSession(); |
| 766 | terminal.setSharedGrid(latestSession.grid); |
| 767 | const initialOutput = readTerminalOutputUpdate( |
| 768 | latestSession.output, |
| 769 | INITIAL_TERMINAL_OUTPUT_CURSOR, |
| 770 | ); |
| 771 | if (initialOutput.type === "reset" && initialOutput.data.length > 0) { |
| 772 | writeTerminalOutputUpdate(terminal, initialOutput); |
| 773 | } |
| 774 | outputCursorRef.current = initialOutput.cursor; |
| 775 | if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error); |
| 776 | synchronizedStatusRef.current = "closed"; |
| 777 | synchronizeTerminalStatus(terminal, latestSession.status, latestSession.version); |
| 778 | // Read and subscribe in one synchronous step so no output lands between them. |
| 779 | let previousSession = latestSession; |
| 780 | let resizeGeneration = writableSessionGeneration(latestSession, hasTerminalWriteAccess()); |
| 781 | setupCleanups.push( |
| 782 | subscribeTerminalSession((session) => { |
| 783 | const nextResizeGeneration = writableSessionGeneration(session, hasTerminalWriteAccess()); |
| 784 | if (nextResizeGeneration !== resizeGeneration) { |
| 785 | resizeGeneration = nextResizeGeneration; |
| 786 | // The first fit can precede authorization/attach; replay the grid for each writable session, including |
| 787 | // reconnects. |
| 788 | if (nextResizeGeneration !== null) terminal.resendSize(); |
| 789 | } |
| 790 | const previous = previousSession; |
| 791 | previousSession = session; |
| 792 | terminal.setSharedGrid(session.grid); |
| 793 | synchronizeTerminalStatus(terminal, session.status, session.version); |
| 794 | outputCursorRef.current = synchronizeTerminalSession( |
| 795 | terminal, |
| 796 | previous, |
| 797 | session, |
| 798 | outputCursorRef.current, |
| 799 | ); |
| 800 | }), |
| 801 | ); |
| 802 | if ( |
| 803 | hasTerminalWriteAccess() && |
| 804 | visibleRef.current && |
| 805 | mount.contains(document.activeElement) |
| 806 | ) { |
| 807 | terminal.focus(); |
| 808 | } |
| 809 | |
| 810 | const clearSelectionAction = () => { |
| 811 | selectionActionRequestIdRef.current += 1; |
| 812 | }; |
| 813 | setupCleanups.push(clearSelectionAction); |
| 814 | |
| 815 | const readSelectionAction = (): { |
| 816 | clipboardText: string; |
| 817 | selection: TerminalContextSelection; |
| 818 | } | null => { |
| 819 | const activeTerminal = terminalRef.current; |
| 820 | if (!activeTerminal || !activeTerminal.hasSelection()) { |
| 821 | return null; |
| 822 | } |
| 823 | const selectionText = activeTerminal.getSelection(); |
| 824 | const selectionPosition = activeTerminal.getSelectionPosition(); |
| 825 | const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, ""); |
| 826 | if (!selectionPosition || normalizedText.length === 0) { |
| 827 | return null; |
| 828 | } |
| 829 | const { lineStart, lineEnd } = terminalSelectionLineRange(selectionPosition); |
| 830 | return { |
| 831 | clipboardText: selectionText, |
| 832 | selection: { |
| 833 | terminalId, |
| 834 | terminalLabel: readTerminalLabel(), |
| 835 | lineStart, |
| 836 | lineEnd, |
| 837 | text: normalizedText, |
| 838 | }, |
| 839 | }; |
| 840 | }; |
| 841 | |
| 842 | const addSelectionToChat = (clipboardText: string) => { |
| 843 | // Output keeps moving the selected rows while a menu is open, so take |
| 844 | // the line numbers now, and only if the same text is still selected. |
| 845 | const current = readSelectionAction(); |
| 846 | if (current?.clipboardText !== clipboardText) return; |
| 847 | handleAddTerminalContext(current.selection); |
| 848 | terminalRef.current?.clearSelection(); |
| 849 | terminalRef.current?.focus(); |
| 850 | }; |
| 851 | |
| 852 | const reportIfCurrent = (requestId: number, error: unknown, fallback: string) => { |
| 853 | if (requestId !== selectionActionRequestIdRef.current) return; |
| 854 | const activeTerminal = terminalRef.current; |
| 855 | if (activeTerminal) { |
| 856 | writeSystemMessage(activeTerminal, thrownErrorMessage(error, m) ?? fallback); |
| 857 | } |
| 858 | }; |
| 859 | |
| 860 | const focusIfCurrent = (requestId: number) => { |
| 861 | if (requestId === selectionActionRequestIdRef.current) { |
| 862 | terminalRef.current?.focus(); |
| 863 | } |
| 864 | }; |
| 865 | |
| 866 | const copySelection = async (text: string, requestId: number) => { |
| 867 | try { |
| 868 | await writeTextToClipboard(text, { |
| 869 | target: "terminal selection", |
| 870 | unavailableMessage: msg( |
| 871 | "Clipboard API is unavailable while copying terminal selection.", |
| 872 | ), |
| 873 | failureMessage: msg("Failed to copy terminal selection to the clipboard."), |
| 874 | }); |
| 875 | } catch (error) { |
| 876 | reportIfCurrent(requestId, error, m(msg("Unable to copy terminal selection"))); |
| 877 | } |
| 878 | focusIfCurrent(requestId); |
| 879 | }; |
| 880 | |
| 881 | const pasteFromClipboard = async (requestId: number) => { |
| 882 | if (!hasTerminalWriteAccess()) return; |
| 883 | const activeTerminal = terminalRef.current; |
| 884 | if (!activeTerminal) return; |
| 885 | try { |
| 886 | // Let the surface own clipboard reads so paste shortcuts can supersede an in-flight menu paste. |
| 887 | await activeTerminal.pasteFromClipboard( |
| 888 | () => |
| 889 | readTextFromClipboard({ |
| 890 | target: "terminal input", |
| 891 | unavailableMessage: msg( |
| 892 | "Clipboard API is unavailable while reading terminal input.", |
| 893 | ), |
| 894 | failureMessage: msg("Failed to read terminal input from the clipboard."), |
| 895 | }), |
| 896 | () => requestId === selectionActionRequestIdRef.current, |
| 897 | ); |
| 898 | } catch (error) { |
| 899 | reportIfCurrent(requestId, error, m(msg("Unable to read the clipboard"))); |
| 900 | return; |
| 901 | } |
| 902 | focusIfCurrent(requestId); |
| 903 | }; |
| 904 | |
| 905 | const showTerminalContextMenu = async (event: MouseEvent) => { |
| 906 | if (!localApi || !terminalRef.current) return; |
| 907 | // Prevent default before awaits; native menus offer a permanently disabled Paste over the canvas. |
| 908 | event.preventDefault(); |
| 909 | clearSelectionAction(); |
| 910 | const selectionAction = readSelectionAction(); |
| 911 | const requestId = selectionActionRequestIdRef.current; |
| 912 | let clicked: TerminalContextMenuAction | null; |
| 913 | try { |
| 914 | clicked = await localApi.contextMenu.show( |
| 915 | terminalContextMenuItems({ |
| 916 | hasSelection: selectionAction !== null, |
| 917 | canAddToChat: canAddSelectionToChat(), |
| 918 | readOnly: !hasTerminalWriteAccess(), |
| 919 | }), |
| 920 | { x: event.clientX, y: event.clientY }, |
| 921 | ); |
| 922 | } catch (error) { |
| 923 | reportIfCurrent(requestId, error, m(msg("Unable to open the terminal context menu"))); |
| 924 | focusIfCurrent(requestId); |
| 925 | return; |
| 926 | } |
| 927 | if (requestId !== selectionActionRequestIdRef.current || clicked === null) { |
| 928 | return; |
| 929 | } |
| 930 | switch (clicked) { |
| 931 | case "add-to-chat": |
| 932 | if (selectionAction && canAddSelectionToChat()) { |
| 933 | addSelectionToChat(selectionAction.clipboardText); |
| 934 | } |
| 935 | return; |
| 936 | case "copy": |
| 937 | if (selectionAction) await copySelection(selectionAction.clipboardText, requestId); |
| 938 | return; |
| 939 | case "paste": |
| 940 | await pasteFromClipboard(requestId); |
| 941 | return; |
| 942 | case "select-all": |
| 943 | terminalRef.current?.selectAll(); |
| 944 | focusIfCurrent(requestId); |
| 945 | return; |
| 946 | case "scroll-to-bottom": |
| 947 | terminalRef.current?.scrollToBottom(); |
| 948 | focusIfCurrent(requestId); |
| 949 | return; |
| 950 | } |
| 951 | }; |
| 952 | |
| 953 | const readInputSession = () => appAtomRegistry.get(terminalSessionAtom); |
| 954 | const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope); |
| 955 | const writeInputChunk = (data: string, kind?: "binary" | "reply") => |
| 956 | retainedTerminalWrite.current({ |
| 957 | environmentId, |
| 958 | input: kind |
| 959 | ? { threadId, terminalId, data, [kind]: true } |
| 960 | : { threadId, terminalId, data }, |
| 961 | }); |
| 962 | const sendTerminalInput = ( |
| 963 | data: string, |
| 964 | fallbackError: string, |
| 965 | kind?: "binary" | "reply", |
| 966 | ) => { |
| 967 | // The server rejects input until the shell runs, and each rejection would print an error. |
| 968 | // Input belongs to the shell and surface it was typed into; a restart the client has seen drops what is left. |
| 969 | const session = readTerminalSession(); |
| 970 | const generation = writableSessionGeneration(session, hasTerminalWriteAccess()); |
| 971 | const lifecycleVersion = session.lifecycleVersion; |
| 972 | if (generation === null) return; |
| 973 | const writeInput = terminalInputWriter( |
| 974 | JSON.stringify([environmentId, threadId, terminalId]), |
| 975 | () => appAtomRegistry.mount(terminalSessionAtom), |
| 976 | ); |
| 977 | let reported = false; |
| 978 | const report = (message: string) => { |
| 979 | if (reported || terminalRef.current !== terminal) return; |
| 980 | reported = true; |
| 981 | writeSystemMessage(terminal, message); |
| 982 | }; |
| 983 | return writeInput( |
| 984 | data, |
| 985 | async (chunk) => { |
| 986 | const currentSession = readInputSession(); |
| 987 | if ( |
| 988 | terminalRef.current !== terminal || |
| 989 | currentSession.lifecycleVersion !== lifecycleVersion || |
| 990 | writableSessionGeneration(currentSession, canWriteInput()) !== generation |
| 991 | ) { |
| 992 | return "not-dispatched"; |
| 993 | } |
| 994 | const result = await writeInputChunk(chunk, kind); |
| 995 | if (result._tag === "Success") return true; |
| 996 | if (terminalRef.current === terminal && !isAtomCommandInterrupted(result)) { |
| 997 | const error = squashAtomCommandFailure(result); |
| 998 | report(thrownErrorMessage(error, m) ?? fallbackError); |
| 999 | } |
| 1000 | return false; |
| 1001 | }, |
| 1002 | // Close the bracket only for the process that saw it open; wait while its pid is unknown. |
| 1003 | async () => { |
| 1004 | const pid = session.summary?.pid ?? null; |
| 1005 | const current = readInputSession(); |
| 1006 | const currentPid = current.summary?.pid ?? null; |
| 1007 | if (currentPid === null) return false; |
| 1008 | if (pid !== null && currentPid !== pid) return true; |
| 1009 | if (writableSessionGeneration(current, canWriteInput()) === null) return false; |
| 1010 | const result = await writeInputChunk("\x1b[201~"); |
| 1011 | if (result._tag === "Success") return true; |
| 1012 | if (!isAtomCommandInterrupted(result)) { |
| 1013 | const error = squashAtomCommandFailure(result); |
| 1014 | report(thrownErrorMessage(error, m) ?? m(msg("Failed to close interrupted paste"))); |
| 1015 | } |
| 1016 | return false; |
| 1017 | }, |
| 1018 | () => |
| 1019 | report(m(msg("Terminal paste interrupted. Paste again when the terminal is ready."))), |
| 1020 | ); |
| 1021 | }; |
| 1022 | |
| 1023 | function handleBeforeKey(event: KeyboardEvent): boolean { |
| 1024 | const currentKeybindings = readKeybindings(); |
| 1025 | const options = { context: { terminalFocus: true, terminalOpen: true } }; |
| 1026 | if (preventTerminalCloseShortcut(event, currentKeybindings)) { |
| 1027 | return false; |
| 1028 | } |
| 1029 | if ( |
| 1030 | isTerminalToggleShortcut(event, currentKeybindings, options) || |
| 1031 | isTerminalSplitShortcut(event, currentKeybindings, options) || |
| 1032 | isTerminalSplitVerticalShortcut(event, currentKeybindings, options) || |
| 1033 | isTerminalNewShortcut(event, currentKeybindings, options) || |
| 1034 | isDiffToggleShortcut(event, currentKeybindings, options) || |
| 1035 | // Match Sidebar's context, or a key it will reject skips the shell. |
| 1036 | isThreadNavigationShortcut(event, currentKeybindings, { |
| 1037 | context: { ...readThreadShortcutContext(), terminalFocus: true }, |
| 1038 | }) |
| 1039 | ) { |
| 1040 | return false; |
| 1041 | } |
| 1042 | |
| 1043 | const navigationData = terminalNavigationShortcutData(event); |
| 1044 | if (navigationData !== null) { |
| 1045 | event.preventDefault(); |
| 1046 | event.stopPropagation(); |
| 1047 | void sendTerminalInput(navigationData, m(msg("Failed to move cursor"))); |
| 1048 | return false; |
| 1049 | } |
| 1050 | |
| 1051 | const deleteData = terminalDeleteShortcutData(event); |
| 1052 | if (deleteData !== null) { |
| 1053 | event.preventDefault(); |
| 1054 | event.stopPropagation(); |
| 1055 | void sendTerminalInput(deleteData, m(msg("Failed to delete terminal input"))); |
| 1056 | return false; |
| 1057 | } |
| 1058 | |
| 1059 | if (!isTerminalClearShortcut(event)) return true; |
| 1060 | event.preventDefault(); |
| 1061 | event.stopPropagation(); |
| 1062 | void sendTerminalInput("\u000c", m(msg("Failed to clear terminal"))); |
| 1063 | return false; |
| 1064 | } |
| 1065 | |
| 1066 | function handleLinkActivate(text: string, event: MouseEvent): void { |
| 1067 | if ( |
| 1068 | !isTerminalUrl(text) && |
| 1069 | !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) |
| 1070 | ) |
| 1071 | return; |
| 1072 | const latestTerminal = terminalRef.current; |
| 1073 | if (!latestTerminal) return; |
| 1074 | if (isTerminalUrl(text)) { |
| 1075 | if (!localApi) { |
| 1076 | writeSystemMessage( |
| 1077 | latestTerminal, |
| 1078 | m(msg("Opening links is unavailable in this browser.")), |
| 1079 | ); |
| 1080 | return; |
| 1081 | } |
| 1082 | const fallbackToBrowser = () => { |
| 1083 | void localApi.shell.openExternal(text).catch((error: unknown) => { |
| 1084 | writeSystemMessage( |
| 1085 | latestTerminal, |
| 1086 | thrownErrorMessage(error, m) ?? m(msg("Unable to open link")), |
| 1087 | ); |
| 1088 | }); |
| 1089 | }; |
| 1090 | if (!readEnvironmentScope(environmentId, AuthPreviewOperateScope)) { |
| 1091 | fallbackToBrowser(); |
| 1092 | return; |
| 1093 | } |
| 1094 | void openLinkInPreview(text, event.metaKey || event.ctrlKey, fallbackToBrowser).catch( |
| 1095 | (error: unknown) => { |
| 1096 | toastManager.add( |
| 1097 | stackedThreadToast({ |
| 1098 | type: "error", |
| 1099 | title: m(msg("Unable to open link")), |
| 1100 | description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")), |
| 1101 | }), |
| 1102 | ); |
| 1103 | }, |
| 1104 | ); |
| 1105 | return; |
| 1106 | } |
| 1107 | const target = resolveTerminalLinkTarget(text, cwd, readHostname()); |
| 1108 | void (async () => { |
| 1109 | const result = await openTerminalPath(target); |
| 1110 | if (result._tag === "Success" || isAtomCommandInterrupted(result)) { |
| 1111 | return; |
| 1112 | } |
| 1113 | const error = squashAtomCommandFailure(result); |
| 1114 | writeSystemMessage( |
| 1115 | latestTerminal, |
| 1116 | thrownErrorMessage(error, m) ?? m(msg("Unable to open path")), |
| 1117 | ); |
| 1118 | })(); |
| 1119 | } |
| 1120 | |
| 1121 | function handleData(data: string): void { |
| 1122 | void sendTerminalInput(data, m(msg("Terminal write failed"))); |
| 1123 | } |
| 1124 | |
| 1125 | const themeObserver = new MutationObserver(() => { |
| 1126 | const activeTerminal = terminalRef.current; |
| 1127 | if (!activeTerminal) return; |
| 1128 | activeTerminal.setTheme(terminalThemeFromApp(containerRef.current)); |
| 1129 | }); |
| 1130 | themeObserver.observe(document.documentElement, { |
| 1131 | attributes: true, |
| 1132 | attributeFilter: ["class", "style"], |
| 1133 | }); |
| 1134 | setupCleanups.push(() => themeObserver.disconnect()); |
| 1135 | |
| 1136 | const fitTimer = window.setTimeout(() => { |
| 1137 | const activeTerminal = terminalRef.current; |
| 1138 | if (!activeTerminal) return; |
| 1139 | const wasAtBottom = activeTerminal.isAtBottom(); |
| 1140 | activeTerminal.fit(); |
| 1141 | if (wasAtBottom) { |
| 1142 | activeTerminal.scrollToBottom(); |
| 1143 | } |
| 1144 | }, 30); |
| 1145 | setupCleanups.push(() => window.clearTimeout(fitTimer)); |
| 1146 | |
| 1147 | const cleanups = setupCleanups; |
| 1148 | setupCleanups = []; |
| 1149 | setupTerminal = null; |
| 1150 | return () => { |
| 1151 | for (const cleanup of cleanups.toReversed()) cleanup(); |
| 1152 | if (terminalRef.current === terminal) terminalRef.current = null; |
| 1153 | terminal.dispose(); |
| 1154 | }; |
| 1155 | }; |
| 1156 | |
| 1157 | void setup() |
| 1158 | .then((nextTeardown) => { |
| 1159 | if (cancelled) { |
| 1160 | nextTeardown?.(); |
| 1161 | return; |
| 1162 | } |
| 1163 | teardown = nextTeardown; |
| 1164 | }) |
| 1165 | .catch((error: unknown) => { |
| 1166 | for (const cleanup of setupCleanups.toReversed()) cleanup(); |
| 1167 | setupCleanups = []; |
| 1168 | if (terminalRef.current === setupTerminal) terminalRef.current = null; |
| 1169 | setupTerminal?.dispose(); |
| 1170 | setupTerminal = null; |
| 1171 | if (cancelled) return; |
| 1172 | const message = |
| 1173 | thrownErrorMessage(error, m) ?? m(msg("Unable to initialize libghostty-vt")); |
| 1174 | mount.textContent = m( |
| 1175 | msg("{message}. Close and reopen the terminal to retry.", { message }), |
| 1176 | ); |
| 1177 | }); |
| 1178 | |
| 1179 | return () => { |
| 1180 | cancelled = true; |
| 1181 | const hadFocus = mount.contains(document.activeElement); |
| 1182 | teardown?.(); |
| 1183 | if (hasTerminalWriteAccess() && hadFocus && mount.isConnected) { |
| 1184 | mount.focus({ preventScroll: true }); |
| 1185 | } |
| 1186 | }; |
| 1187 | }, [cwd, environmentId, terminalId, terminalSessionAtom, threadId]); |
| 1188 | |
| 1189 | const attachContainer = (mount: HTMLDivElement) => { |
| 1190 | containerRef.current = mount; |
| 1191 | const focus = () => |
| 1192 | focusTerminalViewport({ |
| 1193 | mount, |
| 1194 | surface: terminalRef.current, |
| 1195 | canOperate: readEnvironmentScope(environmentId, AuthTerminalOperateScope), |
| 1196 | visible: visibleRef.current, |
| 1197 | }); |
| 1198 | // Once per viewport: a re-attached ref (a fresh callback identity) must not |
| 1199 | // pull focus back on every render of a chatty terminal. As a request, it |
| 1200 | // waits for the grant or for the viewport to show when it cannot focus yet. |
| 1201 | if (autoFocus && !autoFocusedRef.current) { |
| 1202 | autoFocusedRef.current = true; |
| 1203 | focusTerminal(threadRef, terminalId); |
| 1204 | } |
| 1205 | const unregister = registerTerminalFocusTarget({ |
| 1206 | threadRef, |
| 1207 | terminalId, |
| 1208 | element: mount, |
| 1209 | focus, |
| 1210 | }); |
| 1211 | return () => { |
| 1212 | unregister(); |
| 1213 | containerRef.current = null; |
| 1214 | }; |
| 1215 | }; |
| 1216 | return ( |
| 1217 | <div |
| 1218 | ref={attachContainer} |
| 1219 | tabIndex={-1} |
| 1220 | className="relative h-full w-full overflow-hidden bg-(--terminal-background)" |
| 1221 | /> |
| 1222 | ); |
| 1223 | } |
| 1224 | |
| 1225 | interface ThreadTerminalDrawerProps { |
| 1226 | mode?: "drawer" | "panel"; |
| 1227 | threadRef: ScopedThreadRef; |
| 1228 | threadId: ThreadId; |
| 1229 | cwd: string; |
| 1230 | worktreePath?: string | null; |
| 1231 | runtimeEnv?: Record<string, string>; |
| 1232 | visible?: boolean; |
| 1233 | height: number; |
| 1234 | /** Space the chat column keeps for the composer overlay; only read in drawer mode. */ |
| 1235 | composerHeight?: number; |
| 1236 | terminalIds: string[]; |
| 1237 | activeTerminalId: string; |
| 1238 | terminalGroups: ThreadTerminalGroup[]; |
| 1239 | activeTerminalGroupId: string; |
| 1240 | onSplitTerminal: () => void; |
| 1241 | onSplitTerminalVertical: () => void; |
| 1242 | onNewTerminal: () => void; |
| 1243 | splitShortcutLabel?: string | undefined; |
| 1244 | splitVerticalShortcutLabel?: string | undefined; |
| 1245 | newShortcutLabel?: string | undefined; |
| 1246 | closeShortcutLabel?: string | undefined; |
| 1247 | onActiveTerminalChange: (terminalId: string) => void; |
| 1248 | onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; |
| 1249 | onHeightChange: (height: number) => void; |
| 1250 | onAddTerminalContext: (selection: TerminalContextSelection) => void; |
| 1251 | keybindings: ResolvedKeybindingsConfig; |
| 1252 | terminalLabelsById?: ReadonlyMap<string, string>; |
| 1253 | terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>; |
| 1254 | } |
| 1255 | |
| 1256 | interface TerminalActionButtonProps { |
| 1257 | label: string; |
| 1258 | className: string; |
| 1259 | onClick: () => void; |
| 1260 | children: ReactNode; |
| 1261 | disabled?: boolean; |
| 1262 | } |
| 1263 | |
| 1264 | function TerminalActionButton({ |
| 1265 | label, |
| 1266 | className, |
| 1267 | onClick, |
| 1268 | children, |
| 1269 | disabled, |
| 1270 | }: TerminalActionButtonProps) { |
| 1271 | return ( |
| 1272 | <Popover> |
| 1273 | <PopoverTrigger |
| 1274 | openOnHover |
| 1275 | render={ |
| 1276 | <button |
| 1277 | type="button" |
| 1278 | className={cn(className, disabled && "opacity-64 cursor-not-allowed")} |
| 1279 | onClick={disabled ? undefined : onClick} |
| 1280 | aria-label={label} |
| 1281 | aria-disabled={disabled} |
| 1282 | /> |
| 1283 | } |
| 1284 | > |
| 1285 | {children} |
| 1286 | </PopoverTrigger> |
| 1287 | <PopoverPopup |
| 1288 | tooltipStyle |
| 1289 | side="bottom" |
| 1290 | sideOffset={6} |
| 1291 | align="center" |
| 1292 | className="pointer-events-none select-none" |
| 1293 | > |
| 1294 | {label} |
| 1295 | </PopoverPopup> |
| 1296 | </Popover> |
| 1297 | ); |
| 1298 | } |
| 1299 | |
| 1300 | function TerminalSplitPanes({ |
| 1301 | terminalIds, |
| 1302 | splitDirection, |
| 1303 | activeTerminalId, |
| 1304 | terminalLabelById, |
| 1305 | resolveLaunchLocation, |
| 1306 | onActiveTerminalChange, |
| 1307 | onCloseTerminal, |
| 1308 | advancedTypography, |
| 1309 | threadRef, |
| 1310 | threadId, |
| 1311 | onAddTerminalContext, |
| 1312 | visible, |
| 1313 | keybindings, |
| 1314 | }: { |
| 1315 | terminalIds: readonly string[]; |
| 1316 | splitDirection: "horizontal" | "vertical"; |
| 1317 | activeTerminalId: string; |
| 1318 | terminalLabelById: ReadonlyMap<string, string>; |
| 1319 | resolveLaunchLocation: (terminalId: string) => TerminalLaunchLocation; |
| 1320 | onActiveTerminalChange: (terminalId: string) => void; |
| 1321 | onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void; |
| 1322 | advancedTypography: boolean; |
| 1323 | threadRef: ScopedThreadRef; |
| 1324 | threadId: ThreadId; |
| 1325 | onAddTerminalContext: (selection: TerminalContextSelection) => void; |
| 1326 | visible: boolean; |
| 1327 | keybindings: ResolvedKeybindingsConfig; |
| 1328 | }) { |
| 1329 | const gt = useGT(); |
| 1330 | return ( |
| 1331 | <div |
| 1332 | className="grid h-full w-full min-w-0 gap-0 overflow-hidden" |
| 1333 | style={ |
| 1334 | splitDirection === "vertical" |
| 1335 | ? { |
| 1336 | gridTemplateRows: `repeat(${terminalIds.length}, minmax(0, 1fr))`, |
| 1337 | } |
| 1338 | : { |
| 1339 | gridTemplateColumns: `repeat(${terminalIds.length}, minmax(0, 1fr))`, |
| 1340 | } |
| 1341 | } |
| 1342 | > |
| 1343 | {terminalIds.map((terminalId) => { |
| 1344 | const terminalLaunchLocation = resolveLaunchLocation(terminalId); |
| 1345 | return ( |
| 1346 | <div |
| 1347 | key={terminalId} |
| 1348 | className={`min-h-0 min-w-0 ${ |
| 1349 | splitDirection === "vertical" |
| 1350 | ? "border-t first:border-t-0" |
| 1351 | : "border-l first:border-l-0" |
| 1352 | } ${terminalId === activeTerminalId ? "border-border" : "border-border/70"}`} |
| 1353 | onPointerDown={() => { |
| 1354 | if (terminalId !== activeTerminalId) { |
| 1355 | onActiveTerminalChange(terminalId); |
| 1356 | } |
| 1357 | }} |
| 1358 | > |
| 1359 | <div className="h-full"> |
| 1360 | <TerminalViewport |
| 1361 | advancedTypography={advancedTypography} |
| 1362 | threadRef={threadRef} |
| 1363 | threadId={threadId} |
| 1364 | terminalId={terminalId} |
| 1365 | terminalLabel={terminalLabelById.get(terminalId) ?? gt("Terminal")} |
| 1366 | cwd={terminalLaunchLocation.cwd} |
| 1367 | {...(terminalLaunchLocation.worktreePath !== undefined |
| 1368 | ? { worktreePath: terminalLaunchLocation.worktreePath } |
| 1369 | : {})} |
| 1370 | {...(terminalLaunchLocation.runtimeEnv |
| 1371 | ? { runtimeEnv: terminalLaunchLocation.runtimeEnv } |
| 1372 | : {})} |
| 1373 | onSessionExited={() => onCloseTerminal(terminalId, threadRef)} |
| 1374 | onAddTerminalContext={onAddTerminalContext} |
| 1375 | visible={visible} |
| 1376 | keybindings={keybindings} |
| 1377 | /> |
| 1378 | </div> |
| 1379 | </div> |
| 1380 | ); |
| 1381 | })} |
| 1382 | </div> |
| 1383 | ); |
| 1384 | } |
| 1385 | |
| 1386 | function TerminalSidebarGroup({ |
| 1387 | terminalGroup, |
| 1388 | activeTerminalId, |
| 1389 | showHeader, |
| 1390 | terminalLabelById, |
| 1391 | closeShortcutLabel, |
| 1392 | canOperateTerminal, |
| 1393 | onActiveTerminalChange, |
| 1394 | onCloseTerminal, |
| 1395 | }: { |
| 1396 | terminalGroup: ThreadTerminalGroup; |
| 1397 | activeTerminalId: string; |
| 1398 | showHeader: boolean; |
| 1399 | terminalLabelById: ReadonlyMap<string, string>; |
| 1400 | closeShortcutLabel: string | undefined; |
| 1401 | canOperateTerminal: boolean; |
| 1402 | onActiveTerminalChange: (terminalId: string) => void; |
| 1403 | onCloseTerminal: (terminalId: string) => void; |
| 1404 | }) { |
| 1405 | const gt = useGT(); |
| 1406 | const isGroupActive = terminalGroup.terminalIds.includes(activeTerminalId); |
| 1407 | const groupActiveTerminalId = isGroupActive |
| 1408 | ? activeTerminalId |
| 1409 | : (terminalGroup.terminalIds[0] ?? activeTerminalId); |
| 1410 | const terminalCount = terminalGroup.terminalIds.length; |
| 1411 | const isSplitGroup = terminalCount > 1; |
| 1412 | const groupLabel = !isSplitGroup |
| 1413 | ? gt("Single", { $context: "terminal group with one terminal" }) |
| 1414 | : terminalGroup.splitDirection === "vertical" |
| 1415 | ? gt("Stacked", { $context: "terminals split vertically" }) |
| 1416 | : gt("Side by side", { $context: "terminals split horizontally" }); |
| 1417 | const GroupIcon = !isSplitGroup |
| 1418 | ? Square |
| 1419 | : terminalGroup.splitDirection === "vertical" |
| 1420 | ? SquareSplitVertical |
| 1421 | : SquareSplitHorizontal; |
| 1422 | |
| 1423 | return ( |
| 1424 | <div className="pb-0.5"> |
| 1425 | {showHeader && ( |
| 1426 | <button |
| 1427 | type="button" |
| 1428 | className={`flex h-[22px] w-full cursor-pointer items-center gap-1 rounded px-1.5 text-2xs ${ |
| 1429 | isGroupActive |
| 1430 | ? "bg-accent/50 text-foreground" |
| 1431 | : "text-muted-foreground hover:bg-accent/40 hover:text-foreground" |
| 1432 | }`} |
| 1433 | onClick={() => onActiveTerminalChange(groupActiveTerminalId)} |
| 1434 | > |
| 1435 | <GroupIcon className="size-3 shrink-0" /> |
| 1436 | <span className="min-w-0 flex-1 truncate text-left">{groupLabel}</span> |
| 1437 | <span className="text-muted-foreground/70 text-3xs tabular-nums">{terminalCount}</span> |
| 1438 | </button> |
| 1439 | )} |
| 1440 | |
| 1441 | <div className="flex flex-col gap-0.5"> |
| 1442 | {terminalGroup.terminalIds.map((terminalId) => { |
| 1443 | const isActive = terminalId === activeTerminalId; |
| 1444 | const terminalLabel = terminalLabelById.get(terminalId) ?? gt("Terminal"); |
| 1445 | const closeTerminalLabel = |
| 1446 | isActive && closeShortcutLabel |
| 1447 | ? gt("Close {terminal} ({shortcut})", { |
| 1448 | terminal: terminalLabel, |
| 1449 | shortcut: closeShortcutLabel, |
| 1450 | }) |
| 1451 | : gt("Close {terminal}", { terminal: terminalLabel }); |
| 1452 | return ( |
| 1453 | <div |
| 1454 | key={terminalId} |
| 1455 | className={cn( |
| 1456 | "group/tab flex h-6 w-full items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs", |
| 1457 | isActive |
| 1458 | ? "bg-accent text-foreground" |
| 1459 | : "text-muted-foreground hover:bg-accent/60 hover:text-foreground", |
| 1460 | )} |
| 1461 | > |
| 1462 | {canOperateTerminal ? ( |
| 1463 | <PanelTabCloseButton |
| 1464 | label={closeTerminalLabel} |
| 1465 | onClick={() => onCloseTerminal(terminalId)} |
| 1466 | tooltip={closeTerminalLabel} |
| 1467 | > |
| 1468 | <TerminalSquare className="size-3 shrink-0" /> |
| 1469 | </PanelTabCloseButton> |
| 1470 | ) : ( |
| 1471 | <TerminalSquare className="size-3 shrink-0" /> |
| 1472 | )} |
| 1473 | <button |
| 1474 | type="button" |
| 1475 | className="flex min-w-0 flex-1 cursor-pointer items-center gap-1 text-left" |
| 1476 | onClick={() => onActiveTerminalChange(terminalId)} |
| 1477 | > |
| 1478 | <span className="truncate">{terminalLabel}</span> |
| 1479 | </button> |
| 1480 | </div> |
| 1481 | ); |
| 1482 | })} |
| 1483 | </div> |
| 1484 | </div> |
| 1485 | ); |
| 1486 | } |
| 1487 | |
| 1488 | export default function ThreadTerminalDrawer({ |
| 1489 | mode = "drawer", |
| 1490 | threadRef, |
| 1491 | threadId, |
| 1492 | cwd, |
| 1493 | worktreePath, |
| 1494 | runtimeEnv, |
| 1495 | visible = true, |
| 1496 | height, |
| 1497 | composerHeight = 0, |
| 1498 | terminalIds, |
| 1499 | activeTerminalId, |
| 1500 | terminalGroups, |
| 1501 | activeTerminalGroupId, |
| 1502 | onSplitTerminal, |
| 1503 | onSplitTerminalVertical, |
| 1504 | onNewTerminal, |
| 1505 | splitShortcutLabel, |
| 1506 | splitVerticalShortcutLabel, |
| 1507 | newShortcutLabel, |
| 1508 | closeShortcutLabel, |
| 1509 | onActiveTerminalChange, |
| 1510 | onCloseTerminal, |
| 1511 | onHeightChange, |
| 1512 | onAddTerminalContext, |
| 1513 | keybindings, |
| 1514 | terminalLabelsById, |
| 1515 | terminalLaunchLocationsById, |
| 1516 | }: ThreadTerminalDrawerProps) { |
| 1517 | const gt = useGT(); |
| 1518 | const messages = useMessages(); |
| 1519 | const canOperateTerminal = useEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope); |
| 1520 | const terminalArea = workspaceAreaProps("terminal", 5, gt("Terminal")); |
| 1521 | const isPanel = mode === "panel"; |
| 1522 | const [advancedTypography] = useLocalStorage( |
| 1523 | TYPOGRAPHY_ADVANCED_STORAGE_KEY, |
| 1524 | false, |
| 1525 | Schema.Boolean, |
| 1526 | ); |
| 1527 | const drawerRef = useRef<HTMLElement | null>(null); |
| 1528 | const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null)); |
| 1529 | const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight }); |
| 1530 | const drawerHeight = clampDrawerHeight(height, maxDrawerHeight); |
| 1531 | // A drag only writes the drawer's style; the store hears the height once, at |
| 1532 | // pointerup. The custom property outranks the rendered height while it is set. |
| 1533 | const resizeStateRef = useRef<{ |
| 1534 | pointerId: number; |
| 1535 | startY: number; |
| 1536 | startHeight: number; |
| 1537 | height: number; |
| 1538 | drawer: HTMLElement | null; |
| 1539 | } | null>(null); |
| 1540 | |
| 1541 | const normalizedTerminalIds = (() => { |
| 1542 | const normalizedIds: string[] = []; |
| 1543 | const seen = new Set<string>(); |
| 1544 | for (const id of terminalIds) { |
| 1545 | const trimmedId = id.trim(); |
| 1546 | if (trimmedId.length === 0 || seen.has(trimmedId)) continue; |
| 1547 | seen.add(trimmedId); |
| 1548 | normalizedIds.push(trimmedId); |
| 1549 | } |
| 1550 | return normalizedIds; |
| 1551 | })(); |
| 1552 | const resolvedTerminalGroups = (() => { |
| 1553 | if (normalizedTerminalIds.length === 0) { |
| 1554 | return []; |
| 1555 | } |
| 1556 | const validTerminalIdSet = new Set(normalizedTerminalIds); |
| 1557 | const assignedTerminalIds = new Set<string>(); |
| 1558 | const usedGroupIds = new Set<string>(); |
| 1559 | const nextGroups: ThreadTerminalGroup[] = []; |
| 1560 | |
| 1561 | const assignUniqueGroupId = (groupId: string): string => { |
| 1562 | if (!usedGroupIds.has(groupId)) { |
| 1563 | usedGroupIds.add(groupId); |
| 1564 | return groupId; |
| 1565 | } |
| 1566 | let suffix = 2; |
| 1567 | while (usedGroupIds.has(`${groupId}-${suffix}`)) { |
| 1568 | suffix += 1; |
| 1569 | } |
| 1570 | const uniqueGroupId = `${groupId}-${suffix}`; |
| 1571 | usedGroupIds.add(uniqueGroupId); |
| 1572 | return uniqueGroupId; |
| 1573 | }; |
| 1574 | |
| 1575 | for (const terminalGroup of terminalGroups) { |
| 1576 | const nextTerminalIds: string[] = []; |
| 1577 | const seenGroupTerminalIds = new Set<string>(); |
| 1578 | for (const id of terminalGroup.terminalIds) { |
| 1579 | const terminalId = id.trim(); |
| 1580 | if (terminalId.length === 0) continue; |
| 1581 | if (seenGroupTerminalIds.has(terminalId)) continue; |
| 1582 | seenGroupTerminalIds.add(terminalId); |
| 1583 | if (!validTerminalIdSet.has(terminalId)) continue; |
| 1584 | if (assignedTerminalIds.has(terminalId)) continue; |
| 1585 | nextTerminalIds.push(terminalId); |
| 1586 | } |
| 1587 | if (nextTerminalIds.length === 0) continue; |
| 1588 | |
| 1589 | for (const terminalId of nextTerminalIds) { |
| 1590 | assignedTerminalIds.add(terminalId); |
| 1591 | } |
| 1592 | |
| 1593 | const baseGroupId = |
| 1594 | terminalGroup.id.trim().length > 0 |
| 1595 | ? terminalGroup.id.trim() |
| 1596 | : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`; |
| 1597 | nextGroups.push({ |
| 1598 | id: assignUniqueGroupId(baseGroupId), |
| 1599 | terminalIds: nextTerminalIds, |
| 1600 | ...(terminalGroup.splitDirection === "vertical" |
| 1601 | ? { splitDirection: "vertical" as const } |
| 1602 | : {}), |
| 1603 | }); |
| 1604 | } |
| 1605 | |
| 1606 | for (const terminalId of normalizedTerminalIds) { |
| 1607 | if (assignedTerminalIds.has(terminalId)) continue; |
| 1608 | nextGroups.push({ |
| 1609 | id: assignUniqueGroupId(`group-${terminalId}`), |
| 1610 | terminalIds: [terminalId], |
| 1611 | }); |
| 1612 | } |
| 1613 | |
| 1614 | const terminalOrderIndex = new Map( |
| 1615 | normalizedTerminalIds.map((id, index) => [id, index] as const), |
| 1616 | ); |
| 1617 | nextGroups.sort((left, right) => { |
| 1618 | const rank = (ids: readonly string[]) => |
| 1619 | Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY)); |
| 1620 | return rank(left.terminalIds) - rank(right.terminalIds); |
| 1621 | }); |
| 1622 | |
| 1623 | return nextGroups; |
| 1624 | })(); |
| 1625 | const groupIndexByTerminalId = (() => { |
| 1626 | const next = new Map<string, number>(); |
| 1627 | for (const [index, terminalGroup] of resolvedTerminalGroups.entries()) { |
| 1628 | for (const terminalId of terminalGroup.terminalIds) next.set(terminalId, index); |
| 1629 | } |
| 1630 | return next; |
| 1631 | })(); |
| 1632 | const terminalLabelById = (() => { |
| 1633 | const next = new Map<string, string>(); |
| 1634 | for (const terminalId of normalizedTerminalIds) { |
| 1635 | next.set( |
| 1636 | terminalId, |
| 1637 | terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId, messages), |
| 1638 | ); |
| 1639 | } |
| 1640 | return next; |
| 1641 | })(); |
| 1642 | |
| 1643 | const resolvedActiveTerminalId = |
| 1644 | normalizedTerminalIds.length === 0 |
| 1645 | ? "" |
| 1646 | : normalizedTerminalIds.includes(activeTerminalId) |
| 1647 | ? activeTerminalId |
| 1648 | : (normalizedTerminalIds[0] ?? ""); |
| 1649 | |
| 1650 | const groupIndexById = resolvedTerminalGroups.findIndex( |
| 1651 | (terminalGroup) => terminalGroup.id === activeTerminalGroupId, |
| 1652 | ); |
| 1653 | const resolvedActiveGroupIndex = |
| 1654 | groupIndexById >= 0 |
| 1655 | ? groupIndexById |
| 1656 | : (groupIndexByTerminalId.get(resolvedActiveTerminalId) ?? 0); |
| 1657 | |
| 1658 | const visibleTerminalIds = |
| 1659 | resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? |
| 1660 | (normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []); |
| 1661 | const splitDirection = |
| 1662 | resolvedTerminalGroups[resolvedActiveGroupIndex]?.splitDirection ?? "horizontal"; |
| 1663 | const hasTerminalSidebar = normalizedTerminalIds.length > 1; |
| 1664 | const showGroupHeaders = |
| 1665 | resolvedTerminalGroups.length > 1 || |
| 1666 | resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1); |
| 1667 | const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP; |
| 1668 | const resolveTerminalLaunchLocation = (terminalId: string): TerminalLaunchLocation => |
| 1669 | terminalLaunchLocationsById?.get(terminalId) ?? { |
| 1670 | cwd, |
| 1671 | ...(worktreePath !== undefined ? { worktreePath } : {}), |
| 1672 | ...(runtimeEnv ? { runtimeEnv } : {}), |
| 1673 | }; |
| 1674 | const splitTerminalActionLabel = hasReachedSplitLimit |
| 1675 | ? gt("Split Terminal Horizontally (max {max} per group)", { max: MAX_TERMINALS_PER_GROUP }) |
| 1676 | : splitShortcutLabel |
| 1677 | ? gt("Split Terminal Horizontally ({shortcut})", { shortcut: splitShortcutLabel }) |
| 1678 | : gt("Split Terminal Horizontally"); |
| 1679 | const splitTerminalVerticalActionLabel = hasReachedSplitLimit |
| 1680 | ? gt("Split Terminal Vertically (max {max} per group)", { max: MAX_TERMINALS_PER_GROUP }) |
| 1681 | : splitVerticalShortcutLabel |
| 1682 | ? gt("Split Terminal Vertically ({shortcut})", { shortcut: splitVerticalShortcutLabel }) |
| 1683 | : gt("Split Terminal Vertically"); |
| 1684 | const newTerminalActionLabel = newShortcutLabel |
| 1685 | ? gt("New Terminal ({shortcut})", { shortcut: newShortcutLabel }) |
| 1686 | : gt("New Terminal"); |
| 1687 | const closeTerminalActionLabel = closeShortcutLabel |
| 1688 | ? gt("Close Terminal ({shortcut})", { shortcut: closeShortcutLabel }) |
| 1689 | : gt("Close Terminal"); |
| 1690 | const onSplitTerminalAction = () => { |
| 1691 | if (!canOperateTerminal || hasReachedSplitLimit) return; |
| 1692 | onSplitTerminal(); |
| 1693 | }; |
| 1694 | const onSplitTerminalVerticalAction = () => { |
| 1695 | if (!canOperateTerminal || hasReachedSplitLimit) return; |
| 1696 | onSplitTerminalVertical(); |
| 1697 | }; |
| 1698 | const onNewTerminalAction = () => { |
| 1699 | if (!canOperateTerminal) return; |
| 1700 | onNewTerminal(); |
| 1701 | }; |
| 1702 | const confirmCloseTerminal = (terminalId: string) => { |
| 1703 | if (!canOperateTerminal) return; |
| 1704 | const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId, m); |
| 1705 | void confirmTerminalClose([label]).then((confirmed) => { |
| 1706 | if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) { |
| 1707 | onCloseTerminal(terminalId, threadRef); |
| 1708 | } |
| 1709 | }); |
| 1710 | }; |
| 1711 | |
| 1712 | const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1713 | if (event.button !== 0) return; |
| 1714 | event.preventDefault(); |
| 1715 | event.currentTarget.setPointerCapture(event.pointerId); |
| 1716 | resizeStateRef.current = { |
| 1717 | pointerId: event.pointerId, |
| 1718 | startY: event.clientY, |
| 1719 | startHeight: drawerHeight, |
| 1720 | height: drawerHeight, |
| 1721 | drawer: event.currentTarget.parentElement, |
| 1722 | }; |
| 1723 | }; |
| 1724 | |
| 1725 | const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1726 | const resizeState = resizeStateRef.current; |
| 1727 | if (!resizeState || resizeState.pointerId !== event.pointerId) return; |
| 1728 | event.preventDefault(); |
| 1729 | const clampedHeight = clampDrawerHeight( |
| 1730 | resizeState.startHeight + (resizeState.startY - event.clientY), |
| 1731 | maxDrawerHeight, |
| 1732 | ); |
| 1733 | if (clampedHeight === resizeState.height) { |
| 1734 | return; |
| 1735 | } |
| 1736 | resizeState.height = clampedHeight; |
| 1737 | resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`); |
| 1738 | }; |
| 1739 | |
| 1740 | const handleResizePointerEnd = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1741 | const resizeState = resizeStateRef.current; |
| 1742 | if (!resizeState || resizeState.pointerId !== event.pointerId) return; |
| 1743 | resizeStateRef.current = null; |
| 1744 | if (event.currentTarget.hasPointerCapture(event.pointerId)) { |
| 1745 | event.currentTarget.releasePointerCapture(event.pointerId); |
| 1746 | } |
| 1747 | resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY); |
| 1748 | // A drag that ends where it started keeps the stored preference, which may |
| 1749 | // be taller than the capped height the drag started from. |
| 1750 | if (resizeState.height === resizeState.startHeight || resizeState.height === height) return; |
| 1751 | onHeightChange(resizeState.height); |
| 1752 | }; |
| 1753 | |
| 1754 | const drawerLayoutRef = useRef(drawerLayout); |
| 1755 | const updateDrawerLayout = useEffectEvent( |
| 1756 | (column: HTMLElement | null, source: "window" | "column") => { |
| 1757 | const layout = readDrawerLayout(column); |
| 1758 | const previous = drawerLayoutRef.current; |
| 1759 | const heightBudgetChanged = |
| 1760 | layout.viewportHeight !== previous.viewportHeight || |
| 1761 | layout.chatColumnHeight !== previous.chatColumnHeight || |
| 1762 | layout.headerHeight !== previous.headerHeight; |
| 1763 | // The column also reports width-only changes, such as every frame of a |
| 1764 | // right panel drag; the surface refits itself for those. |
| 1765 | if (!heightBudgetChanged && source === "column") return; |
| 1766 | drawerLayoutRef.current = layout; |
| 1767 | const resizeState = resizeStateRef.current; |
| 1768 | if (resizeState) { |
| 1769 | const liveHeight = clampDrawerHeight( |
| 1770 | resizeState.height, |
| 1771 | resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }), |
| 1772 | ); |
| 1773 | if (liveHeight !== resizeState.height) { |
| 1774 | resizeState.height = liveHeight; |
| 1775 | resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`); |
| 1776 | } |
| 1777 | } |
| 1778 | if (heightBudgetChanged) setDrawerLayout(layout); |
| 1779 | }, |
| 1780 | ); |
| 1781 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the drawer before visible paint and observes window and chat column resizes while visible |
| 1782 | useLayoutEffect(() => { |
| 1783 | if (!visible) { |
| 1784 | return; |
| 1785 | } |
| 1786 | // The column and window may have resized while the drawer was hidden and |
| 1787 | // not listening, so measure before the first visible paint. |
| 1788 | const column = isPanel ? null : chatColumnOf(drawerRef.current); |
| 1789 | const onWindowResize = () => updateDrawerLayout(column, "window"); |
| 1790 | onWindowResize(); |
| 1791 | const header = column?.querySelector<HTMLElement>("[data-chat-header]"); |
| 1792 | const stopObserving = column |
| 1793 | ? observeResize(header ? [column, header] : column, () => |
| 1794 | updateDrawerLayout(column, "column"), |
| 1795 | ) |
| 1796 | : undefined; |
| 1797 | window.addEventListener("resize", onWindowResize); |
| 1798 | return () => { |
| 1799 | stopObserving?.(); |
| 1800 | window.removeEventListener("resize", onWindowResize); |
| 1801 | }; |
| 1802 | }, [isPanel, visible]); |
| 1803 | |
| 1804 | const resizeHandle = isPanel ? null : ( |
| 1805 | <div |
| 1806 | className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize touch-none any-pointer-coarse:h-4" |
| 1807 | onPointerDown={handleResizePointerDown} |
| 1808 | onPointerMove={handleResizePointerMove} |
| 1809 | onPointerUp={handleResizePointerEnd} |
| 1810 | onPointerCancel={handleResizePointerEnd} |
| 1811 | onLostPointerCapture={handleResizePointerEnd} |
| 1812 | /> |
| 1813 | ); |
| 1814 | |
| 1815 | if (normalizedTerminalIds.length === 0) { |
| 1816 | return ( |
| 1817 | <aside |
| 1818 | ref={drawerRef} |
| 1819 | {...(!isPanel && visible ? terminalArea : {})} |
| 1820 | data-thread-terminal-drawer |
| 1821 | data-terminal-owner={isPanel ? "right-panel" : "drawer"} |
| 1822 | className={cn( |
| 1823 | "relative flex min-w-0 flex-col overflow-hidden bg-background", |
| 1824 | isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80", |
| 1825 | )} |
| 1826 | style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }} |
| 1827 | > |
| 1828 | {resizeHandle} |
| 1829 | <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 px-4 py-6 text-center text-sm text-muted-foreground"> |
| 1830 | <p> |
| 1831 | <T>No terminal sessions for this thread yet.</T> |
| 1832 | </p> |
| 1833 | <Button |
| 1834 | size="xs" |
| 1835 | variant="outline" |
| 1836 | onClick={onNewTerminalAction} |
| 1837 | disabled={!canOperateTerminal} |
| 1838 | > |
| 1839 | {newTerminalActionLabel} |
| 1840 | </Button> |
| 1841 | </div> |
| 1842 | </aside> |
| 1843 | ); |
| 1844 | } |
| 1845 | |
| 1846 | return ( |
| 1847 | <aside |
| 1848 | ref={drawerRef} |
| 1849 | {...(!isPanel && visible ? terminalArea : {})} |
| 1850 | data-thread-terminal-drawer |
| 1851 | data-terminal-owner={isPanel ? "right-panel" : "drawer"} |
| 1852 | className={cn( |
| 1853 | "relative flex min-w-0 flex-col overflow-hidden bg-background", |
| 1854 | isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80", |
| 1855 | )} |
| 1856 | style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }} |
| 1857 | > |
| 1858 | {resizeHandle} |
| 1859 | |
| 1860 | {!hasTerminalSidebar && ( |
| 1861 | <div className="pointer-events-none absolute right-2 top-2 z-20"> |
| 1862 | <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background shadow-xs"> |
| 1863 | <TerminalActionButton |
| 1864 | disabled={!canOperateTerminal} |
| 1865 | className={`p-1 text-foreground/90 transition-colors ${ |
| 1866 | hasReachedSplitLimit |
| 1867 | ? "cursor-not-allowed opacity-64 hover:bg-transparent" |
| 1868 | : "hover:bg-accent" |
| 1869 | }`} |
| 1870 | onClick={onSplitTerminalAction} |
| 1871 | label={splitTerminalActionLabel} |
| 1872 | > |
| 1873 | <SquareSplitHorizontal className="size-3.25" /> |
| 1874 | </TerminalActionButton> |
| 1875 | <div className="h-4 w-px bg-border/80" /> |
| 1876 | <TerminalActionButton |
| 1877 | disabled={!canOperateTerminal} |
| 1878 | className={`p-1 text-foreground/90 transition-colors ${ |
| 1879 | hasReachedSplitLimit |
| 1880 | ? "cursor-not-allowed opacity-64 hover:bg-transparent" |
| 1881 | : "hover:bg-accent" |
| 1882 | }`} |
| 1883 | onClick={onSplitTerminalVerticalAction} |
| 1884 | label={splitTerminalVerticalActionLabel} |
| 1885 | > |
| 1886 | <SquareSplitVertical className="size-3.25" /> |
| 1887 | </TerminalActionButton> |
| 1888 | <div className="h-4 w-px bg-border/80" /> |
| 1889 | <TerminalActionButton |
| 1890 | disabled={!canOperateTerminal} |
| 1891 | className="p-1 text-foreground/90 transition-colors hover:bg-accent" |
| 1892 | onClick={onNewTerminalAction} |
| 1893 | label={newTerminalActionLabel} |
| 1894 | > |
| 1895 | <Plus className="size-3.25" /> |
| 1896 | </TerminalActionButton> |
| 1897 | <div className="h-4 w-px bg-border/80" /> |
| 1898 | <TerminalActionButton |
| 1899 | disabled={!canOperateTerminal} |
| 1900 | className="p-1 text-foreground/90 transition-colors hover:bg-accent" |
| 1901 | onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)} |
| 1902 | label={closeTerminalActionLabel} |
| 1903 | > |
| 1904 | <Trash2 className="size-3.25" /> |
| 1905 | </TerminalActionButton> |
| 1906 | </div> |
| 1907 | </div> |
| 1908 | )} |
| 1909 | |
| 1910 | <div className="min-h-0 w-full flex-1"> |
| 1911 | <div |
| 1912 | className={cn( |
| 1913 | "flex h-full min-h-0 bg-(--terminal-background)", |
| 1914 | hasTerminalSidebar && "gap-1.5", |
| 1915 | )} |
| 1916 | > |
| 1917 | <div className="min-w-0 flex-1"> |
| 1918 | <TerminalSplitPanes |
| 1919 | terminalIds={visibleTerminalIds} |
| 1920 | splitDirection={splitDirection} |
| 1921 | activeTerminalId={resolvedActiveTerminalId} |
| 1922 | terminalLabelById={terminalLabelById} |
| 1923 | resolveLaunchLocation={resolveTerminalLaunchLocation} |
| 1924 | onActiveTerminalChange={onActiveTerminalChange} |
| 1925 | onCloseTerminal={onCloseTerminal} |
| 1926 | advancedTypography={advancedTypography} |
| 1927 | threadRef={threadRef} |
| 1928 | threadId={threadId} |
| 1929 | onAddTerminalContext={onAddTerminalContext} |
| 1930 | visible={visible} |
| 1931 | keybindings={keybindings} |
| 1932 | /> |
| 1933 | </div> |
| 1934 | |
| 1935 | {hasTerminalSidebar && ( |
| 1936 | <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10"> |
| 1937 | <div className="flex h-[22px] items-stretch justify-end border-b border-border/70"> |
| 1938 | {/* Sits above the taller touch resize handle so its buttons keep their taps. */} |
| 1939 | <div className="inline-flex h-full items-stretch any-pointer-coarse:relative any-pointer-coarse:z-30"> |
| 1940 | <TerminalActionButton |
| 1941 | disabled={!canOperateTerminal} |
| 1942 | className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${ |
| 1943 | hasReachedSplitLimit |
| 1944 | ? "cursor-not-allowed opacity-64 hover:bg-transparent" |
| 1945 | : "hover:bg-accent/70" |
| 1946 | }`} |
| 1947 | onClick={onSplitTerminalAction} |
| 1948 | label={splitTerminalActionLabel} |
| 1949 | > |
| 1950 | <SquareSplitHorizontal className="size-3.25" /> |
| 1951 | </TerminalActionButton> |
| 1952 | <TerminalActionButton |
| 1953 | disabled={!canOperateTerminal} |
| 1954 | className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${ |
| 1955 | hasReachedSplitLimit |
| 1956 | ? "cursor-not-allowed opacity-64 hover:bg-transparent" |
| 1957 | : "hover:bg-accent/70" |
| 1958 | }`} |
| 1959 | onClick={onSplitTerminalVerticalAction} |
| 1960 | label={splitTerminalVerticalActionLabel} |
| 1961 | > |
| 1962 | <SquareSplitVertical className="size-3.25" /> |
| 1963 | </TerminalActionButton> |
| 1964 | <TerminalActionButton |
| 1965 | disabled={!canOperateTerminal} |
| 1966 | className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70" |
| 1967 | onClick={onNewTerminalAction} |
| 1968 | label={newTerminalActionLabel} |
| 1969 | > |
| 1970 | <Plus className="size-3.25" /> |
| 1971 | </TerminalActionButton> |
| 1972 | <TerminalActionButton |
| 1973 | disabled={!canOperateTerminal} |
| 1974 | className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70" |
| 1975 | onClick={() => confirmCloseTerminal(resolvedActiveTerminalId)} |
| 1976 | label={closeTerminalActionLabel} |
| 1977 | > |
| 1978 | <Trash2 className="size-3.25" /> |
| 1979 | </TerminalActionButton> |
| 1980 | </div> |
| 1981 | </div> |
| 1982 | |
| 1983 | <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1"> |
| 1984 | {resolvedTerminalGroups.map((terminalGroup) => ( |
| 1985 | <TerminalSidebarGroup |
| 1986 | key={terminalGroup.id} |
| 1987 | terminalGroup={terminalGroup} |
| 1988 | activeTerminalId={resolvedActiveTerminalId} |
| 1989 | showHeader={showGroupHeaders} |
| 1990 | terminalLabelById={terminalLabelById} |
| 1991 | closeShortcutLabel={closeShortcutLabel} |
| 1992 | canOperateTerminal={canOperateTerminal} |
| 1993 | onActiveTerminalChange={onActiveTerminalChange} |
| 1994 | onCloseTerminal={confirmCloseTerminal} |
| 1995 | /> |
| 1996 | ))} |
| 1997 | </div> |
| 1998 | </aside> |
| 1999 | )} |
| 2000 | </div> |
| 2001 | </div> |
| 2002 | </aside> |
| 2003 | ); |
| 2004 | } |