Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadTerminalDrawer.tsx

944 lines33.1 KB

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));
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);
43​
44function writeSystemMessage(terminal: Terminal, message: string): void {
45 terminal.write(`\r\n[terminal] ${message}\r\n`);
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 };
109​
110interface TerminalViewportProps {
111 threadId: ThreadId;
112 terminalId: string;
113 cwd: string;
114 runtimeEnv?: Record<string, string>;
115 focusRequestId: number;
116 autoFocus: boolean;
117 resizeEpoch: number;
118 drawerHeight: number;
120​
121function TerminalViewport({
122 threadId,
123 terminalId,
124 cwd,
125 runtimeEnv,
126 focusRequestId,
127 autoFocus,
128 resizeEpoch,
129 drawerHeight,
130}: TerminalViewportProps) {
131 const containerRef = useRef<HTMLDivElement>(null);
132 const terminalRef = useRef<Terminal | null>(null);
133 const fitAddonRef = useRef<FitAddon | null>(null);
134​
135 useEffect(() => {
136 const mount = containerRef.current;
137 if (!mount) return;
138​
139 let disposed = false;
140​
141 const fitAddon = new FitAddon();
142 const terminal = new Terminal({
143 cursorBlink: true,
144 lineHeight: 1.2,
145 fontSize: 12,
146 scrollback: 5_000,
147 fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
148 theme: terminalThemeFromApp(),
149 });
150 terminal.loadAddon(fitAddon);
151 terminal.open(mount);
152 fitAddon.fit();
153​
154 terminalRef.current = terminal;
155 fitAddonRef.current = fitAddon;
156​
157 const api = readNativeApi();
158 if (!api) return;
159​
160 const sendTerminalInput = async (data: string, fallbackError: string) => {
161 const activeTerminal = terminalRef.current;
162 if (!activeTerminal) return;
163 try {
164 await api.terminal.write({ threadId, terminalId, data });
165 } catch (error) {
166 writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
167 }
168 };
169​
170 terminal.attachCustomKeyEventHandler((event) => {
171 const navigationData = terminalNavigationShortcutData(event);
172 if (navigationData !== null) {
173 event.preventDefault();
174 event.stopPropagation();
175 void sendTerminalInput(navigationData, "Failed to move cursor");
176 return false;
177 }
178​
179 if (!isTerminalClearShortcut(event)) return true;
180 event.preventDefault();
181 event.stopPropagation();
182 void sendTerminalInput("\u000c", "Failed to clear terminal");
183 return false;
184 });
185​
186 const terminalLinksDisposable = terminal.registerLinkProvider({
187 provideLinks: (bufferLineNumber, callback) => {
188 const activeTerminal = terminalRef.current;
189 if (!activeTerminal) {
190 callback(undefined);
191 return;
192 }
193​
194 const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
195 if (!line) {
196 callback(undefined);
197 return;
198 }
199​
200 const lineText = line.translateToString(true);
201 const matches = extractTerminalLinks(lineText);
202 if (matches.length === 0) {
203 callback(undefined);
204 return;
205 }
206​
207 callback(
208 matches.map((match) => ({
209 text: match.text,
210 range: {
211 start: { x: match.start + 1, y: bufferLineNumber },
212 end: { x: match.end, y: bufferLineNumber },
213 },
214 activate: (event: MouseEvent) => {
215 if (!isTerminalLinkActivation(event)) return;
216​
217 const latestTerminal = terminalRef.current;
218 if (!latestTerminal) return;
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 ...(runtimeEnv ? { env: runtimeEnv } : {}),
278 });
279 if (disposed) return;
280 activeTerminal.write("\u001bc");
281 if (snapshot.history.length > 0) {
282 activeTerminal.write(snapshot.history);
283 }
284 if (autoFocus) {
285 window.requestAnimationFrame(() => {
286 activeTerminal.focus();
287 });
288 }
289 } catch (err) {
290 if (disposed) return;
291 writeSystemMessage(
292 terminal,
293 err instanceof Error ? err.message : "Failed to open terminal",
294 );
295 }
296 };
297​
298 const unsubscribe = api?.terminal.onEvent((event) => {
299 if (event.threadId !== threadId || event.terminalId !== terminalId) return;
300 const activeTerminal = terminalRef.current;
301 if (!activeTerminal) return;
302​
303 if (event.type === "output") {
304 activeTerminal.write(event.data);
305 return;
306 }
307​
308 if (event.type === "started" || event.type === "restarted") {
309 activeTerminal.write("\u001bc");
310 if (event.snapshot.history.length > 0) {
311 activeTerminal.write(event.snapshot.history);
312 }
313 return;
314 }
315​
316 if (event.type === "cleared") {
317 activeTerminal.clear();
318 activeTerminal.write("\u001bc");
319 return;
320 }
321​
322 if (event.type === "error") {
323 writeSystemMessage(activeTerminal, event.message);
324 return;
325 }
326​
327 if (event.type === "exited") {
328 const details = [
329 typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
330 typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
331 ]
332 .filter((value): value is string => value !== null)
333 .join(", ");
334 writeSystemMessage(
335 activeTerminal,
336 details.length > 0 ? `Process exited (${details})` : "Process exited",
337 );
338 }
339 });
340​
341 const fitTimer = window.setTimeout(() => {
342 const activeTerminal = terminalRef.current;
343 const activeFitAddon = fitAddonRef.current;
344 if (!activeTerminal || !activeFitAddon) return;
345 const wasAtBottom =
346 activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
347 activeFitAddon.fit();
348 if (wasAtBottom) {
349 activeTerminal.scrollToBottom();
350 }
351 void api.terminal
352 .resize({
353 threadId,
354 terminalId,
355 cols: activeTerminal.cols,
356 rows: activeTerminal.rows,
357 })
358 .catch(() => undefined);
359 }, 30);
360 void openTerminal();
361​
362 return () => {
363 disposed = true;
364 window.clearTimeout(fitTimer);
365 unsubscribe();
366 inputDisposable.dispose();
367 terminalLinksDisposable.dispose();
368 themeObserver.disconnect();
369 terminalRef.current = null;
370 fitAddonRef.current = null;
371 terminal.dispose();
372 };
373 }, [cwd, runtimeEnv, terminalId, threadId]);
374​
375 useEffect(() => {
376 if (!autoFocus) return;
377 const terminal = terminalRef.current;
378 if (!terminal) return;
379 const frame = window.requestAnimationFrame(() => {
380 terminal.focus();
381 });
382 return () => {
383 window.cancelAnimationFrame(frame);
384 };
385 }, [autoFocus, focusRequestId]);
386​
387 useEffect(() => {
388 const api = readNativeApi();
389 const terminal = terminalRef.current;
390 const fitAddon = fitAddonRef.current;
391 if (!api || !terminal || !fitAddon) return;
392 const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
393 const frame = window.requestAnimationFrame(() => {
394 fitAddon.fit();
395 if (wasAtBottom) {
396 terminal.scrollToBottom();
397 }
398 void api.terminal
399 .resize({
400 threadId,
401 terminalId,
402 cols: terminal.cols,
403 rows: terminal.rows,
404 })
405 .catch(() => undefined);
406 });
407 return () => {
408 window.cancelAnimationFrame(frame);
409 };
410 }, [drawerHeight, resizeEpoch, terminalId, threadId]);
411 return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
413​
414interface ThreadTerminalDrawerProps {
415 threadId: ThreadId;
416 cwd: string;
417 runtimeEnv?: Record<string, string>;
418 height: number;
419 terminalIds: string[];
420 activeTerminalId: string;
421 terminalGroups: ThreadTerminalGroup[];
422 activeTerminalGroupId: string;
423 focusRequestId: number;
424 onSplitTerminal: () => void;
425 onNewTerminal: () => void;
426 splitShortcutLabel?: string | undefined;
427 newShortcutLabel?: string | undefined;
428 closeShortcutLabel?: string | undefined;
429 onActiveTerminalChange: (terminalId: string) => void;
430 onCloseTerminal: (terminalId: string) => void;
431 onHeightChange: (height: number) => void;
433​
434interface TerminalActionButtonProps {
435 label: string;
436 className: string;
437 onClick: () => void;
438 children: ReactNode;
440​
441function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
442 return (
443 <Popover>
444 <PopoverTrigger
445 openOnHover
446 render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
447 >
448 {children}
449 </PopoverTrigger>
450 <PopoverPopup
451 tooltipStyle
452 side="bottom"
453 sideOffset={6}
454 align="center"
455 className="pointer-events-none select-none"
456 >
457 {label}
458 </PopoverPopup>
459 </Popover>
460 );
462​
463export default function ThreadTerminalDrawer({
464 threadId,
465 cwd,
466 runtimeEnv,
467 height,
468 terminalIds,
469 activeTerminalId,
470 terminalGroups,
471 activeTerminalGroupId,
472 focusRequestId,
473 onSplitTerminal,
474 onNewTerminal,
475 splitShortcutLabel,
476 newShortcutLabel,
477 closeShortcutLabel,
478 onActiveTerminalChange,
479 onCloseTerminal,
480 onHeightChange,
481}: ThreadTerminalDrawerProps) {
482 const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
483 const [resizeEpoch, setResizeEpoch] = useState(0);
484 const drawerHeightRef = useRef(drawerHeight);
485 const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
486 const onHeightChangeRef = useRef(onHeightChange);
487 const resizeStateRef = useRef<{
488 pointerId: number;
489 startY: number;
490 startHeight: number;
491 } | null>(null);
492 const didResizeDuringDragRef = useRef(false);
493​
494 const normalizedTerminalIds = useMemo(() => {
495 const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
496 return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
497 }, [terminalIds]);
498​
499 const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
500 ? activeTerminalId
501 : (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
502​
503 const resolvedTerminalGroups = useMemo(() => {
504 const validTerminalIdSet = new Set(normalizedTerminalIds);
505 const assignedTerminalIds = new Set<string>();
506 const usedGroupIds = new Set<string>();
507 const nextGroups: ThreadTerminalGroup[] = [];
508​
509 const assignUniqueGroupId = (groupId: string): string => {
510 if (!usedGroupIds.has(groupId)) {
511 usedGroupIds.add(groupId);
512 return groupId;
513 }
514 let suffix = 2;
515 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
516 suffix += 1;
517 }
518 const uniqueGroupId = `${groupId}-${suffix}`;
519 usedGroupIds.add(uniqueGroupId);
520 return uniqueGroupId;
521 };
522​
523 for (const terminalGroup of terminalGroups) {
524 const nextTerminalIds = [
525 ...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
526 ].filter((terminalId) => {
527 if (!validTerminalIdSet.has(terminalId)) return false;
528 if (assignedTerminalIds.has(terminalId)) return false;
529 return true;
530 });
531 if (nextTerminalIds.length === 0) continue;
532​
533 for (const terminalId of nextTerminalIds) {
534 assignedTerminalIds.add(terminalId);
535 }
536​
537 const baseGroupId =
538 terminalGroup.id.trim().length > 0
539 ? terminalGroup.id.trim()
540 : `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
541 nextGroups.push({
542 id: assignUniqueGroupId(baseGroupId),
543 terminalIds: nextTerminalIds,
544 });
545 }
546​
547 for (const terminalId of normalizedTerminalIds) {
548 if (assignedTerminalIds.has(terminalId)) continue;
549 nextGroups.push({
550 id: assignUniqueGroupId(`group-${terminalId}`),
551 terminalIds: [terminalId],
552 });
553 }
554​
555 if (nextGroups.length > 0) {
556 return nextGroups;
557 }
558​
559 return [
560 {
561 id: `group-${resolvedActiveTerminalId}`,
562 terminalIds: [resolvedActiveTerminalId],
563 },
564 ];
565 }, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
566​
567 const resolvedActiveGroupIndex = useMemo(() => {
568 const indexById = resolvedTerminalGroups.findIndex(
569 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
570 );
571 if (indexById >= 0) return indexById;
572 const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
573 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
574 );
575 return indexByTerminal >= 0 ? indexByTerminal : 0;
576 }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
577​
578 const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
579 resolvedActiveTerminalId,
580 ];
581 const hasTerminalSidebar = normalizedTerminalIds.length > 1;
582 const isSplitView = visibleTerminalIds.length > 1;
583 const showGroupHeaders =
584 resolvedTerminalGroups.length > 1 ||
585 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
586 const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
587 const terminalLabelById = useMemo(
588 () =>
589 new Map(
590 normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
591 ),
592 [normalizedTerminalIds],
593 );
594 const splitTerminalActionLabel = hasReachedTerminalLimit
595 ? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
596 : splitShortcutLabel
597 ? `Split Terminal (${splitShortcutLabel})`
598 : "Split Terminal";
599 const newTerminalActionLabel = hasReachedTerminalLimit
600 ? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
601 : newShortcutLabel
602 ? `New Terminal (${newShortcutLabel})`
603 : "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 threadId={threadId}
783 terminalId={terminalId}
784 cwd={cwd}
785 {...(runtimeEnv ? { runtimeEnv } : {})}
786 focusRequestId={focusRequestId}
787 autoFocus={terminalId === resolvedActiveTerminalId}
788 resizeEpoch={resizeEpoch}
789 drawerHeight={drawerHeight}
790 />
791 </div>
792 </div>
793 ))}
794 </div>
795 ) : (
796 <div className="h-full p-1">
797 <TerminalViewport
798 key={resolvedActiveTerminalId}
799 threadId={threadId}
800 terminalId={resolvedActiveTerminalId}
801 cwd={cwd}
802 {...(runtimeEnv ? { runtimeEnv } : {})}
803 focusRequestId={focusRequestId}
804 autoFocus
805 resizeEpoch={resizeEpoch}
806 drawerHeight={drawerHeight}
807 />
808 </div>
809 )}
810 </div>
811​
812 {hasTerminalSidebar && (
813 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
814 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
815 <div className="inline-flex h-full items-stretch">
816 <TerminalActionButton
817 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
818 hasReachedTerminalLimit
819 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
820 : "hover:bg-accent/70"
821 }`}
822 onClick={onSplitTerminalAction}
823 label={splitTerminalActionLabel}
824 >
825 <SquareSplitHorizontal className="size-3.25" />
826 </TerminalActionButton>
827 <TerminalActionButton
828 className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
829 hasReachedTerminalLimit
830 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
831 : "hover:bg-accent/70"
832 }`}
833 onClick={onNewTerminalAction}
834 label={newTerminalActionLabel}
835 >
836 <Plus className="size-3.25" />
837 </TerminalActionButton>
838 <TerminalActionButton
839 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
840 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
841 label={closeTerminalActionLabel}
842 >
843 <Trash2 className="size-3.25" />
844 </TerminalActionButton>
845 </div>
846 </div>
847​
848 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
849 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
850 const isGroupActive =
851 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
852 const groupActiveTerminalId = isGroupActive
853 ? resolvedActiveTerminalId
854 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
855​
856 return (
857 <div key={terminalGroup.id} className="pb-0.5">
858 {showGroupHeaders && (
859 <button
860 type="button"
861 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
862 isGroupActive
863 ? "bg-accent/70 text-foreground"
864 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
865 }`}
866 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
867 >
868 {terminalGroup.terminalIds.length > 1
869 ? `Split ${groupIndex + 1}`
870 : `Terminal ${groupIndex + 1}`}
871 </button>
872 )}
873​
874 <div
875 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
876 >
877 {terminalGroup.terminalIds.map((terminalId) => {
878 const isActive = terminalId === resolvedActiveTerminalId;
879 const closeTerminalLabel = `Close ${
880 terminalLabelById.get(terminalId) ?? "terminal"
881 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
882 return (
883 <div
884 key={terminalId}
885 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
886 isActive
887 ? "bg-accent text-foreground"
888 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
889 }`}
890 >
891 {showGroupHeaders && (
892 <span className="text-[10px] text-muted-foreground/80">└</span>
893 )}
894 <button
895 type="button"
896 className="flex min-w-0 flex-1 items-center gap-1 text-left"
897 onClick={() => onActiveTerminalChange(terminalId)}
898 >
899 <TerminalSquare className="size-3 shrink-0" />
900 <span className="truncate">
901 {terminalLabelById.get(terminalId) ?? "Terminal"}
902 </span>
903 </button>
904 {normalizedTerminalIds.length > 1 && (
905 <Popover>
906 <PopoverTrigger
907 openOnHover
908 render={
909 <button
910 type="button"
911 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"
912 onClick={() => onCloseTerminal(terminalId)}
913 aria-label={closeTerminalLabel}
914 />
915 }
916 >
917 <XIcon className="size-2.5" />
918 </PopoverTrigger>
919 <PopoverPopup
920 tooltipStyle
921 side="bottom"
922 sideOffset={6}
923 align="center"
924 className="pointer-events-none select-none"
925 >
926 {closeTerminalLabel}
927 </PopoverPopup>
928 </Popover>
929 )}
930 </div>
931 );
932 })}
933 </div>
934 </div>
935 );
936 })}
937 </div>
938 </aside>
939 )}
940 </div>
941 </div>
942 </aside>
943 );