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