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