Open History to see the last commit
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));
59}
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);
65}
66
67function writeSystemMessage(terminal: Terminal, message: string): void {
68 terminal.write(`\r\n[terminal] ${message}\r\n`);
69}
70
71function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void {
72 terminal.write("\u001bc");
73 if (snapshot.history.length > 0) {
74 terminal.write(snapshot.history);
75 }
76}
77
78function fitTerminalSafely(fitAddon: FitAddon): boolean {
79 try {
80 fitAddon.fit();
81 return true;
82 } catch {
83 return false;
84 }
85}
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 );
94}
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;
107}
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 };
181}
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;
206}
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 };
241}
242
243export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
244 return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
245}
246
247export function shouldHandleTerminalSelectionMouseUp(
248 selectionGestureActive: boolean,
249 button: number,
250): boolean {
251 return selectionGestureActive && button === 0;
252}
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;
269}
270
271interface TerminalLaunchLocation {
272 readonly cwd: string;
273 readonly worktreePath?: string | null;
274 readonly runtimeEnv?: Record<string, string>;
275}
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: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
333 theme: terminalThemeFromApp(mount),
334 });
335 terminal.loadAddon(fitAddon);
336 terminal.open(mount);
337 fitTerminalSafely(fitAddon);
338
339 terminalRef.current = terminal;
340 fitAddonRef.current = fitAddon;
341
342 const clearSelectionAction = () => {
343 selectionActionRequestIdRef.current += 1;
344 if (selectionActionTimerRef.current !== null) {
345 window.clearTimeout(selectionActionTimerRef.current);
346 selectionActionTimerRef.current = null;
347 }
348 };
349
350 const readSelectionAction = (): {
351 position: { x: number; y: number };
352 selection: TerminalContextSelection;
353 } | null => {
354 const activeTerminal = terminalRef.current;
355 const mountElement = containerRef.current;
356 if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
357 return null;
358 }
359 const selectionText = activeTerminal.getSelection();
360 const selectionPosition = activeTerminal.getSelectionPosition();
361 const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
362 if (!selectionPosition || normalizedText.length === 0) {
363 return null;
364 }
365 const lineStart = selectionPosition.start.y + 1;
366 const lineCount = normalizedText.split("\n").length;
367 const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
368 const bounds = mountElement.getBoundingClientRect();
369 const selectionRect = getTerminalSelectionRect(mountElement);
370 const position = resolveTerminalSelectionActionPosition({
371 bounds,
372 selectionRect:
373 selectionRect === null
374 ? null
375 : { right: selectionRect.right, bottom: selectionRect.bottom },
376 pointer: selectionPointerRef.current,
377 });
378 return {
379 position,
380 selection: {
381 terminalId,
382 terminalLabel: readTerminalLabel(),
383 lineStart,
384 lineEnd,
385 text: normalizedText,
386 },
387 };
388 };
389
390 const showSelectionAction = async () => {
391 if (!localApi) {
392 clearSelectionAction();
393 return;
394 }
395 if (selectionActionOpenRef.current) {
396 return;
397 }
398 const nextAction = readSelectionAction();
399 if (!nextAction) {
400 clearSelectionAction();
401 return;
402 }
403 const requestId = ++selectionActionRequestIdRef.current;
404 selectionActionOpenRef.current = true;
405 try {
406 const clicked = await localApi.contextMenu.show(
407 [{ id: "add-to-chat", label: "Add to chat" }],
408 nextAction.position,
409 );
410 if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
411 return;
412 }
413 handleAddTerminalContext(nextAction.selection);
414 terminalRef.current?.clearSelection();
415 terminalRef.current?.focus();
416 } finally {
417 selectionActionOpenRef.current = false;
418 }
419 };
420
421 const sendTerminalInput = async (data: string, fallbackError: string) => {
422 const activeTerminal = terminalRef.current;
423 if (!activeTerminal) return;
424 try {
425 await api.terminal.write({ threadId, terminalId, data });
426 } catch (error) {
427 writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
428 }
429 };
430
431 terminal.attachCustomKeyEventHandler((event) => {
432 const currentKeybindings = keybindingsRef.current;
433 const options = { context: { terminalFocus: true, terminalOpen: true } };
434 if (
435 isTerminalToggleShortcut(event, currentKeybindings, options) ||
436 isTerminalSplitShortcut(event, currentKeybindings, options) ||
437 isTerminalNewShortcut(event, currentKeybindings, options) ||
438 isTerminalCloseShortcut(event, currentKeybindings, options) ||
439 isDiffToggleShortcut(event, currentKeybindings, options)
440 ) {
441 return false;
442 }
443
444 const navigationData = terminalNavigationShortcutData(event);
445 if (navigationData !== null) {
446 event.preventDefault();
447 event.stopPropagation();
448 void sendTerminalInput(navigationData, "Failed to move cursor");
449 return false;
450 }
451
452 const deleteData = terminalDeleteShortcutData(event);
453 if (deleteData !== null) {
454 event.preventDefault();
455 event.stopPropagation();
456 void sendTerminalInput(deleteData, "Failed to delete terminal input");
457 return false;
458 }
459
460 if (!isTerminalClearShortcut(event)) return true;
461 event.preventDefault();
462 event.stopPropagation();
463 void sendTerminalInput("\u000c", "Failed to clear terminal");
464 return false;
465 });
466
467 const terminalLinksDisposable = terminal.registerLinkProvider({
468 provideLinks: (bufferLineNumber, callback) => {
469 const activeTerminal = terminalRef.current;
470 if (!activeTerminal) {
471 callback(undefined);
472 return;
473 }
474
475 const wrappedLine = collectWrappedTerminalLinkLine(bufferLineNumber, (bufferLineIndex) =>
476 activeTerminal.buffer.active.getLine(bufferLineIndex),
477 );
478 if (!wrappedLine) {
479 callback(undefined);
480 return;
481 }
482
483 const links = extractTerminalLinks(wrappedLine.text)
484 .map((match) => ({
485 match,
486 range: resolveWrappedTerminalLinkRange(wrappedLine, match),
487 }))
488 .filter(({ range }) =>
489 wrappedTerminalLinkRangeIntersectsBufferLine(range, bufferLineNumber),
490 );
491 if (links.length === 0) {
492 callback(undefined);
493 return;
494 }
495
496 callback(
497 links.map(({ match, range }) => ({
498 text: match.text,
499 range,
500 activate: (event: MouseEvent) => {
501 if (!isTerminalLinkActivation(event)) return;
502
503 const latestTerminal = terminalRef.current;
504 if (!latestTerminal) return;
505 if (!localApi) {
506 writeSystemMessage(latestTerminal, "Opening links is unavailable in this browser.");
507 return;
508 }
509
510 if (match.kind === "url") {
511 void localApi.shell.openExternal(match.text).catch((error: unknown) => {
512 writeSystemMessage(
513 latestTerminal,
514 error instanceof Error ? error.message : "Unable to open link",
515 );
516 });
517 return;
518 }
519
520 const target = resolvePathLinkTarget(match.text, cwd);
521 void openInPreferredEditor(localApi, target).catch((error) => {
522 writeSystemMessage(
523 latestTerminal,
524 error instanceof Error ? error.message : "Unable to open path",
525 );
526 });
527 },
528 })),
529 );
530 },
531 });
532
533 const inputDisposable = terminal.onData((data) => {
534 void api.terminal
535 .write({ threadId, terminalId, data })
536 .catch((err) =>
537 writeSystemMessage(
538 terminal,
539 err instanceof Error ? err.message : "Terminal write failed",
540 ),
541 );
542 });
543
544 const selectionDisposable = terminal.onSelectionChange(() => {
545 if (terminalRef.current?.hasSelection()) {
546 return;
547 }
548 clearSelectionAction();
549 });
550
551 const handleMouseUp = (event: MouseEvent) => {
552 const shouldHandle = shouldHandleTerminalSelectionMouseUp(
553 selectionGestureActiveRef.current,
554 event.button,
555 );
556 selectionGestureActiveRef.current = false;
557 if (!shouldHandle) {
558 return;
559 }
560 selectionPointerRef.current = { x: event.clientX, y: event.clientY };
561 const delay = terminalSelectionActionDelayForClickCount(event.detail);
562 selectionActionTimerRef.current = window.setTimeout(() => {
563 selectionActionTimerRef.current = null;
564 window.requestAnimationFrame(() => {
565 void showSelectionAction();
566 });
567 }, delay);
568 };
569 const handlePointerDown = (event: PointerEvent) => {
570 clearSelectionAction();
571 selectionGestureActiveRef.current = event.button === 0;
572 };
573 window.addEventListener("mouseup", handleMouseUp);
574 mount.addEventListener("pointerdown", handlePointerDown);
575
576 const themeObserver = new MutationObserver(() => {
577 const activeTerminal = terminalRef.current;
578 if (!activeTerminal) return;
579 activeTerminal.options.theme = terminalThemeFromApp(containerRef.current);
580 activeTerminal.refresh(0, activeTerminal.rows - 1);
581 });
582 themeObserver.observe(document.documentElement, {
583 attributes: true,
584 attributeFilter: ["class", "style"],
585 });
586
587 const applyAttachEvent = (event: TerminalAttachStreamEvent) => {
588 const activeTerminal = terminalRef.current;
589 if (!activeTerminal) {
590 return;
591 }
592
593 if (event.type === "activity") {
594 return;
595 }
596
597 if (event.type === "snapshot") {
598 hasHandledExitRef.current = false;
599 clearSelectionAction();
600 writeTerminalSnapshot(activeTerminal, event.snapshot);
601 return;
602 }
603
604 if (event.type === "output") {
605 activeTerminal.write(event.data);
606 clearSelectionAction();
607 return;
608 }
609
610 if (event.type === "restarted") {
611 hasHandledExitRef.current = false;
612 clearSelectionAction();
613 writeTerminalSnapshot(activeTerminal, event.snapshot);
614 return;
615 }
616
617 if (event.type === "cleared") {
618 clearSelectionAction();
619 activeTerminal.clear();
620 activeTerminal.write("\u001bc");
621 return;
622 }
623
624 if (event.type === "error") {
625 writeSystemMessage(activeTerminal, event.message);
626 return;
627 }
628
629 if (event.type === "closed") {
630 writeSystemMessage(activeTerminal, "Terminal closed");
631 } else {
632 const details = [
633 typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
634 typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
635 ]
636 .filter((value): value is string => value !== null)
637 .join(", ");
638 writeSystemMessage(
639 activeTerminal,
640 details.length > 0 ? `Process exited (${details})` : "Process exited",
641 );
642 }
643
644 if (hasHandledExitRef.current) {
645 return;
646 }
647 hasHandledExitRef.current = true;
648 window.setTimeout(() => {
649 if (!hasHandledExitRef.current) {
650 return;
651 }
652 handleSessionExited();
653 }, 0);
654 };
655 let unsubscribeAttach: (() => void) | null = null;
656 const attachTerminal = () => {
657 const activeTerminal = terminalRef.current;
658 const activeFitAddon = fitAddonRef.current;
659 if (!activeTerminal || !activeFitAddon) return;
660 fitTerminalSafely(activeFitAddon);
661 unsubscribeAttach = attachTerminalSession({
662 environmentId,
663 client: api,
664 terminal: {
665 threadId,
666 terminalId,
667 cwd,
668 ...(worktreePath !== undefined ? { worktreePath } : {}),
669 cols: activeTerminal.cols,
670 rows: activeTerminal.rows,
671 ...(runtimeEnv ? { env: runtimeEnv } : {}),
672 },
673 onEvent: (event) => {
674 if (disposed) return;
675 applyAttachEvent(event);
676 },
677 onSnapshot: () => {
678 if (disposed) return;
679 if (autoFocus) {
680 window.requestAnimationFrame(() => {
681 activeTerminal.focus();
682 });
683 }
684 },
685 });
686 };
687
688 const fitTimer = window.setTimeout(() => {
689 const activeTerminal = terminalRef.current;
690 const activeFitAddon = fitAddonRef.current;
691 if (!activeTerminal || !activeFitAddon) return;
692 const wasAtBottom =
693 activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
694 fitTerminalSafely(activeFitAddon);
695 if (wasAtBottom) {
696 activeTerminal.scrollToBottom();
697 }
698 void api.terminal
699 .resize({
700 threadId,
701 terminalId,
702 cols: activeTerminal.cols,
703 rows: activeTerminal.rows,
704 })
705 .catch(() => undefined);
706 }, 30);
707 attachTerminal();
708
709 return () => {
710 disposed = true;
711 unsubscribeAttach?.();
712 unsubscribeAttach = null;
713 window.clearTimeout(fitTimer);
714 inputDisposable.dispose();
715 selectionDisposable.dispose();
716 terminalLinksDisposable.dispose();
717 if (selectionActionTimerRef.current !== null) {
718 window.clearTimeout(selectionActionTimerRef.current);
719 }
720 window.removeEventListener("mouseup", handleMouseUp);
721 mount.removeEventListener("pointerdown", handlePointerDown);
722 themeObserver.disconnect();
723 terminalRef.current = null;
724 fitAddonRef.current = null;
725 terminal.dispose();
726 };
727 // autoFocus is intentionally omitted;
728 // it is only read at mount time and must not trigger terminal teardown/recreation.
729 // eslint-disable-next-line react-hooks/exhaustive-deps
730 }, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]);
731
732 useEffect(() => {
733 if (!autoFocus) return;
734 const terminal = terminalRef.current;
735 if (!terminal) return;
736 const frame = window.requestAnimationFrame(() => {
737 terminal.focus();
738 });
739 return () => {
740 window.cancelAnimationFrame(frame);
741 };
742 }, [autoFocus, focusRequestId]);
743
744 useEffect(() => {
745 const api = readEnvironmentApi(environmentId);
746 const terminal = terminalRef.current;
747 const fitAddon = fitAddonRef.current;
748 if (!api || !terminal || !fitAddon) return;
749 const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
750 const frame = window.requestAnimationFrame(() => {
751 fitTerminalSafely(fitAddon);
752 if (wasAtBottom) {
753 terminal.scrollToBottom();
754 }
755 void api.terminal
756 .resize({
757 threadId,
758 terminalId,
759 cols: terminal.cols,
760 rows: terminal.rows,
761 })
762 .catch(() => undefined);
763 });
764 return () => {
765 window.cancelAnimationFrame(frame);
766 };
767 }, [drawerHeight, environmentId, resizeEpoch, terminalId, threadId]);
768 return (
769 <div
770 ref={containerRef}
771 className="relative h-full w-full overflow-hidden rounded-[4px] bg-background"
772 />
773 );
774}
775
776interface ThreadTerminalDrawerProps {
777 threadRef: ScopedThreadRef;
778 threadId: ThreadId;
779 cwd: string;
780 worktreePath?: string | null;
781 runtimeEnv?: Record<string, string>;
782 visible?: boolean;
783 height: number;
784 terminalIds: string[];
785 activeTerminalId: string;
786 terminalGroups: ThreadTerminalGroup[];
787 activeTerminalGroupId: string;
788 focusRequestId: number;
789 onSplitTerminal: () => void;
790 onNewTerminal: () => void;
791 splitShortcutLabel?: string | undefined;
792 newShortcutLabel?: string | undefined;
793 closeShortcutLabel?: string | undefined;
794 onActiveTerminalChange: (terminalId: string) => void;
795 onCloseTerminal: (terminalId: string) => void;
796 onHeightChange: (height: number) => void;
797 onAddTerminalContext: (selection: TerminalContextSelection) => void;
798 keybindings: ResolvedKeybindingsConfig;
799 /** Prefer server-provided tab titles when present (e.g. active subprocess name). */
800 terminalLabelsById?: ReadonlyMap<string, string>;
801 /** Prefer per-session launch locations when the server already knows a terminal. */
802 terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>;
803}
804
805interface TerminalActionButtonProps {
806 label: string;
807 className: string;
808 onClick: () => void;
809 children: ReactNode;
810}
811
812function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
813 return (
814 <Popover>
815 <PopoverTrigger
816 openOnHover
817 render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
818 >
819 {children}
820 </PopoverTrigger>
821 <PopoverPopup
822 tooltipStyle
823 side="bottom"
824 sideOffset={6}
825 align="center"
826 className="pointer-events-none select-none"
827 >
828 {label}
829 </PopoverPopup>
830 </Popover>
831 );
832}
833
834export default function ThreadTerminalDrawer({
835 threadRef,
836 threadId,
837 cwd,
838 worktreePath,
839 runtimeEnv,
840 visible = true,
841 height,
842 terminalIds,
843 activeTerminalId,
844 terminalGroups,
845 activeTerminalGroupId,
846 focusRequestId,
847 onSplitTerminal,
848 onNewTerminal,
849 splitShortcutLabel,
850 newShortcutLabel,
851 closeShortcutLabel,
852 onActiveTerminalChange,
853 onCloseTerminal,
854 onHeightChange,
855 onAddTerminalContext,
856 keybindings,
857 terminalLabelsById,
858 terminalLaunchLocationsById,
859}: ThreadTerminalDrawerProps) {
860 const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
861 const [resizeEpoch, setResizeEpoch] = useState(0);
862 const drawerHeightRef = useRef(drawerHeight);
863 const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
864 const onHeightChangeRef = useRef(onHeightChange);
865 const resizeStateRef = useRef<{
866 pointerId: number;
867 startY: number;
868 startHeight: number;
869 } | null>(null);
870 const didResizeDuringDragRef = useRef(false);
871
872 const normalizedTerminalIds = useMemo(() => {
873 const normalizedIds: string[] = [];
874 const seen = new Set<string>();
875 for (const id of terminalIds) {
876 const trimmedId = id.trim();
877 if (trimmedId.length === 0 || seen.has(trimmedId)) continue;
878 seen.add(trimmedId);
879 normalizedIds.push(trimmedId);
880 }
881 return normalizedIds;
882 }, [terminalIds]);
883
884 const resolvedActiveTerminalId =
885 normalizedTerminalIds.length === 0
886 ? ""
887 : normalizedTerminalIds.includes(activeTerminalId)
888 ? activeTerminalId
889 : (normalizedTerminalIds[0] ?? "");
890
891 const resolvedTerminalGroups = useMemo(() => {
892 if (normalizedTerminalIds.length === 0) {
893 return [];
894 }
895 const validTerminalIdSet = new Set(normalizedTerminalIds);
896 const assignedTerminalIds = new Set<string>();
897 const usedGroupIds = new Set<string>();
898 const nextGroups: ThreadTerminalGroup[] = [];
899
900 const assignUniqueGroupId = (groupId: string): string => {
901 if (!usedGroupIds.has(groupId)) {
902 usedGroupIds.add(groupId);
903 return groupId;
904 }
905 let suffix = 2;
906 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
907 suffix += 1;
908 }
909 const uniqueGroupId = `${groupId}-${suffix}`;
910 usedGroupIds.add(uniqueGroupId);
911 return uniqueGroupId;
912 };
913
914 for (const terminalGroup of terminalGroups) {
915 const nextTerminalIds: string[] = [];
916 const seenGroupTerminalIds = new Set<string>();
917 for (const id of terminalGroup.terminalIds) {
918 const terminalId = id.trim();
919 if (terminalId.length === 0) continue;
920 if (seenGroupTerminalIds.has(terminalId)) continue;
921 seenGroupTerminalIds.add(terminalId);
922 if (!validTerminalIdSet.has(terminalId)) continue;
923 if (assignedTerminalIds.has(terminalId)) continue;
924 nextTerminalIds.push(terminalId);
925 }
926 if (nextTerminalIds.length === 0) continue;
927
928 for (const terminalId of nextTerminalIds) {
929 assignedTerminalIds.add(terminalId);
930 }
931
932 const baseGroupId =
933 terminalGroup.id.trim().length > 0
934 ? terminalGroup.id.trim()
935 : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`;
936 nextGroups.push({
937 id: assignUniqueGroupId(baseGroupId),
938 terminalIds: nextTerminalIds,
939 });
940 }
941
942 for (const terminalId of normalizedTerminalIds) {
943 if (assignedTerminalIds.has(terminalId)) continue;
944 nextGroups.push({
945 id: assignUniqueGroupId(`group-${terminalId}`),
946 terminalIds: [terminalId],
947 });
948 }
949
950 const terminalOrderIndex = new Map(
951 normalizedTerminalIds.map((id, index) => [id, index] as const),
952 );
953 nextGroups.sort((left, right) => {
954 const rank = (ids: readonly string[]) =>
955 Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY));
956 return rank(left.terminalIds) - rank(right.terminalIds);
957 });
958
959 return nextGroups;
960 }, [normalizedTerminalIds, terminalGroups]);
961
962 const resolvedActiveGroupIndex = useMemo(() => {
963 const indexById = resolvedTerminalGroups.findIndex(
964 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
965 );
966 if (indexById >= 0) return indexById;
967 const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
968 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
969 );
970 return indexByTerminal >= 0 ? indexByTerminal : 0;
971 }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
972
973 const visibleTerminalIds =
974 resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ??
975 (normalizedTerminalIds.length > 0 ? [resolvedActiveTerminalId] : []);
976 const hasTerminalSidebar = normalizedTerminalIds.length > 1;
977 const isSplitView = visibleTerminalIds.length > 1;
978 const showGroupHeaders =
979 resolvedTerminalGroups.length > 1 ||
980 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
981 const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
982 const terminalLabelById = useMemo(() => {
983 const next = new Map<string, string>();
984 for (const terminalId of normalizedTerminalIds) {
985 next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId));
986 }
987 return next;
988 }, [normalizedTerminalIds, terminalLabelsById]);
989 const resolveTerminalLaunchLocation = useCallback(
990 (terminalId: string): TerminalLaunchLocation => {
991 return (
992 terminalLaunchLocationsById?.get(terminalId) ?? {
993 cwd,
994 ...(worktreePath !== undefined ? { worktreePath } : {}),
995 ...(runtimeEnv ? { runtimeEnv } : {}),
996 }
997 );
998 },
999 [cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
1000 );
1001 const splitTerminalActionLabel = hasReachedSplitLimit
1002 ? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
1003 : splitShortcutLabel
1004 ? `Split Terminal (${splitShortcutLabel})`
1005 : "Split Terminal";
1006 const newTerminalActionLabel = newShortcutLabel
1007 ? `New Terminal (${newShortcutLabel})`
1008 : "New Terminal";
1009 const closeTerminalActionLabel = closeShortcutLabel
1010 ? `Close Terminal (${closeShortcutLabel})`
1011 : "Close Terminal";
1012 const onSplitTerminalAction = useCallback(() => {
1013 if (hasReachedSplitLimit) return;
1014 onSplitTerminal();
1015 }, [hasReachedSplitLimit, onSplitTerminal]);
1016 const onNewTerminalAction = useCallback(() => {
1017 onNewTerminal();
1018 }, [onNewTerminal]);
1019
1020 useEffect(() => {
1021 onHeightChangeRef.current = onHeightChange;
1022 }, [onHeightChange]);
1023
1024 useEffect(() => {
1025 drawerHeightRef.current = drawerHeight;
1026 }, [drawerHeight]);
1027
1028 const syncHeight = useCallback((nextHeight: number) => {
1029 const clampedHeight = clampDrawerHeight(nextHeight);
1030 if (lastSyncedHeightRef.current === clampedHeight) return;
1031 lastSyncedHeightRef.current = clampedHeight;
1032 onHeightChangeRef.current(clampedHeight);
1033 }, []);
1034
1035 useEffect(() => {
1036 const clampedHeight = clampDrawerHeight(height);
1037 setDrawerHeight(clampedHeight);
1038 drawerHeightRef.current = clampedHeight;
1039 lastSyncedHeightRef.current = clampedHeight;
1040 }, [height, threadId]);
1041
1042 const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1043 if (event.button !== 0) return;
1044 event.preventDefault();
1045 event.currentTarget.setPointerCapture(event.pointerId);
1046 didResizeDuringDragRef.current = false;
1047 resizeStateRef.current = {
1048 pointerId: event.pointerId,
1049 startY: event.clientY,
1050 startHeight: drawerHeightRef.current,
1051 };
1052 }, []);
1053
1054 const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1055 const resizeState = resizeStateRef.current;
1056 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1057 event.preventDefault();
1058 const clampedHeight = clampDrawerHeight(
1059 resizeState.startHeight + (resizeState.startY - event.clientY),
1060 );
1061 if (clampedHeight === drawerHeightRef.current) {
1062 return;
1063 }
1064 didResizeDuringDragRef.current = true;
1065 drawerHeightRef.current = clampedHeight;
1066 setDrawerHeight(clampedHeight);
1067 }, []);
1068
1069 const handleResizePointerEnd = useCallback(
1070 (event: ReactPointerEvent<HTMLDivElement>) => {
1071 const resizeState = resizeStateRef.current;
1072 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1073 resizeStateRef.current = null;
1074 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
1075 event.currentTarget.releasePointerCapture(event.pointerId);
1076 }
1077 if (!didResizeDuringDragRef.current) {
1078 return;
1079 }
1080 syncHeight(drawerHeightRef.current);
1081 setResizeEpoch((value) => value + 1);
1082 },
1083 [syncHeight],
1084 );
1085
1086 useEffect(() => {
1087 if (!visible) {
1088 return;
1089 }
1090
1091 const onWindowResize = () => {
1092 const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
1093 const changed = clampedHeight !== drawerHeightRef.current;
1094 if (changed) {
1095 setDrawerHeight(clampedHeight);
1096 drawerHeightRef.current = clampedHeight;
1097 }
1098 if (!resizeStateRef.current) {
1099 syncHeight(clampedHeight);
1100 }
1101 setResizeEpoch((value) => value + 1);
1102 };
1103 window.addEventListener("resize", onWindowResize);
1104 return () => {
1105 window.removeEventListener("resize", onWindowResize);
1106 };
1107 }, [syncHeight, visible]);
1108
1109 useEffect(() => {
1110 if (!visible) {
1111 return;
1112 }
1113 setResizeEpoch((value) => value + 1);
1114 }, [visible]);
1115
1116 useEffect(() => {
1117 return () => {
1118 syncHeight(drawerHeightRef.current);
1119 };
1120 }, [syncHeight]);
1121
1122 if (normalizedTerminalIds.length === 0) {
1123 return (
1124 <aside
1125 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
1126 style={{ height: `${drawerHeight}px` }}
1127 >
1128 <div
1129 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
1130 onPointerDown={handleResizePointerDown}
1131 onPointerMove={handleResizePointerMove}
1132 onPointerUp={handleResizePointerEnd}
1133 onPointerCancel={handleResizePointerEnd}
1134 />
1135 <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">
1136 <p>No terminal sessions for this thread yet.</p>
1137 <button
1138 type="button"
1139 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"
1140 onClick={onNewTerminalAction}
1141 >
1142 {newTerminalActionLabel}
1143 </button>
1144 </div>
1145 </aside>
1146 );
1147 }
1148
1149 const activeTerminalLaunchLocation = resolveTerminalLaunchLocation(resolvedActiveTerminalId);
1150
1151 return (
1152 <aside
1153 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
1154 style={{ height: `${drawerHeight}px` }}
1155 >
1156 <div
1157 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
1158 onPointerDown={handleResizePointerDown}
1159 onPointerMove={handleResizePointerMove}
1160 onPointerUp={handleResizePointerEnd}
1161 onPointerCancel={handleResizePointerEnd}
1162 />
1163
1164 {!hasTerminalSidebar && (
1165 <div className="pointer-events-none absolute right-2 top-2 z-20">
1166 <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
1167 <TerminalActionButton
1168 className={`p-1 text-foreground/90 transition-colors ${
1169 hasReachedSplitLimit
1170 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1171 : "hover:bg-accent"
1172 }`}
1173 onClick={onSplitTerminalAction}
1174 label={splitTerminalActionLabel}
1175 >
1176 <SquareSplitHorizontal className="size-3.25" />
1177 </TerminalActionButton>
1178 <div className="h-4 w-px bg-border/80" />
1179 <TerminalActionButton
1180 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1181 onClick={onNewTerminalAction}
1182 label={newTerminalActionLabel}
1183 >
1184 <Plus className="size-3.25" />
1185 </TerminalActionButton>
1186 <div className="h-4 w-px bg-border/80" />
1187 <TerminalActionButton
1188 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1189 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1190 label={closeTerminalActionLabel}
1191 >
1192 <Trash2 className="size-3.25" />
1193 </TerminalActionButton>
1194 </div>
1195 </div>
1196 )}
1197
1198 <div className="min-h-0 w-full flex-1">
1199 <div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
1200 <div className="min-w-0 flex-1">
1201 {isSplitView ? (
1202 <div
1203 className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
1204 style={{
1205 gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
1206 }}
1207 >
1208 {visibleTerminalIds.map((terminalId) => {
1209 const terminalLaunchLocation = resolveTerminalLaunchLocation(terminalId);
1210 return (
1211 <div
1212 key={terminalId}
1213 className={`min-h-0 min-w-0 border-l first:border-l-0 ${
1214 terminalId === resolvedActiveTerminalId
1215 ? "border-border"
1216 : "border-border/70"
1217 }`}
1218 onMouseDown={() => {
1219 if (terminalId !== resolvedActiveTerminalId) {
1220 onActiveTerminalChange(terminalId);
1221 }
1222 }}
1223 >
1224 <div className="h-full p-1">
1225 <TerminalViewport
1226 threadRef={threadRef}
1227 threadId={threadId}
1228 terminalId={terminalId}
1229 terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
1230 cwd={terminalLaunchLocation.cwd}
1231 {...(terminalLaunchLocation.worktreePath !== undefined
1232 ? { worktreePath: terminalLaunchLocation.worktreePath }
1233 : {})}
1234 {...(terminalLaunchLocation.runtimeEnv
1235 ? { runtimeEnv: terminalLaunchLocation.runtimeEnv }
1236 : {})}
1237 onSessionExited={() => onCloseTerminal(terminalId)}
1238 onAddTerminalContext={onAddTerminalContext}
1239 focusRequestId={focusRequestId}
1240 autoFocus={terminalId === resolvedActiveTerminalId}
1241 resizeEpoch={resizeEpoch}
1242 drawerHeight={drawerHeight}
1243 keybindings={keybindings}
1244 />
1245 </div>
1246 </div>
1247 );
1248 })}
1249 </div>
1250 ) : (
1251 <div className="h-full p-1">
1252 <TerminalViewport
1253 key={resolvedActiveTerminalId}
1254 threadRef={threadRef}
1255 threadId={threadId}
1256 terminalId={resolvedActiveTerminalId}
1257 terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
1258 cwd={activeTerminalLaunchLocation.cwd}
1259 {...(activeTerminalLaunchLocation.worktreePath !== undefined
1260 ? { worktreePath: activeTerminalLaunchLocation.worktreePath }
1261 : {})}
1262 {...(activeTerminalLaunchLocation.runtimeEnv
1263 ? { runtimeEnv: activeTerminalLaunchLocation.runtimeEnv }
1264 : {})}
1265 onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
1266 onAddTerminalContext={onAddTerminalContext}
1267 focusRequestId={focusRequestId}
1268 autoFocus
1269 resizeEpoch={resizeEpoch}
1270 drawerHeight={drawerHeight}
1271 keybindings={keybindings}
1272 />
1273 </div>
1274 )}
1275 </div>
1276
1277 {hasTerminalSidebar && (
1278 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
1279 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
1280 <div className="inline-flex h-full items-stretch">
1281 <TerminalActionButton
1282 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
1283 hasReachedSplitLimit
1284 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1285 : "hover:bg-accent/70"
1286 }`}
1287 onClick={onSplitTerminalAction}
1288 label={splitTerminalActionLabel}
1289 >
1290 <SquareSplitHorizontal className="size-3.25" />
1291 </TerminalActionButton>
1292 <TerminalActionButton
1293 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1294 onClick={onNewTerminalAction}
1295 label={newTerminalActionLabel}
1296 >
1297 <Plus className="size-3.25" />
1298 </TerminalActionButton>
1299 <TerminalActionButton
1300 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1301 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1302 label={closeTerminalActionLabel}
1303 >
1304 <Trash2 className="size-3.25" />
1305 </TerminalActionButton>
1306 </div>
1307 </div>
1308
1309 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
1310 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
1311 const isGroupActive =
1312 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
1313 const groupActiveTerminalId = isGroupActive
1314 ? resolvedActiveTerminalId
1315 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
1316
1317 return (
1318 <div key={terminalGroup.id} className="pb-0.5">
1319 {showGroupHeaders && (
1320 <button
1321 type="button"
1322 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
1323 isGroupActive
1324 ? "bg-accent/70 text-foreground"
1325 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1326 }`}
1327 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
1328 >
1329 Group {groupIndex + 1}
1330 </button>
1331 )}
1332
1333 <div
1334 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
1335 >
1336 {terminalGroup.terminalIds.map((terminalId) => {
1337 const isActive = terminalId === resolvedActiveTerminalId;
1338 const closeTerminalLabel = `Close ${
1339 terminalLabelById.get(terminalId) ?? "terminal"
1340 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
1341 return (
1342 <div
1343 key={terminalId}
1344 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
1345 isActive
1346 ? "bg-accent text-foreground"
1347 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1348 }`}
1349 >
1350 {showGroupHeaders && (
1351 <span className="text-[10px] text-muted-foreground/80">└</span>
1352 )}
1353 <button
1354 type="button"
1355 className="flex min-w-0 flex-1 items-center gap-1 text-left"
1356 onClick={() => onActiveTerminalChange(terminalId)}
1357 >
1358 <TerminalSquare className="size-3 shrink-0" />
1359 <span className="truncate">
1360 {terminalLabelById.get(terminalId) ?? "Terminal"}
1361 </span>
1362 </button>
1363 {normalizedTerminalIds.length > 1 && (
1364 <Popover>
1365 <PopoverTrigger
1366 openOnHover
1367 render={
1368 <button
1369 type="button"
1370 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"
1371 onClick={() => onCloseTerminal(terminalId)}
1372 aria-label={closeTerminalLabel}
1373 />
1374 }
1375 >
1376 <XIcon className="size-2.5" />
1377 </PopoverTrigger>
1378 <PopoverPopup
1379 tooltipStyle
1380 side="bottom"
1381 sideOffset={6}
1382 align="center"
1383 className="pointer-events-none select-none"
1384 >
1385 {closeTerminalLabel}
1386 </PopoverPopup>
1387 </Popover>
1388 )}
1389 </div>
1390 );
1391 })}
1392 </div>
1393 </div>
1394 );
1395 })}
1396 </div>
1397 </aside>
1398 )}
1399 </div>
1400 </div>
1401 </aside>
1402 );
1403}