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