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

ThreadTerminalDrawer.tsx

1,404 lines49.6 KB

1import { FitAddon } from "@xterm/addon-fit";
2import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
3import {
4 type ResolvedKeybindingsConfig,
5 type ScopedThreadRef,
6 type TerminalAttachStreamEvent,
7 type TerminalSessionSnapshot,
8 type ThreadId,
9} from "@t3tools/contracts";
10import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
11import { Terminal, type ITheme } from "@xterm/xterm";
12import {
13 type PointerEvent as ReactPointerEvent,
14 type ReactNode,
15 useCallback,
16 useEffect,
17 useEffectEvent,
18 useMemo,
19 useRef,
20 useState,
21} from "react";
22import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
23import { type TerminalContextSelection } from "~/lib/terminalContext";
24import { openInPreferredEditor } from "../editorPreferences";
25import {
26 collectWrappedTerminalLinkLine,
27 extractTerminalLinks,
28 isTerminalLinkActivation,
29 resolvePathLinkTarget,
30 resolveWrappedTerminalLinkRange,
31 wrappedTerminalLinkRangeIntersectsBufferLine,
32} from "../terminal-links";
33import {
34 isDiffToggleShortcut,
35 isTerminalClearShortcut,
36 isTerminalCloseShortcut,
37 isTerminalNewShortcut,
38 isTerminalSplitShortcut,
39 isTerminalToggleShortcut,
40 terminalDeleteShortcutData,
41 terminalNavigationShortcutData,
42} from "../keybindings";
43import {
44 DEFAULT_THREAD_TERMINAL_HEIGHT,
45 MAX_TERMINALS_PER_GROUP,
46 type ThreadTerminalGroup,
47} from "../types";
48import { readEnvironmentApi } from "~/environmentApi";
49import { readLocalApi } from "~/localApi";
50import { attachTerminalSession } from "../terminalSessionState";
51​
52const MIN_DRAWER_HEIGHT = 180;
53const MAX_DRAWER_HEIGHT_RATIO = 0.75;
54const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
55​
56function maxDrawerHeight(): number {
57 if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
58 return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
60​
61function clampDrawerHeight(height: number): number {
62 const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
63 const maxHeight = maxDrawerHeight();
64 return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
66​
67function writeSystemMessage(terminal: Terminal, message: string): void {
68 terminal.write(`\r\n[terminal] ${message}\r\n`);
70​
71function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void {
72 terminal.write("\u001bc");
73 if (snapshot.history.length > 0) {
74 terminal.write(snapshot.history);
75 }
77​
78function fitTerminalSafely(fitAddon: FitAddon): boolean {
79 try {
80 fitAddon.fit();
81 return true;
82 } catch {
83 return false;
84 }
86​
87function runtimeEnvSignature(runtimeEnv: Record<string, string> | undefined): string {
88 if (!runtimeEnv) return "";
89 return JSON.stringify(
90 Object.entries(runtimeEnv)
91 .filter(([key, value]) => key.length > 0 && typeof value === "string")
92 .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
93 );
95​
96function normalizeComputedColor(value: string | null | undefined, fallback: string): string {
97 const normalizedValue = value?.trim().toLowerCase();
98 if (
99 !normalizedValue ||
100 normalizedValue === "transparent" ||
101 normalizedValue === "rgba(0, 0, 0, 0)" ||
102 normalizedValue === "rgba(0 0 0 / 0)"
103 ) {
104 return fallback;
105 }
106 return value ?? fallback;
108​
109function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme {
110 const isDark = document.documentElement.classList.contains("dark");
111 const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)";
112 const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)";
113 const drawerSurface =
114 mountElement?.closest(".thread-terminal-drawer") ??
115 document.querySelector(".thread-terminal-drawer") ??
116 document.body;
117 const drawerStyles = getComputedStyle(drawerSurface);
118 const bodyStyles = getComputedStyle(document.body);
119 const background = normalizeComputedColor(
120 drawerStyles.backgroundColor,
121 normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground),
122 );
123 const foreground = normalizeComputedColor(
124 drawerStyles.color,
125 normalizeComputedColor(bodyStyles.color, fallbackForeground),
126 );
127​
128 if (isDark) {
129 return {
130 background,
131 foreground,
132 cursor: "rgb(180, 203, 255)",
133 selectionBackground: "rgba(180, 203, 255, 0.25)",
134 scrollbarSliderBackground: "rgba(255, 255, 255, 0.1)",
135 scrollbarSliderHoverBackground: "rgba(255, 255, 255, 0.18)",
136 scrollbarSliderActiveBackground: "rgba(255, 255, 255, 0.22)",
137 black: "rgb(24, 30, 38)",
138 red: "rgb(255, 122, 142)",
139 green: "rgb(134, 231, 149)",
140 yellow: "rgb(244, 205, 114)",
141 blue: "rgb(137, 190, 255)",
142 magenta: "rgb(208, 176, 255)",
143 cyan: "rgb(124, 232, 237)",
144 white: "rgb(210, 218, 230)",
145 brightBlack: "rgb(110, 120, 136)",
146 brightRed: "rgb(255, 168, 180)",
147 brightGreen: "rgb(176, 245, 186)",
148 brightYellow: "rgb(255, 224, 149)",
149 brightBlue: "rgb(174, 210, 255)",
150 brightMagenta: "rgb(229, 203, 255)",
151 brightCyan: "rgb(167, 244, 247)",
152 brightWhite: "rgb(244, 247, 252)",
153 };
154 }
155​
156 return {
157 background,
158 foreground,
159 cursor: "rgb(38, 56, 78)",
160 selectionBackground: "rgba(37, 63, 99, 0.2)",
161 scrollbarSliderBackground: "rgba(0, 0, 0, 0.15)",
162 scrollbarSliderHoverBackground: "rgba(0, 0, 0, 0.25)",
163 scrollbarSliderActiveBackground: "rgba(0, 0, 0, 0.3)",
164 black: "rgb(44, 53, 66)",
165 red: "rgb(191, 70, 87)",
166 green: "rgb(60, 126, 86)",
167 yellow: "rgb(146, 112, 35)",
168 blue: "rgb(72, 102, 163)",
169 magenta: "rgb(132, 86, 149)",
170 cyan: "rgb(53, 127, 141)",
171 white: "rgb(210, 215, 223)",
172 brightBlack: "rgb(112, 123, 140)",
173 brightRed: "rgb(212, 95, 112)",
174 brightGreen: "rgb(85, 148, 111)",
175 brightYellow: "rgb(173, 133, 45)",
176 brightBlue: "rgb(91, 124, 194)",
177 brightMagenta: "rgb(153, 107, 172)",
178 brightCyan: "rgb(70, 149, 164)",
179 brightWhite: "rgb(236, 240, 246)",
180 };
182​
183function getTerminalSelectionRect(mountElement: HTMLElement): DOMRect | null {
184 const selection = window.getSelection();
185 if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
186 return null;
187 }
188​
189 const range = selection.getRangeAt(0);
190 const commonAncestor = range.commonAncestorContainer;
191 const selectionRoot =
192 commonAncestor instanceof Element ? commonAncestor : commonAncestor.parentElement;
193 if (!(selectionRoot instanceof Element) || !mountElement.contains(selectionRoot)) {
194 return null;
195 }
196​
197 const rects = Array.from(range.getClientRects()).filter(
198 (rect) => rect.width > 0 || rect.height > 0,
199 );
200 if (rects.length > 0) {
201 return rects[rects.length - 1] ?? null;
202 }
203​
204 const boundingRect = range.getBoundingClientRect();
205 return boundingRect.width > 0 || boundingRect.height > 0 ? boundingRect : null;
207​
208export function resolveTerminalSelectionActionPosition(options: {
209 bounds: { left: number; top: number; width: number; height: number };
210 selectionRect: { right: number; bottom: number } | null;
211 pointer: { x: number; y: number } | null;
212 viewport?: { width: number; height: number } | null;
213}): { x: number; y: number } {
214 const { bounds, selectionRect, pointer, viewport } = options;
215 const viewportWidth =
216 viewport?.width ??
217 (typeof window === "undefined" ? bounds.left + bounds.width + 8 : window.innerWidth);
218 const viewportHeight =
219 viewport?.height ??
220 (typeof window === "undefined" ? bounds.top + bounds.height + 8 : window.innerHeight);
221 const drawerLeft = Math.round(bounds.left);
222 const drawerTop = Math.round(bounds.top);
223 const drawerRight = Math.round(bounds.left + bounds.width);
224 const drawerBottom = Math.round(bounds.top + bounds.height);
225 const preferredX =
226 selectionRect !== null
227 ? Math.round(selectionRect.right)
228 : pointer === null
229 ? Math.round(bounds.left + bounds.width - 140)
230 : Math.max(drawerLeft, Math.min(Math.round(pointer.x), drawerRight));
231 const preferredY =
232 selectionRect !== null
233 ? Math.round(selectionRect.bottom + 4)
234 : pointer === null
235 ? Math.round(bounds.top + 12)
236 : Math.max(drawerTop, Math.min(Math.round(pointer.y), drawerBottom));
237 return {
238 x: Math.max(8, Math.min(preferredX, Math.max(viewportWidth - 8, 8))),
239 y: Math.max(8, Math.min(preferredY, Math.max(viewportHeight - 8, 8))),
240 };
242​
243export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
244 return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
246​
247export function shouldHandleTerminalSelectionMouseUp(
248 selectionGestureActive: boolean,
249 button: number,
250): boolean {
251 return selectionGestureActive && button === 0;
253​
254interface TerminalViewportProps {
255 threadRef: ScopedThreadRef;
256 threadId: ThreadId;
257 terminalId: string;
258 terminalLabel: string;
259 cwd: string;
260 worktreePath?: string | null;
261 runtimeEnv?: Record<string, string>;
262 onSessionExited: () => void;
263 onAddTerminalContext: (selection: TerminalContextSelection) => void;
264 focusRequestId: number;
265 autoFocus: boolean;
266 resizeEpoch: number;
267 drawerHeight: number;
268 keybindings: ResolvedKeybindingsConfig;
270​
271interface TerminalLaunchLocation {
272 readonly cwd: string;
273 readonly worktreePath?: string | null;
274 readonly runtimeEnv?: Record<string, string>;
276​
277export function TerminalViewport({
278 threadRef,
279 threadId,
280 terminalId,
281 terminalLabel,
282 cwd,
283 worktreePath,
284 runtimeEnv,
285 onSessionExited,
286 onAddTerminalContext,
287 focusRequestId,
288 autoFocus,
289 resizeEpoch,
290 drawerHeight,
291 keybindings,
292}: TerminalViewportProps) {
293 const containerRef = useRef<HTMLDivElement>(null);
294 const terminalRef = useRef<Terminal | null>(null);
295 const fitAddonRef = useRef<FitAddon | null>(null);
296 const environmentId = threadRef.environmentId;
297 const hasHandledExitRef = useRef(false);
298 const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
299 const selectionGestureActiveRef = useRef(false);
300 const selectionActionRequestIdRef = useRef(0);
301 const selectionActionOpenRef = useRef(false);
302 const selectionActionTimerRef = useRef<number | null>(null);
303 const keybindingsRef = useRef(keybindings);
304 const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]);
305 const handleSessionExited = useEffectEvent(() => {
306 onSessionExited();
307 });
308 const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
309 onAddTerminalContext(selection);
310 });
311 const readTerminalLabel = useEffectEvent(() => terminalLabel);
312​
313 useEffect(() => {
314 keybindingsRef.current = keybindings;
315 }, [keybindings]);
316​
317 useEffect(() => {
318 const mount = containerRef.current;
319 if (!mount) return;
320​
321 let disposed = false;
322 const api = readEnvironmentApi(environmentId);
323 const localApi = readLocalApi();
324 if (!api) return;
325​
326 const fitAddon = new FitAddon();
327 const terminal = new Terminal({
328 cursorBlink: true,
329 lineHeight: 1.2,
330 fontSize: 12,
331 scrollback: 5_000,
332 fontFamily:
333 '"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace',
334 theme: terminalThemeFromApp(mount),
335 });
336 terminal.loadAddon(fitAddon);
337 terminal.open(mount);
338 fitTerminalSafely(fitAddon);
339​
340 terminalRef.current = terminal;
341 fitAddonRef.current = fitAddon;
342​
343 const clearSelectionAction = () => {
344 selectionActionRequestIdRef.current += 1;
345 if (selectionActionTimerRef.current !== null) {
346 window.clearTimeout(selectionActionTimerRef.current);
347 selectionActionTimerRef.current = null;
348 }
349 };
350​
351 const readSelectionAction = (): {
352 position: { x: number; y: number };
353 selection: TerminalContextSelection;
354 } | null => {
355 const activeTerminal = terminalRef.current;
356 const mountElement = containerRef.current;
357 if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
358 return null;
359 }
360 const selectionText = activeTerminal.getSelection();
361 const selectionPosition = activeTerminal.getSelectionPosition();
362 const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
363 if (!selectionPosition || normalizedText.length === 0) {
364 return null;
365 }
366 const lineStart = selectionPosition.start.y + 1;
367 const lineCount = normalizedText.split("\n").length;
368 const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
369 const bounds = mountElement.getBoundingClientRect();
370 const selectionRect = getTerminalSelectionRect(mountElement);
371 const position = resolveTerminalSelectionActionPosition({
372 bounds,
373 selectionRect:
374 selectionRect === null
375 ? null
376 : { right: selectionRect.right, bottom: selectionRect.bottom },
377 pointer: selectionPointerRef.current,
378 });
379 return {
380 position,
381 selection: {
382 terminalId,
383 terminalLabel: readTerminalLabel(),
384 lineStart,
385 lineEnd,
386 text: normalizedText,
387 },
388 };
389 };
390​
391 const showSelectionAction = async () => {
392 if (!localApi) {
393 clearSelectionAction();
394 return;
395 }
396 if (selectionActionOpenRef.current) {
397 return;
398 }
399 const nextAction = readSelectionAction();
400 if (!nextAction) {
401 clearSelectionAction();
402 return;
403 }
404 const requestId = ++selectionActionRequestIdRef.current;
405 selectionActionOpenRef.current = true;
406 try {
407 const clicked = await localApi.contextMenu.show(
408 [{ id: "add-to-chat", label: "Add to chat" }],
409 nextAction.position,
410 );
411 if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
412 return;
413 }
414 handleAddTerminalContext(nextAction.selection);
415 terminalRef.current?.clearSelection();
416 terminalRef.current?.focus();
417 } finally {
418 selectionActionOpenRef.current = false;
419 }
420 };
421​
422 const sendTerminalInput = async (data: string, fallbackError: string) => {
423 const activeTerminal = terminalRef.current;
424 if (!activeTerminal) return;
425 try {
426 await api.terminal.write({ threadId, terminalId, data });
427 } catch (error) {
428 writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
429 }
430 };
431​
432 terminal.attachCustomKeyEventHandler((event) => {
433 const currentKeybindings = keybindingsRef.current;
434 const options = { context: { terminalFocus: true, terminalOpen: true } };
435 if (
436 isTerminalToggleShortcut(event, currentKeybindings, options) ||
437 isTerminalSplitShortcut(event, currentKeybindings, options) ||
438 isTerminalNewShortcut(event, currentKeybindings, options) ||
439 isTerminalCloseShortcut(event, currentKeybindings, options) ||
440 isDiffToggleShortcut(event, currentKeybindings, options)
441 ) {
442 return false;
443 }
444​
445 const navigationData = terminalNavigationShortcutData(event);
446 if (navigationData !== null) {
447 event.preventDefault();
448 event.stopPropagation();
449 void sendTerminalInput(navigationData, "Failed to move cursor");
450 return false;
451 }
452​
453 const deleteData = terminalDeleteShortcutData(event);
454 if (deleteData !== null) {
455 event.preventDefault();
456 event.stopPropagation();
457 void sendTerminalInput(deleteData, "Failed to delete terminal input");
458 return false;
459 }
460​
461 if (!isTerminalClearShortcut(event)) return true;
462 event.preventDefault();
463 event.stopPropagation();
464 void sendTerminalInput("\u000c", "Failed to clear terminal");
465 return false;
466 });
467​
468 const terminalLinksDisposable = terminal.registerLinkProvider({
469 provideLinks: (bufferLineNumber, callback) => {
470 const activeTerminal = terminalRef.current;
471 if (!activeTerminal) {
472 callback(undefined);
473 return;
474 }
475​
476 const wrappedLine = collectWrappedTerminalLinkLine(bufferLineNumber, (bufferLineIndex) =>
477 activeTerminal.buffer.active.getLine(bufferLineIndex),
478 );
479 if (!wrappedLine) {
480 callback(undefined);
481 return;
482 }
483​
484 const links = extractTerminalLinks(wrappedLine.text)
485 .map((match) => ({
486 match,
487 range: resolveWrappedTerminalLinkRange(wrappedLine, match),
488 }))
489 .filter(({ range }) =>
490 wrappedTerminalLinkRangeIntersectsBufferLine(range, bufferLineNumber),
491 );
492 if (links.length === 0) {
493 callback(undefined);
494 return;
495 }
496​
497 callback(
498 links.map(({ match, range }) => ({
499 text: match.text,
500 range,
501 activate: (event: MouseEvent) => {
502 if (!isTerminalLinkActivation(event)) return;
503​
504 const latestTerminal = terminalRef.current;
505 if (!latestTerminal) return;
506 if (!localApi) {
507 writeSystemMessage(latestTerminal, "Opening links is unavailable in this browser.");
508 return;
509 }
510​
511 if (match.kind === "url") {
512 void localApi.shell.openExternal(match.text).catch((error: unknown) => {
513 writeSystemMessage(
514 latestTerminal,
515 error instanceof Error ? error.message : "Unable to open link",
516 );
517 });
518 return;
519 }
520​
521 const target = resolvePathLinkTarget(match.text, cwd);
522 void openInPreferredEditor(localApi, target).catch((error) => {
523 writeSystemMessage(
524 latestTerminal,
525 error instanceof Error ? error.message : "Unable to open path",
526 );
527 });
528 },
529 })),
530 );
531 },
532 });
533​
534 const inputDisposable = terminal.onData((data) => {
535 void api.terminal
536 .write({ threadId, terminalId, data })
537 .catch((err) =>
538 writeSystemMessage(
539 terminal,
540 err instanceof Error ? err.message : "Terminal write failed",
541 ),
542 );
543 });
544​
545 const selectionDisposable = terminal.onSelectionChange(() => {
546 if (terminalRef.current?.hasSelection()) {
547 return;
548 }
549 clearSelectionAction();
550 });
551​
552 const handleMouseUp = (event: MouseEvent) => {
553 const shouldHandle = shouldHandleTerminalSelectionMouseUp(
554 selectionGestureActiveRef.current,
555 event.button,
556 );
557 selectionGestureActiveRef.current = false;
558 if (!shouldHandle) {
559 return;
560 }
561 selectionPointerRef.current = { x: event.clientX, y: event.clientY };
562 const delay = terminalSelectionActionDelayForClickCount(event.detail);
563 selectionActionTimerRef.current = window.setTimeout(() => {
564 selectionActionTimerRef.current = null;
565 window.requestAnimationFrame(() => {
566 void showSelectionAction();
567 });
568 }, delay);
569 };
570 const handlePointerDown = (event: PointerEvent) => {
571 clearSelectionAction();
572 selectionGestureActiveRef.current = event.button === 0;
573 };
574 window.addEventListener("mouseup", handleMouseUp);
575 mount.addEventListener("pointerdown", handlePointerDown);
576​
577 const themeObserver = new MutationObserver(() => {
578 const activeTerminal = terminalRef.current;
579 if (!activeTerminal) return;
580 activeTerminal.options.theme = terminalThemeFromApp(containerRef.current);
581 activeTerminal.refresh(0, activeTerminal.rows - 1);
582 });
583 themeObserver.observe(document.documentElement, {
584 attributes: true,
585 attributeFilter: ["class", "style"],
586 });
587​
588 const applyAttachEvent = (event: TerminalAttachStreamEvent) => {
589 const activeTerminal = terminalRef.current;
590 if (!activeTerminal) {
591 return;
592 }
593​
594 if (event.type === "activity") {
595 return;
596 }
597​
598 if (event.type === "snapshot") {
599 hasHandledExitRef.current = false;
600 clearSelectionAction();
601 writeTerminalSnapshot(activeTerminal, event.snapshot);
602 return;
603 }
604​
605 if (event.type === "output") {
606 activeTerminal.write(event.data);
607 clearSelectionAction();
608 return;
609 }
610​
611 if (event.type === "restarted") {
612 hasHandledExitRef.current = false;
613 clearSelectionAction();
614 writeTerminalSnapshot(activeTerminal, event.snapshot);
615 return;
616 }
617​
618 if (event.type === "cleared") {
619 clearSelectionAction();
620 activeTerminal.clear();
621 activeTerminal.write("\u001bc");
622 return;
623 }
624​
625 if (event.type === "error") {
626 writeSystemMessage(activeTerminal, event.message);
627 return;
628 }
629​
630 if (event.type === "closed") {
631 writeSystemMessage(activeTerminal, "Terminal closed");
632 } else {
633 const details = [
634 typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
635 typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
636 ]
637 .filter((value): value is string => value !== null)
638 .join(", ");
639 writeSystemMessage(
640 activeTerminal,
641 details.length > 0 ? `Process exited (${details})` : "Process exited",
642 );
643 }
644​
645 if (hasHandledExitRef.current) {
646 return;
647 }
648 hasHandledExitRef.current = true;
649 window.setTimeout(() => {
650 if (!hasHandledExitRef.current) {
651 return;
652 }
653 handleSessionExited();
654 }, 0);
655 };
656 let unsubscribeAttach: (() => void) | null = null;
657 const attachTerminal = () => {
658 const activeTerminal = terminalRef.current;
659 const activeFitAddon = fitAddonRef.current;
660 if (!activeTerminal || !activeFitAddon) return;
661 fitTerminalSafely(activeFitAddon);
662 unsubscribeAttach = attachTerminalSession({
663 environmentId,
664 client: api,
665 terminal: {
666 threadId,
667 terminalId,
668 cwd,
669 ...(worktreePath !== undefined ? { worktreePath } : {}),
670 cols: activeTerminal.cols,
671 rows: activeTerminal.rows,
672 ...(runtimeEnv ? { env: runtimeEnv } : {}),
673 },
674 onEvent: (event) => {
675 if (disposed) return;
676 applyAttachEvent(event);
677 },
678 onSnapshot: () => {
679 if (disposed) return;
680 if (autoFocus) {
681 window.requestAnimationFrame(() => {
682 activeTerminal.focus();
683 });
684 }
685 },
686 });
687 };
688​
689 const fitTimer = window.setTimeout(() => {
690 const activeTerminal = terminalRef.current;
691 const activeFitAddon = fitAddonRef.current;
692 if (!activeTerminal || !activeFitAddon) return;
693 const wasAtBottom =
694 activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
695 fitTerminalSafely(activeFitAddon);
696 if (wasAtBottom) {
697 activeTerminal.scrollToBottom();
698 }
699 void api.terminal
700 .resize({
701 threadId,
702 terminalId,
703 cols: activeTerminal.cols,
704 rows: activeTerminal.rows,
705 })
706 .catch(() => undefined);
707 }, 30);
708 attachTerminal();
709​
710 return () => {
711 disposed = true;
712 unsubscribeAttach?.();
713 unsubscribeAttach = null;
714 window.clearTimeout(fitTimer);
715 inputDisposable.dispose();
716 selectionDisposable.dispose();
717 terminalLinksDisposable.dispose();
718 if (selectionActionTimerRef.current !== null) {
719 window.clearTimeout(selectionActionTimerRef.current);
720 }
721 window.removeEventListener("mouseup", handleMouseUp);
722 mount.removeEventListener("pointerdown", handlePointerDown);
723 themeObserver.disconnect();
724 terminalRef.current = null;
725 fitAddonRef.current = null;
726 terminal.dispose();
727 };
728 // autoFocus is intentionally omitted;
729 // it is only read at mount time and must not trigger terminal teardown/recreation.
730 // eslint-disable-next-line react-hooks/exhaustive-deps
731 }, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]);
732​
733 useEffect(() => {
734 if (!autoFocus) return;
735 const terminal = terminalRef.current;
736 if (!terminal) return;
737 const frame = window.requestAnimationFrame(() => {
738 terminal.focus();
739 });
740 return () => {
741 window.cancelAnimationFrame(frame);
742 };
743 }, [autoFocus, focusRequestId]);
744​
745 useEffect(() => {
746 const api = readEnvironmentApi(environmentId);
747 const terminal = terminalRef.current;
748 const fitAddon = fitAddonRef.current;
749 if (!api || !terminal || !fitAddon) return;
750 const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
751 const frame = window.requestAnimationFrame(() => {
752 fitTerminalSafely(fitAddon);
753 if (wasAtBottom) {
754 terminal.scrollToBottom();
755 }
756 void api.terminal
757 .resize({
758 threadId,
759 terminalId,
760 cols: terminal.cols,
761 rows: terminal.rows,
762 })
763 .catch(() => undefined);
764 });
765 return () => {
766 window.cancelAnimationFrame(frame);
767 };
768 }, [drawerHeight, environmentId, resizeEpoch, terminalId, threadId]);
769 return (
770 <div
771 ref={containerRef}
772 className="relative h-full w-full overflow-hidden rounded-[4px] bg-background"
773 />
774 );
776​
777interface ThreadTerminalDrawerProps {
778 threadRef: ScopedThreadRef;
779 threadId: ThreadId;
780 cwd: string;
781 worktreePath?: string | null;
782 runtimeEnv?: Record<string, string>;
783 visible?: boolean;
784 height: number;
785 terminalIds: string[];
786 activeTerminalId: string;
787 terminalGroups: ThreadTerminalGroup[];
788 activeTerminalGroupId: string;
789 focusRequestId: number;
790 onSplitTerminal: () => void;
791 onNewTerminal: () => void;
792 splitShortcutLabel?: string | undefined;
793 newShortcutLabel?: string | undefined;
794 closeShortcutLabel?: string | undefined;
795 onActiveTerminalChange: (terminalId: string) => void;
796 onCloseTerminal: (terminalId: string) => void;
797 onHeightChange: (height: number) => void;
798 onAddTerminalContext: (selection: TerminalContextSelection) => void;
799 keybindings: ResolvedKeybindingsConfig;
800 /** Prefer server-provided tab titles when present (e.g. active subprocess name). */
801 terminalLabelsById?: ReadonlyMap<string, string>;
802 /** Prefer per-session launch locations when the server already knows a terminal. */
803 terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>;
805​
806interface TerminalActionButtonProps {
807 label: string;
808 className: string;
809 onClick: () => void;
810 children: ReactNode;
812​
813function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
814 return (
815 <Popover>
816 <PopoverTrigger
817 openOnHover
818 render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
819 >
820 {children}
821 </PopoverTrigger>
822 <PopoverPopup
823 tooltipStyle
824 side="bottom"
825 sideOffset={6}
826 align="center"
827 className="pointer-events-none select-none"
828 >
829 {label}
830 </PopoverPopup>
831 </Popover>
832 );
834​
835export default function ThreadTerminalDrawer({
836 threadRef,
837 threadId,
838 cwd,
839 worktreePath,
840 runtimeEnv,
841 visible = true,
842 height,
843 terminalIds,
844 activeTerminalId,
845 terminalGroups,
846 activeTerminalGroupId,
847 focusRequestId,
848 onSplitTerminal,
849 onNewTerminal,
850 splitShortcutLabel,
851 newShortcutLabel,
852 closeShortcutLabel,
853 onActiveTerminalChange,
854 onCloseTerminal,
855 onHeightChange,
856 onAddTerminalContext,
857 keybindings,
858 terminalLabelsById,
859 terminalLaunchLocationsById,
860}: ThreadTerminalDrawerProps) {
861 const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
862 const [resizeEpoch, setResizeEpoch] = useState(0);
863 const drawerHeightRef = useRef(drawerHeight);
864 const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
865 const onHeightChangeRef = useRef(onHeightChange);
866 const resizeStateRef = useRef<{
867 pointerId: number;
868 startY: number;
869 startHeight: number;
870 } | null>(null);
871 const didResizeDuringDragRef = useRef(false);
872​
873 const normalizedTerminalIds = useMemo(() => {
874 const normalizedIds: string[] = [];
875 const seen = new Set<string>();
876 for (const id of terminalIds) {
877 const trimmedId = id.trim();
878 if (trimmedId.length === 0 || seen.has(trimmedId)) continue;
879 seen.add(trimmedId);
880 normalizedIds.push(trimmedId);
881 }
882 return normalizedIds;
883 }, [terminalIds]);
884​
885 const resolvedActiveTerminalId =
886 normalizedTerminalIds.length === 0
887 ? ""
888 : normalizedTerminalIds.includes(activeTerminalId)
889 ? activeTerminalId
890 : (normalizedTerminalIds[0] ?? "");
891​
892 const resolvedTerminalGroups = useMemo(() => {
893 if (normalizedTerminalIds.length === 0) {
894 return [];
895 }
896 const validTerminalIdSet = new Set(normalizedTerminalIds);
897 const assignedTerminalIds = new Set<string>();
898 const usedGroupIds = new Set<string>();
899 const nextGroups: ThreadTerminalGroup[] = [];
900​
901 const assignUniqueGroupId = (groupId: string): string => {
902 if (!usedGroupIds.has(groupId)) {
903 usedGroupIds.add(groupId);
904 return groupId;
905 }
906 let suffix = 2;
907 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
908 suffix += 1;
909 }
910 const uniqueGroupId = `${groupId}-${suffix}`;
911 usedGroupIds.add(uniqueGroupId);
912 return uniqueGroupId;
913 };
914​
915 for (const terminalGroup of terminalGroups) {
916 const nextTerminalIds: string[] = [];
917 const seenGroupTerminalIds = new Set<string>();
918 for (const id of terminalGroup.terminalIds) {
919 const terminalId = id.trim();
920 if (terminalId.length === 0) continue;
921 if (seenGroupTerminalIds.has(terminalId)) continue;
922 seenGroupTerminalIds.add(terminalId);
923 if (!validTerminalIdSet.has(terminalId)) continue;
924 if (assignedTerminalIds.has(terminalId)) continue;
925 nextTerminalIds.push(terminalId);
926 }
927 if (nextTerminalIds.length === 0) continue;
928​
929 for (const terminalId of nextTerminalIds) {
930 assignedTerminalIds.add(terminalId);
931 }
932​
933 const baseGroupId =
934 terminalGroup.id.trim().length > 0
935 ? terminalGroup.id.trim()
936 : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`;
937 nextGroups.push({
938 id: assignUniqueGroupId(baseGroupId),
939 terminalIds: nextTerminalIds,
940 });
941 }
942​
943 for (const terminalId of normalizedTerminalIds) {
944 if (assignedTerminalIds.has(terminalId)) continue;
945 nextGroups.push({
946 id: assignUniqueGroupId(`group-${terminalId}`),
947 terminalIds: [terminalId],
948 });
949 }
950​
951 const terminalOrderIndex = new Map(
952 normalizedTerminalIds.map((id, index) => [id, index] as const),
953 );
954 nextGroups.sort((left, right) => {
955 const rank = (ids: readonly string[]) =>
956 Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY));
957 return rank(left.terminalIds) - rank(right.terminalIds);
958 });
959​
960 return nextGroups;
961 }, [normalizedTerminalIds, terminalGroups]);
962​
963 const resolvedActiveGroupIndex = useMemo(() => {
964 const indexById = resolvedTerminalGroups.findIndex(
965 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
966 );
967 if (indexById >= 0) return indexById;
968 const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
969 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
970 );
971 return indexByTerminal >= 0 ? indexByTerminal : 0;
972 }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
973​
974 const visibleTerminalIds =
975 resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ??
976 (normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []);
977 const hasTerminalSidebar = normalizedTerminalIds.length > 1;
978 const isSplitView = visibleTerminalIds.length > 1;
979 const showGroupHeaders =
980 resolvedTerminalGroups.length > 1 ||
981 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
982 const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
983 const terminalLabelById = useMemo(() => {
984 const next = new Map<string, string>();
985 for (const terminalId of normalizedTerminalIds) {
986 next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId));
987 }
988 return next;
989 }, [normalizedTerminalIds, terminalLabelsById]);
990 const resolveTerminalLaunchLocation = useCallback(
991 (terminalId: string): TerminalLaunchLocation => {
992 return (
993 terminalLaunchLocationsById?.get(terminalId) ?? {
994 cwd,
995 ...(worktreePath !== undefined ? { worktreePath } : {}),
996 ...(runtimeEnv ? { runtimeEnv } : {}),
997 }
998 );
999 },
1000 [cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
1001 );
1002 const splitTerminalActionLabel = hasReachedSplitLimit
1003 ? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
1004 : splitShortcutLabel
1005 ? `Split Terminal (${splitShortcutLabel})`
1006 : "Split Terminal";
1007 const newTerminalActionLabel = newShortcutLabel
1008 ? `New Terminal (${newShortcutLabel})`
1009 : "New Terminal";
1010 const closeTerminalActionLabel = closeShortcutLabel
1011 ? `Close Terminal (${closeShortcutLabel})`
1012 : "Close Terminal";
1013 const onSplitTerminalAction = useCallback(() => {
1014 if (hasReachedSplitLimit) return;
1015 onSplitTerminal();
1016 }, [hasReachedSplitLimit, onSplitTerminal]);
1017 const onNewTerminalAction = useCallback(() => {
1018 onNewTerminal();
1019 }, [onNewTerminal]);
1020​
1021 useEffect(() => {
1022 onHeightChangeRef.current = onHeightChange;
1023 }, [onHeightChange]);
1024​
1025 useEffect(() => {
1026 drawerHeightRef.current = drawerHeight;
1027 }, [drawerHeight]);
1028​
1029 const syncHeight = useCallback((nextHeight: number) => {
1030 const clampedHeight = clampDrawerHeight(nextHeight);
1031 if (lastSyncedHeightRef.current === clampedHeight) return;
1032 lastSyncedHeightRef.current = clampedHeight;
1033 onHeightChangeRef.current(clampedHeight);
1034 }, []);
1035​
1036 useEffect(() => {
1037 const clampedHeight = clampDrawerHeight(height);
1038 setDrawerHeight(clampedHeight);
1039 drawerHeightRef.current = clampedHeight;
1040 lastSyncedHeightRef.current = clampedHeight;
1041 }, [height, threadId]);
1042​
1043 const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1044 if (event.button !== 0) return;
1045 event.preventDefault();
1046 event.currentTarget.setPointerCapture(event.pointerId);
1047 didResizeDuringDragRef.current = false;
1048 resizeStateRef.current = {
1049 pointerId: event.pointerId,
1050 startY: event.clientY,
1051 startHeight: drawerHeightRef.current,
1052 };
1053 }, []);
1054​
1055 const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1056 const resizeState = resizeStateRef.current;
1057 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1058 event.preventDefault();
1059 const clampedHeight = clampDrawerHeight(
1060 resizeState.startHeight + (resizeState.startY - event.clientY),
1061 );
1062 if (clampedHeight === drawerHeightRef.current) {
1063 return;
1065 didResizeDuringDragRef.current = true;
1066 drawerHeightRef.current = clampedHeight;
1067 setDrawerHeight(clampedHeight);
1068 }, []);
1069​
1070 const handleResizePointerEnd = useCallback(
1071 (event: ReactPointerEvent<HTMLDivElement>) => {
1072 const resizeState = resizeStateRef.current;
1073 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1074 resizeStateRef.current = null;
1075 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
1076 event.currentTarget.releasePointerCapture(event.pointerId);
1078 if (!didResizeDuringDragRef.current) {
1079 return;
1081 syncHeight(drawerHeightRef.current);
1082 setResizeEpoch((value) => value + 1);
1083 },
1084 [syncHeight],
1085 );
1086​
1087 useEffect(() => {
1088 if (!visible) {
1089 return;
1091​
1092 const onWindowResize = () => {
1093 const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
1094 const changed = clampedHeight !== drawerHeightRef.current;
1095 if (changed) {
1096 setDrawerHeight(clampedHeight);
1097 drawerHeightRef.current = clampedHeight;
1099 if (!resizeStateRef.current) {
1100 syncHeight(clampedHeight);
1102 setResizeEpoch((value) => value + 1);
1103 };
1104 window.addEventListener("resize", onWindowResize);
1105 return () => {
1106 window.removeEventListener("resize", onWindowResize);
1107 };
1108 }, [syncHeight, visible]);
1109​
1110 useEffect(() => {
1111 if (!visible) {
1112 return;
1114 setResizeEpoch((value) => value + 1);
1115 }, [visible]);
1116​
1117 useEffect(() => {
1118 return () => {
1119 syncHeight(drawerHeightRef.current);
1120 };
1121 }, [syncHeight]);
1122​
1123 if (normalizedTerminalIds.length === 0) {
1124 return (
1125 <aside
1126 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
1127 style={{ height: `${drawerHeight}px` }}
1129 <div
1130 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
1131 onPointerDown={handleResizePointerDown}
1132 onPointerMove={handleResizePointerMove}
1133 onPointerUp={handleResizePointerEnd}
1134 onPointerCancel={handleResizePointerEnd}
1135 />
1136 <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">
1137 <p>No terminal sessions for this thread yet.</p>
1138 <button
1139 type="button"
1140 className="rounded-md border border-border/80 bg-background px-3 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent"
1141 onClick={onNewTerminalAction}
1143 {newTerminalActionLabel}
1144 </button>
1145 </div>
1146 </aside>
1147 );
1149​
1150 const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId);
1151​
1152 return (
1153 <aside
1154 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
1155 style={{ height: `${drawerHeight}px` }}
1157 <div
1158 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
1159 onPointerDown={handleResizePointerDown}
1160 onPointerMove={handleResizePointerMove}
1161 onPointerUp={handleResizePointerEnd}
1162 onPointerCancel={handleResizePointerEnd}
1163 />
1164​
1165 {!hasTerminalSidebar && (
1166 <div className="pointer-events-none absolute right-2 top-2 z-20">
1167 <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
1168 <TerminalActionButton
1169 className={`p-1 text-foreground/90 transition-colors ${
1170 hasReachedSplitLimit
1171 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1172 : "hover:bg-accent"
1173 }`}
1174 onClick={onSplitTerminalAction}
1175 label={splitTerminalActionLabel}
1177 <SquareSplitHorizontal className="size-3.25" />
1178 </TerminalActionButton>
1179 <div className="h-4 w-px bg-border/80" />
1180 <TerminalActionButton
1181 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1182 onClick={onNewTerminalAction}
1183 label={newTerminalActionLabel}
1185 <Plus className="size-3.25" />
1186 </TerminalActionButton>
1187 <div className="h-4 w-px bg-border/80" />
1188 <TerminalActionButton
1189 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1190 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1191 label={closeTerminalActionLabel}
1193 <Trash2 className="size-3.25" />
1194 </TerminalActionButton>
1195 </div>
1196 </div>
1197 )}
1198​
1199 <div className="min-h-0 w-full flex-1">
1200 <div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
1201 <div className="min-w-0 flex-1">
1202 {isSplitView ? (
1203 <div
1204 className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
1205 style={{
1206 gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
1207 }}
1209 {visibleTerminalIds.map((terminalId) => {
1210 const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
1211 return (
1212 <div
1213 key={terminalId}
1214 className={`min-h-0 min-w-0 border-l first:border-l-0 ${
1215 terminalId === resolvedActiveTerminalId
1216 ? "border-border"
1217 : "border-border/70"
1218 }`}
1219 onMouseDown={() => {
1220 if (terminalId !== resolvedActiveTerminalId) {
1221 onActiveTerminalChange(terminalId);
1223 }}
1225 <div className="h-full p-1">
1226 <TerminalViewport
1227 threadRef={threadRef}
1228 threadId={threadId}
1229 terminalId={terminalId}
1230 terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
1231 cwd={terminalLaunchLocation.cwd}
1232 {...(terminalLaunchLocation.worktreePath !== undefined
1233 ? { worktreePath: terminalLaunchLocation.worktreePath }
1234 : {})}
1235 {...(terminalLaunchLocation.runtimeEnv
1236 ? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
1237 : {})}
1238 onSessionExited={() => onCloseTerminal(terminalId)}
1239 onAddTerminalContext={onAddTerminalContext}
1240 focusRequestId={focusRequestId}
1241 autoFocus={terminalId === resolvedActiveTerminalId}
1242 resizeEpoch={resizeEpoch}
1243 drawerHeight={drawerHeight}
1244 keybindings={keybindings}
1245 />
1246 </div>
1247 </div>
1248 );
1249 })}
1250 </div>
1251 ) : (
1252 <div className="h-full p-1">
1253 <TerminalViewport
1254 key={resolvedActiveTerminalId}
1255 threadRef={threadRef}
1256 threadId={threadId}
1257 terminalId={resolvedActiveTerminalId}
1258 terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
1259 cwd={activeTerminalLaunchLocation.cwd}
1260 {...(activeTerminalLaunchLocation.worktreePath !== undefined
1261 ? { worktreePath: activeTerminalLaunchLocation.worktreePath }
1262 : {})}
1263 {...(activeTerminalLaunchLocation.runtimeEnv
1264 ? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }
1265 : {})}
1266 onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
1267 onAddTerminalContext={onAddTerminalContext}
1268 focusRequestId={focusRequestId}
1269 autoFocus
1270 resizeEpoch={resizeEpoch}
1271 drawerHeight={drawerHeight}
1272 keybindings={keybindings}
1273 />
1274 </div>
1275 )}
1276 </div>
1277​
1278 {hasTerminalSidebar && (
1279 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
1280 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
1281 <div className="inline-flex h-full items-stretch">
1282 <TerminalActionButton
1283 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
1284 hasReachedSplitLimit
1285 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1286 : "hover:bg-accent/70"
1287 }`}
1288 onClick={onSplitTerminalAction}
1289 label={splitTerminalActionLabel}
1291 <SquareSplitHorizontal className="size-3.25" />
1292 </TerminalActionButton>
1293 <TerminalActionButton
1294 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1295 onClick={onNewTerminalAction}
1296 label={newTerminalActionLabel}
1298 <Plus className="size-3.25" />
1299 </TerminalActionButton>
1300 <TerminalActionButton
1301 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1302 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1303 label={closeTerminalActionLabel}
1305 <Trash2 className="size-3.25" />
1306 </TerminalActionButton>
1307 </div>
1308 </div>
1309​
1310 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
1311 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
1312 const isGroupActive =
1313 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
1314 const groupActiveTerminalId = isGroupActive
1315 ? resolvedActiveTerminalId
1316 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
1317​
1318 return (
1319 <div key={terminalGroup.id} className="pb-0.5">
1320 {showGroupHeaders && (
1321 <button
1322 type="button"
1323 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
1324 isGroupActive
1325 ? "bg-accent/70 text-foreground"
1326 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1327 }`}
1328 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
1330 Group {groupIndex + 1}
1331 </button>
1332 )}
1333​
1334 <div
1335 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
1337 {terminalGroup.terminalIds.map((terminalId) => {
1338 const isActive = terminalId === resolvedActiveTerminalId;
1339 const closeTerminalLabel = `Close ${
1340 terminalLabelById.get(terminalId) ?? "terminal"
1341 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
1342 return (
1343 <div
1344 key={terminalId}
1345 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
1346 isActive
1347 ? "bg-accent text-foreground"
1348 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1349 }`}
1351 {showGroupHeaders && (
1352 <span className="text-[10px] text-muted-foreground/80">└</span>
1353 )}
1354 <button
1355 type="button"
1356 className="flex min-w-0 flex-1 items-center gap-1 text-left"
1357 onClick={() => onActiveTerminalChange(terminalId)}
1359 <TerminalSquare className="size-3 shrink-0" />
1360 <span className="truncate">
1361 {terminalLabelById.get(terminalId) ?? "Terminal"}
1362 </span>
1363 </button>
1364 {normalizedTerminalIds.length > 1 && (
1365 <Popover>
1366 <PopoverTrigger
1367 openOnHover
1368 render={
1369 <button
1370 type="button"
1371 className="inline-flex size-3.5 items-center justify-center rounded text-xs font-medium leading-none text-muted-foreground opacity-0 transition hover:bg-accent hover:text-foreground group-hover:opacity-100"
1372 onClick={() => onCloseTerminal(terminalId)}
1373 aria-label={closeTerminalLabel}
1374 />
1377 <XIcon className="size-2.5" />
1378 </PopoverTrigger>
1379 <PopoverPopup
1380 tooltipStyle
1381 side="bottom"
1382 sideOffset={6}
1383 align="center"
1384 className="pointer-events-none select-none"
1386 {closeTerminalLabel}
1387 </PopoverPopup>
1388 </Popover>
1389 )}
1390 </div>
1391 );
1392 })}
1393 </div>
1394 </div>
1395 );
1396 })}
1397 </div>
1398 </aside>
1399 )}
1400 </div>
1401 </div>
1402 </aside>
1403 );