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

ThreadTerminalDrawer.tsx

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