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