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 // 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 hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
609 const terminalLabelById = useMemo(
610 () =>
611 new Map(
612 normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
613 ),
614 [normalizedTerminalIds],
615 );
616 const splitTerminalActionLabel = hasReachedTerminalLimit
617 ? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
618 : splitShortcutLabel
619 ? `Split Terminal (${splitShortcutLabel})`
620 : "Split Terminal";
621 const newTerminalActionLabel = hasReachedTerminalLimit
622 ? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
623 : newShortcutLabel
624 ? `New Terminal (${newShortcutLabel})`
625 : "New Terminal";
626 const closeTerminalActionLabel = closeShortcutLabel
627 ? `Close Terminal (${closeShortcutLabel})`
628 : "Close Terminal";
629 const onSplitTerminalAction = useCallback(() => {
630 if (hasReachedTerminalLimit) return;
631 onSplitTerminal();
632 }, [hasReachedTerminalLimit, onSplitTerminal]);
633 const onNewTerminalAction = useCallback(() => {
634 if (hasReachedTerminalLimit) return;
635 onNewTerminal();
636 }, [hasReachedTerminalLimit, onNewTerminal]);
637
638 useEffect(() => {
639 onHeightChangeRef.current = onHeightChange;
640 }, [onHeightChange]);
641
642 useEffect(() => {
643 drawerHeightRef.current = drawerHeight;
644 }, [drawerHeight]);
645
646 const syncHeight = useCallback((nextHeight: number) => {
647 const clampedHeight = clampDrawerHeight(nextHeight);
648 if (lastSyncedHeightRef.current === clampedHeight) return;
649 lastSyncedHeightRef.current = clampedHeight;
650 onHeightChangeRef.current(clampedHeight);
651 }, []);
652
653 useEffect(() => {
654 const clampedHeight = clampDrawerHeight(height);
655 setDrawerHeight(clampedHeight);
656 drawerHeightRef.current = clampedHeight;
657 lastSyncedHeightRef.current = clampedHeight;
658 }, [height, threadId]);
659
660 const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
661 if (event.button !== 0) return;
662 event.preventDefault();
663 event.currentTarget.setPointerCapture(event.pointerId);
664 didResizeDuringDragRef.current = false;
665 resizeStateRef.current = {
666 pointerId: event.pointerId,
667 startY: event.clientY,
668 startHeight: drawerHeightRef.current,
669 };
670 }, []);
671
672 const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
673 const resizeState = resizeStateRef.current;
674 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
675 event.preventDefault();
676 const clampedHeight = clampDrawerHeight(
677 resizeState.startHeight + (resizeState.startY - event.clientY),
678 );
679 if (clampedHeight === drawerHeightRef.current) {
680 return;
681 }
682 didResizeDuringDragRef.current = true;
683 drawerHeightRef.current = clampedHeight;
684 setDrawerHeight(clampedHeight);
685 }, []);
686
687 const handleResizePointerEnd = useCallback(
688 (event: ReactPointerEvent<HTMLDivElement>) => {
689 const resizeState = resizeStateRef.current;
690 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
691 resizeStateRef.current = null;
692 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
693 event.currentTarget.releasePointerCapture(event.pointerId);
694 }
695 if (!didResizeDuringDragRef.current) {
696 return;
697 }
698 syncHeight(drawerHeightRef.current);
699 setResizeEpoch((value) => value + 1);
700 },
701 [syncHeight],
702 );
703
704 useEffect(() => {
705 const onWindowResize = () => {
706 const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
707 const changed = clampedHeight !== drawerHeightRef.current;
708 if (changed) {
709 setDrawerHeight(clampedHeight);
710 drawerHeightRef.current = clampedHeight;
711 }
712 if (!resizeStateRef.current) {
713 syncHeight(clampedHeight);
714 }
715 setResizeEpoch((value) => value + 1);
716 };
717 window.addEventListener("resize", onWindowResize);
718 return () => {
719 window.removeEventListener("resize", onWindowResize);
720 };
721 }, [syncHeight]);
722
723 useEffect(() => {
724 return () => {
725 syncHeight(drawerHeightRef.current);
726 };
727 }, [syncHeight]);
728
729 return (
730 <aside
731 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
732 style={{ height: `${drawerHeight}px` }}
733 >
734 <div
735 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
736 onPointerDown={handleResizePointerDown}
737 onPointerMove={handleResizePointerMove}
738 onPointerUp={handleResizePointerEnd}
739 onPointerCancel={handleResizePointerEnd}
740 />
741
742 {!hasTerminalSidebar && (
743 <div className="pointer-events-none absolute right-2 top-2 z-20">
744 <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
745 <TerminalActionButton
746 className={`p-1 text-foreground/90 transition-colors ${
747 hasReachedTerminalLimit
748 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
749 : "hover:bg-accent"
750 }`}
751 onClick={onSplitTerminalAction}
752 label={splitTerminalActionLabel}
753 >
754 <SquareSplitHorizontal className="size-3.25" />
755 </TerminalActionButton>
756 <div className="h-4 w-px bg-border/80" />
757 <TerminalActionButton
758 className={`p-1 text-foreground/90 transition-colors ${
759 hasReachedTerminalLimit
760 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
761 : "hover:bg-accent"
762 }`}
763 onClick={onNewTerminalAction}
764 label={newTerminalActionLabel}
765 >
766 <Plus className="size-3.25" />
767 </TerminalActionButton>
768 <div className="h-4 w-px bg-border/80" />
769 <TerminalActionButton
770 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
771 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
772 label={closeTerminalActionLabel}
773 >
774 <Trash2 className="size-3.25" />
775 </TerminalActionButton>
776 </div>
777 </div>
778 )}
779
780 <div className="min-h-0 w-full flex-1">
781 <div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
782 <div className="min-w-0 flex-1">
783 {isSplitView ? (
784 <div
785 className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
786 style={{
787 gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
788 }}
789 >
790 {visibleTerminalIds.map((terminalId) => (
791 <div
792 key={terminalId}
793 className={`min-h-0 min-w-0 border-l first:border-l-0 ${
794 terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
795 }`}
796 onMouseDown={() => {
797 if (terminalId !== resolvedActiveTerminalId) {
798 onActiveTerminalChange(terminalId);
799 }
800 }}
801 >
802 <div className="h-full p-1">
803 <TerminalViewport
804 threadId={threadId}
805 terminalId={terminalId}
806 cwd={cwd}
807 {...(runtimeEnv ? { runtimeEnv } : {})}
808 onSessionExited={() => onCloseTerminal(terminalId)}
809 focusRequestId={focusRequestId}
810 autoFocus={terminalId === resolvedActiveTerminalId}
811 resizeEpoch={resizeEpoch}
812 drawerHeight={drawerHeight}
813 />
814 </div>
815 </div>
816 ))}
817 </div>
818 ) : (
819 <div className="h-full p-1">
820 <TerminalViewport
821 key={resolvedActiveTerminalId}
822 threadId={threadId}
823 terminalId={resolvedActiveTerminalId}
824 cwd={cwd}
825 {...(runtimeEnv ? { runtimeEnv } : {})}
826 onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
827 focusRequestId={focusRequestId}
828 autoFocus
829 resizeEpoch={resizeEpoch}
830 drawerHeight={drawerHeight}
831 />
832 </div>
833 )}
834 </div>
835
836 {hasTerminalSidebar && (
837 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
838 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
839 <div className="inline-flex h-full items-stretch">
840 <TerminalActionButton
841 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
842 hasReachedTerminalLimit
843 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
844 : "hover:bg-accent/70"
845 }`}
846 onClick={onSplitTerminalAction}
847 label={splitTerminalActionLabel}
848 >
849 <SquareSplitHorizontal 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 ${
853 hasReachedTerminalLimit
854 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
855 : "hover:bg-accent/70"
856 }`}
857 onClick={onNewTerminalAction}
858 label={newTerminalActionLabel}
859 >
860 <Plus className="size-3.25" />
861 </TerminalActionButton>
862 <TerminalActionButton
863 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
864 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
865 label={closeTerminalActionLabel}
866 >
867 <Trash2 className="size-3.25" />
868 </TerminalActionButton>
869 </div>
870 </div>
871
872 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
873 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
874 const isGroupActive =
875 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
876 const groupActiveTerminalId = isGroupActive
877 ? resolvedActiveTerminalId
878 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
879
880 return (
881 <div key={terminalGroup.id} className="pb-0.5">
882 {showGroupHeaders && (
883 <button
884 type="button"
885 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
886 isGroupActive
887 ? "bg-accent/70 text-foreground"
888 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
889 }`}
890 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
891 >
892 {terminalGroup.terminalIds.length > 1
893 ? `Split ${groupIndex + 1}`
894 : `Terminal ${groupIndex + 1}`}
895 </button>
896 )}
897
898 <div
899 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
900 >
901 {terminalGroup.terminalIds.map((terminalId) => {
902 const isActive = terminalId === resolvedActiveTerminalId;
903 const closeTerminalLabel = `Close ${
904 terminalLabelById.get(terminalId) ?? "terminal"
905 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
906 return (
907 <div
908 key={terminalId}
909 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
910 isActive
911 ? "bg-accent text-foreground"
912 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
913 }`}
914 >
915 {showGroupHeaders && (
916 <span className="text-[10px] text-muted-foreground/80">└</span>
917 )}
918 <button
919 type="button"
920 className="flex min-w-0 flex-1 items-center gap-1 text-left"
921 onClick={() => onActiveTerminalChange(terminalId)}
922 >
923 <TerminalSquare className="size-3 shrink-0" />
924 <span className="truncate">
925 {terminalLabelById.get(terminalId) ?? "Terminal"}
926 </span>
927 </button>
928 {normalizedTerminalIds.length > 1 && (
929 <Popover>
930 <PopoverTrigger
931 openOnHover
932 render={
933 <button
934 type="button"
935 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"
936 onClick={() => onCloseTerminal(terminalId)}
937 aria-label={closeTerminalLabel}
938 />
939 }
940 >
941 <XIcon className="size-2.5" />
942 </PopoverTrigger>
943 <PopoverPopup
944 tooltipStyle
945 side="bottom"
946 sideOffset={6}
947 align="center"
948 className="pointer-events-none select-none"
949 >
950 {closeTerminalLabel}
951 </PopoverPopup>
952 </Popover>
953 )}
954 </div>
955 );
956 })}
957 </div>
958 </div>
959 );
960 })}
961 </div>
962 </aside>
963 )}
964 </div>
965 </div>
966 </aside>
967 );
968}