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 {
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";
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 api.shell.openInEditor(target, preferredTerminalEditor()).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 }, [cwd, runtimeEnv, terminalId, threadId]);
393
394 useEffect(() => {
395 if (!autoFocus) return;
396 const terminal = terminalRef.current;
397 if (!terminal) return;
398 const frame = window.requestAnimationFrame(() => {
399 terminal.focus();
400 });
401 return () => {
402 window.cancelAnimationFrame(frame);
403 };
404 }, [autoFocus, focusRequestId]);
405
406 useEffect(() => {
407 const api = readNativeApi();
408 const terminal = terminalRef.current;
409 const fitAddon = fitAddonRef.current;
410 if (!api || !terminal || !fitAddon) return;
411 const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
412 const frame = window.requestAnimationFrame(() => {
413 fitAddon.fit();
414 if (wasAtBottom) {
415 terminal.scrollToBottom();
416 }
417 void api.terminal
418 .resize({
419 threadId,
420 terminalId,
421 cols: terminal.cols,
422 rows: terminal.rows,
423 })
424 .catch(() => undefined);
425 });
426 return () => {
427 window.cancelAnimationFrame(frame);
428 };
429 }, [drawerHeight, resizeEpoch, terminalId, threadId]);
430 return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
431}
432
433interface ThreadTerminalDrawerProps {
434 threadId: ThreadId;
435 cwd: string;
436 runtimeEnv?: Record<string, string>;
437 height: number;
438 terminalIds: string[];
439 activeTerminalId: string;
440 terminalGroups: ThreadTerminalGroup[];
441 activeTerminalGroupId: string;
442 focusRequestId: number;
443 onSplitTerminal: () => void;
444 onNewTerminal: () => void;
445 splitShortcutLabel?: string | undefined;
446 newShortcutLabel?: string | undefined;
447 closeShortcutLabel?: string | undefined;
448 onActiveTerminalChange: (terminalId: string) => void;
449 onCloseTerminal: (terminalId: string) => void;
450 onHeightChange: (height: number) => void;
451}
452
453interface TerminalActionButtonProps {
454 label: string;
455 className: string;
456 onClick: () => void;
457 children: ReactNode;
458}
459
460function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
461 return (
462 <Popover>
463 <PopoverTrigger
464 openOnHover
465 render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
466 >
467 {children}
468 </PopoverTrigger>
469 <PopoverPopup
470 tooltipStyle
471 side="bottom"
472 sideOffset={6}
473 align="center"
474 className="pointer-events-none select-none"
475 >
476 {label}
477 </PopoverPopup>
478 </Popover>
479 );
480}
481
482export default function ThreadTerminalDrawer({
483 threadId,
484 cwd,
485 runtimeEnv,
486 height,
487 terminalIds,
488 activeTerminalId,
489 terminalGroups,
490 activeTerminalGroupId,
491 focusRequestId,
492 onSplitTerminal,
493 onNewTerminal,
494 splitShortcutLabel,
495 newShortcutLabel,
496 closeShortcutLabel,
497 onActiveTerminalChange,
498 onCloseTerminal,
499 onHeightChange,
500}: ThreadTerminalDrawerProps) {
501 const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
502 const [resizeEpoch, setResizeEpoch] = useState(0);
503 const drawerHeightRef = useRef(drawerHeight);
504 const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
505 const onHeightChangeRef = useRef(onHeightChange);
506 const resizeStateRef = useRef<{
507 pointerId: number;
508 startY: number;
509 startHeight: number;
510 } | null>(null);
511 const didResizeDuringDragRef = useRef(false);
512
513 const normalizedTerminalIds = useMemo(() => {
514 const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
515 return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
516 }, [terminalIds]);
517
518 const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
519 ? activeTerminalId
520 : (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
521
522 const resolvedTerminalGroups = useMemo(() => {
523 const validTerminalIdSet = new Set(normalizedTerminalIds);
524 const assignedTerminalIds = new Set<string>();
525 const usedGroupIds = new Set<string>();
526 const nextGroups: ThreadTerminalGroup[] = [];
527
528 const assignUniqueGroupId = (groupId: string): string => {
529 if (!usedGroupIds.has(groupId)) {
530 usedGroupIds.add(groupId);
531 return groupId;
532 }
533 let suffix = 2;
534 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
535 suffix += 1;
536 }
537 const uniqueGroupId = `${groupId}-${suffix}`;
538 usedGroupIds.add(uniqueGroupId);
539 return uniqueGroupId;
540 };
541
542 for (const terminalGroup of terminalGroups) {
543 const nextTerminalIds = [
544 ...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
545 ].filter((terminalId) => {
546 if (!validTerminalIdSet.has(terminalId)) return false;
547 if (assignedTerminalIds.has(terminalId)) return false;
548 return true;
549 });
550 if (nextTerminalIds.length === 0) continue;
551
552 for (const terminalId of nextTerminalIds) {
553 assignedTerminalIds.add(terminalId);
554 }
555
556 const baseGroupId =
557 terminalGroup.id.trim().length > 0
558 ? terminalGroup.id.trim()
559 : `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
560 nextGroups.push({
561 id: assignUniqueGroupId(baseGroupId),
562 terminalIds: nextTerminalIds,
563 });
564 }
565
566 for (const terminalId of normalizedTerminalIds) {
567 if (assignedTerminalIds.has(terminalId)) continue;
568 nextGroups.push({
569 id: assignUniqueGroupId(`group-${terminalId}`),
570 terminalIds: [terminalId],
571 });
572 }
573
574 if (nextGroups.length > 0) {
575 return nextGroups;
576 }
577
578 return [
579 {
580 id: `group-${resolvedActiveTerminalId}`,
581 terminalIds: [resolvedActiveTerminalId],
582 },
583 ];
584 }, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
585
586 const resolvedActiveGroupIndex = useMemo(() => {
587 const indexById = resolvedTerminalGroups.findIndex(
588 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
589 );
590 if (indexById >= 0) return indexById;
591 const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
592 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
593 );
594 return indexByTerminal >= 0 ? indexByTerminal : 0;
595 }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
596
597 const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
598 resolvedActiveTerminalId,
599 ];
600 const hasTerminalSidebar = normalizedTerminalIds.length > 1;
601 const isSplitView = visibleTerminalIds.length > 1;
602 const showGroupHeaders =
603 resolvedTerminalGroups.length > 1 ||
604 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
605 const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
606 const terminalLabelById = useMemo(
607 () =>
608 new Map(
609 normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
610 ),
611 [normalizedTerminalIds],
612 );
613 const splitTerminalActionLabel = hasReachedTerminalLimit
614 ? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
615 : splitShortcutLabel
616 ? `Split Terminal (${splitShortcutLabel})`
617 : "Split Terminal";
618 const newTerminalActionLabel = hasReachedTerminalLimit
619 ? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
620 : newShortcutLabel
621 ? `New Terminal (${newShortcutLabel})`
622 : "New Terminal";
623 const closeTerminalActionLabel = closeShortcutLabel
624 ? `Close Terminal (${closeShortcutLabel})`
625 : "Close Terminal";
626 const onSplitTerminalAction = useCallback(() => {
627 if (hasReachedTerminalLimit) return;
628 onSplitTerminal();
629 }, [hasReachedTerminalLimit, onSplitTerminal]);
630 const onNewTerminalAction = useCallback(() => {
631 if (hasReachedTerminalLimit) return;
632 onNewTerminal();
633 }, [hasReachedTerminalLimit, 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 hasReachedTerminalLimit
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 ${
756 hasReachedTerminalLimit
757 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
758 : "hover:bg-accent"
759 }`}
760 onClick={onNewTerminalAction}
761 label={newTerminalActionLabel}
762 >
763 <Plus className="size-3.25" />
764 </TerminalActionButton>
765 <div className="h-4 w-px bg-border/80" />
766 <TerminalActionButton
767 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
768 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
769 label={closeTerminalActionLabel}
770 >
771 <Trash2 className="size-3.25" />
772 </TerminalActionButton>
773 </div>
774 </div>
775 )}
776
777 <div className="min-h-0 w-full flex-1">
778 <div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
779 <div className="min-w-0 flex-1">
780 {isSplitView ? (
781 <div
782 className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
783 style={{
784 gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
785 }}
786 >
787 {visibleTerminalIds.map((terminalId) => (
788 <div
789 key={terminalId}
790 className={`min-h-0 min-w-0 border-l first:border-l-0 ${
791 terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
792 }`}
793 onMouseDown={() => {
794 if (terminalId !== resolvedActiveTerminalId) {
795 onActiveTerminalChange(terminalId);
796 }
797 }}
798 >
799 <div className="h-full p-1">
800 <TerminalViewport
801 threadId={threadId}
802 terminalId={terminalId}
803 cwd={cwd}
804 {...(runtimeEnv ? { runtimeEnv } : {})}
805 onSessionExited={() => onCloseTerminal(terminalId)}
806 focusRequestId={focusRequestId}
807 autoFocus={terminalId === resolvedActiveTerminalId}
808 resizeEpoch={resizeEpoch}
809 drawerHeight={drawerHeight}
810 />
811 </div>
812 </div>
813 ))}
814 </div>
815 ) : (
816 <div className="h-full p-1">
817 <TerminalViewport
818 key={resolvedActiveTerminalId}
819 threadId={threadId}
820 terminalId={resolvedActiveTerminalId}
821 cwd={cwd}
822 {...(runtimeEnv ? { runtimeEnv } : {})}
823 onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
824 focusRequestId={focusRequestId}
825 autoFocus
826 resizeEpoch={resizeEpoch}
827 drawerHeight={drawerHeight}
828 />
829 </div>
830 )}
831 </div>
832
833 {hasTerminalSidebar && (
834 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
835 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
836 <div className="inline-flex h-full items-stretch">
837 <TerminalActionButton
838 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
839 hasReachedTerminalLimit
840 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
841 : "hover:bg-accent/70"
842 }`}
843 onClick={onSplitTerminalAction}
844 label={splitTerminalActionLabel}
845 >
846 <SquareSplitHorizontal className="size-3.25" />
847 </TerminalActionButton>
848 <TerminalActionButton
849 className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
850 hasReachedTerminalLimit
851 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
852 : "hover:bg-accent/70"
853 }`}
854 onClick={onNewTerminalAction}
855 label={newTerminalActionLabel}
856 >
857 <Plus className="size-3.25" />
858 </TerminalActionButton>
859 <TerminalActionButton
860 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
861 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
862 label={closeTerminalActionLabel}
863 >
864 <Trash2 className="size-3.25" />
865 </TerminalActionButton>
866 </div>
867 </div>
868
869 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
870 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
871 const isGroupActive =
872 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
873 const groupActiveTerminalId = isGroupActive
874 ? resolvedActiveTerminalId
875 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
876
877 return (
878 <div key={terminalGroup.id} className="pb-0.5">
879 {showGroupHeaders && (
880 <button
881 type="button"
882 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
883 isGroupActive
884 ? "bg-accent/70 text-foreground"
885 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
886 }`}
887 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
888 >
889 {terminalGroup.terminalIds.length > 1
890 ? `Split ${groupIndex + 1}`
891 : `Terminal ${groupIndex + 1}`}
892 </button>
893 )}
894
895 <div
896 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
897 >
898 {terminalGroup.terminalIds.map((terminalId) => {
899 const isActive = terminalId === resolvedActiveTerminalId;
900 const closeTerminalLabel = `Close ${
901 terminalLabelById.get(terminalId) ?? "terminal"
902 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
903 return (
904 <div
905 key={terminalId}
906 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
907 isActive
908 ? "bg-accent text-foreground"
909 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
910 }`}
911 >
912 {showGroupHeaders && (
913 <span className="text-[10px] text-muted-foreground/80">└</span>
914 )}
915 <button
916 type="button"
917 className="flex min-w-0 flex-1 items-center gap-1 text-left"
918 onClick={() => onActiveTerminalChange(terminalId)}
919 >
920 <TerminalSquare className="size-3 shrink-0" />
921 <span className="truncate">
922 {terminalLabelById.get(terminalId) ?? "Terminal"}
923 </span>
924 </button>
925 {normalizedTerminalIds.length > 1 && (
926 <Popover>
927 <PopoverTrigger
928 openOnHover
929 render={
930 <button
931 type="button"
932 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"
933 onClick={() => onCloseTerminal(terminalId)}
934 aria-label={closeTerminalLabel}
935 />
936 }
937 >
938 <XIcon className="size-2.5" />
939 </PopoverTrigger>
940 <PopoverPopup
941 tooltipStyle
942 side="bottom"
943 sideOffset={6}
944 align="center"
945 className="pointer-events-none select-none"
946 >
947 {closeTerminalLabel}
948 </PopoverPopup>
949 </Popover>
950 )}
951 </div>
952 );
953 })}
954 </div>
955 </div>
956 );
957 })}
958 </div>
959 </aside>
960 )}
961 </div>
962 </div>
963 </aside>
964 );
965}