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