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

ThreadTerminalDrawer.tsx

1,267 lines44.4 KB

1import { FitAddon } from "@xterm/addon-fit";
2import { Plus, SquareSplitHorizontal, TerminalSquare, Trash2, XIcon } from "lucide-react";
3import {
4 type TerminalEvent,
5 type TerminalSessionSnapshot,
6 type ThreadId,
7} from "@t3tools/contracts";
8import { Terminal, type ITheme } from "@xterm/xterm";
9import {
10 type PointerEvent as ReactPointerEvent,
11 type ReactNode,
12 useCallback,
13 useEffect,
14 useEffectEvent,
15 useMemo,
16 useRef,
17 useState,
18} from "react";
19import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
20import { type TerminalContextSelection } from "~/lib/terminalContext";
21import { openInPreferredEditor } from "../editorPreferences";
22import {
23 extractTerminalLinks,
24 isTerminalLinkActivation,
25 resolvePathLinkTarget,
26} from "../terminal-links";
27import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
28import {
29 DEFAULT_THREAD_TERMINAL_HEIGHT,
30 DEFAULT_THREAD_TERMINAL_ID,
31 MAX_TERMINALS_PER_GROUP,
32 type ThreadTerminalGroup,
33} from "../types";
34import { readNativeApi } from "~/nativeApi";
35import { selectTerminalEventEntries, useTerminalStateStore } from "../terminalStateStore";
36​
37const MIN_DRAWER_HEIGHT = 180;
38const MAX_DRAWER_HEIGHT_RATIO = 0.75;
39const MULTI_CLICK_SELECTION_ACTION_DELAY_MS = 260;
40​
41function maxDrawerHeight(): number {
42 if (typeof window === "undefined") return DEFAULT_THREAD_TERMINAL_HEIGHT;
43 return Math.max(MIN_DRAWER_HEIGHT, Math.floor(window.innerHeight * MAX_DRAWER_HEIGHT_RATIO));
45​
46function clampDrawerHeight(height: number): number {
47 const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
48 const maxHeight = maxDrawerHeight();
49 return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
51​
52function writeSystemMessage(terminal: Terminal, message: string): void {
53 terminal.write(`\r\n[terminal] ${message}\r\n`);
55​
56function writeTerminalSnapshot(terminal: Terminal, snapshot: TerminalSessionSnapshot): void {
57 terminal.write("\u001bc");
58 if (snapshot.history.length > 0) {
59 terminal.write(snapshot.history);
60 }
62​
63export function selectTerminalEventEntriesAfterSnapshot(
64 entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
65 snapshotUpdatedAt: string,
66): ReadonlyArray<{ id: number; event: TerminalEvent }> {
67 return entries.filter((entry) => entry.event.createdAt > snapshotUpdatedAt);
69​
70export function selectPendingTerminalEventEntries(
71 entries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
72 lastAppliedTerminalEventId: number,
73): ReadonlyArray<{ id: number; event: TerminalEvent }> {
74 return entries.filter((entry) => entry.id > lastAppliedTerminalEventId);
76​
77function terminalThemeFromApp(): ITheme {
78 const isDark = document.documentElement.classList.contains("dark");
79 const bodyStyles = getComputedStyle(document.body);
80 const background =
81 bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)");
82 const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)");
83​
84 if (isDark) {
85 return {
86 background,
87 foreground,
88 cursor: "rgb(180, 203, 255)",
89 selectionBackground: "rgba(180, 203, 255, 0.25)",
90 scrollbarSliderBackground: "rgba(255, 255, 255, 0.1)",
91 scrollbarSliderHoverBackground: "rgba(255, 255, 255, 0.18)",
92 scrollbarSliderActiveBackground: "rgba(255, 255, 255, 0.22)",
93 black: "rgb(24, 30, 38)",
94 red: "rgb(255, 122, 142)",
95 green: "rgb(134, 231, 149)",
96 yellow: "rgb(244, 205, 114)",
97 blue: "rgb(137, 190, 255)",
98 magenta: "rgb(208, 176, 255)",
99 cyan: "rgb(124, 232, 237)",
100 white: "rgb(210, 218, 230)",
101 brightBlack: "rgb(110, 120, 136)",
102 brightRed: "rgb(255, 168, 180)",
103 brightGreen: "rgb(176, 245, 186)",
104 brightYellow: "rgb(255, 224, 149)",
105 brightBlue: "rgb(174, 210, 255)",
106 brightMagenta: "rgb(229, 203, 255)",
107 brightCyan: "rgb(167, 244, 247)",
108 brightWhite: "rgb(244, 247, 252)",
109 };
110 }
111​
112 return {
113 background,
114 foreground,
115 cursor: "rgb(38, 56, 78)",
116 selectionBackground: "rgba(37, 63, 99, 0.2)",
117 scrollbarSliderBackground: "rgba(0, 0, 0, 0.15)",
118 scrollbarSliderHoverBackground: "rgba(0, 0, 0, 0.25)",
119 scrollbarSliderActiveBackground: "rgba(0, 0, 0, 0.3)",
120 black: "rgb(44, 53, 66)",
121 red: "rgb(191, 70, 87)",
122 green: "rgb(60, 126, 86)",
123 yellow: "rgb(146, 112, 35)",
124 blue: "rgb(72, 102, 163)",
125 magenta: "rgb(132, 86, 149)",
126 cyan: "rgb(53, 127, 141)",
127 white: "rgb(210, 215, 223)",
128 brightBlack: "rgb(112, 123, 140)",
129 brightRed: "rgb(212, 95, 112)",
130 brightGreen: "rgb(85, 148, 111)",
131 brightYellow: "rgb(173, 133, 45)",
132 brightBlue: "rgb(91, 124, 194)",
133 brightMagenta: "rgb(153, 107, 172)",
134 brightCyan: "rgb(70, 149, 164)",
135 brightWhite: "rgb(236, 240, 246)",
136 };
138​
139function getTerminalSelectionRect(mountElement: HTMLElement): DOMRect | null {
140 const selection = window.getSelection();
141 if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
142 return null;
143 }
144​
145 const range = selection.getRangeAt(0);
146 const commonAncestor = range.commonAncestorContainer;
147 const selectionRoot =
148 commonAncestor instanceof Element ? commonAncestor : commonAncestor.parentElement;
149 if (!(selectionRoot instanceof Element) || !mountElement.contains(selectionRoot)) {
150 return null;
151 }
152​
153 const rects = Array.from(range.getClientRects()).filter(
154 (rect) => rect.width > 0 || rect.height > 0,
155 );
156 if (rects.length > 0) {
157 return rects[rects.length - 1] ?? null;
158 }
159​
160 const boundingRect = range.getBoundingClientRect();
161 return boundingRect.width > 0 || boundingRect.height > 0 ? boundingRect : null;
163​
164export function resolveTerminalSelectionActionPosition(options: {
165 bounds: { left: number; top: number; width: number; height: number };
166 selectionRect: { right: number; bottom: number } | null;
167 pointer: { x: number; y: number } | null;
168 viewport?: { width: number; height: number } | null;
169}): { x: number; y: number } {
170 const { bounds, selectionRect, pointer, viewport } = options;
171 const viewportWidth =
172 viewport?.width ??
173 (typeof window === "undefined" ? bounds.left + bounds.width + 8 : window.innerWidth);
174 const viewportHeight =
175 viewport?.height ??
176 (typeof window === "undefined" ? bounds.top + bounds.height + 8 : window.innerHeight);
177 const drawerLeft = Math.round(bounds.left);
178 const drawerTop = Math.round(bounds.top);
179 const drawerRight = Math.round(bounds.left + bounds.width);
180 const drawerBottom = Math.round(bounds.top + bounds.height);
181 const preferredX =
182 selectionRect !== null
183 ? Math.round(selectionRect.right)
184 : pointer === null
185 ? Math.round(bounds.left + bounds.width - 140)
186 : Math.max(drawerLeft, Math.min(Math.round(pointer.x), drawerRight));
187 const preferredY =
188 selectionRect !== null
189 ? Math.round(selectionRect.bottom + 4)
190 : pointer === null
191 ? Math.round(bounds.top + 12)
192 : Math.max(drawerTop, Math.min(Math.round(pointer.y), drawerBottom));
193 return {
194 x: Math.max(8, Math.min(preferredX, Math.max(viewportWidth - 8, 8))),
195 y: Math.max(8, Math.min(preferredY, Math.max(viewportHeight - 8, 8))),
196 };
198​
199export function terminalSelectionActionDelayForClickCount(clickCount: number): number {
200 return clickCount >= 2 ? MULTI_CLICK_SELECTION_ACTION_DELAY_MS : 0;
202​
203export function shouldHandleTerminalSelectionMouseUp(
204 selectionGestureActive: boolean,
205 button: number,
206): boolean {
207 return selectionGestureActive && button === 0;
209​
210interface TerminalViewportProps {
211 threadId: ThreadId;
212 terminalId: string;
213 terminalLabel: string;
214 cwd: string;
215 worktreePath?: string | null;
216 runtimeEnv?: Record<string, string>;
217 onSessionExited: () => void;
218 onAddTerminalContext: (selection: TerminalContextSelection) => void;
219 focusRequestId: number;
220 autoFocus: boolean;
221 resizeEpoch: number;
222 drawerHeight: number;
224​
225function TerminalViewport({
226 threadId,
227 terminalId,
228 terminalLabel,
229 cwd,
230 worktreePath,
231 runtimeEnv,
232 onSessionExited,
233 onAddTerminalContext,
234 focusRequestId,
235 autoFocus,
236 resizeEpoch,
237 drawerHeight,
238}: TerminalViewportProps) {
239 const containerRef = useRef<HTMLDivElement>(null);
240 const terminalRef = useRef<Terminal | null>(null);
241 const fitAddonRef = useRef<FitAddon | null>(null);
242 const hasHandledExitRef = useRef(false);
243 const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
244 const selectionGestureActiveRef = useRef(false);
245 const selectionActionRequestIdRef = useRef(0);
246 const selectionActionOpenRef = useRef(false);
247 const selectionActionTimerRef = useRef<number | null>(null);
248 const lastAppliedTerminalEventIdRef = useRef(0);
249 const terminalHydratedRef = useRef(false);
250 const handleSessionExited = useEffectEvent(() => {
251 onSessionExited();
252 });
253 const handleAddTerminalContext = useEffectEvent((selection: TerminalContextSelection) => {
254 onAddTerminalContext(selection);
255 });
256 const readTerminalLabel = useEffectEvent(() => terminalLabel);
257​
258 useEffect(() => {
259 const mount = containerRef.current;
260 if (!mount) return;
261​
262 let disposed = false;
263​
264 const fitAddon = new FitAddon();
265 const terminal = new Terminal({
266 cursorBlink: true,
267 lineHeight: 1.2,
268 fontSize: 12,
269 scrollback: 5_000,
270 fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
271 theme: terminalThemeFromApp(),
272 });
273 terminal.loadAddon(fitAddon);
274 terminal.open(mount);
275 fitAddon.fit();
276​
277 terminalRef.current = terminal;
278 fitAddonRef.current = fitAddon;
279​
280 const api = readNativeApi();
281 if (!api) return;
282​
283 const clearSelectionAction = () => {
284 selectionActionRequestIdRef.current += 1;
285 if (selectionActionTimerRef.current !== null) {
286 window.clearTimeout(selectionActionTimerRef.current);
287 selectionActionTimerRef.current = null;
288 }
289 };
290​
291 const readSelectionAction = (): {
292 position: { x: number; y: number };
293 selection: TerminalContextSelection;
294 } | null => {
295 const activeTerminal = terminalRef.current;
296 const mountElement = containerRef.current;
297 if (!activeTerminal || !mountElement || !activeTerminal.hasSelection()) {
298 return null;
299 }
300 const selectionText = activeTerminal.getSelection();
301 const selectionPosition = activeTerminal.getSelectionPosition();
302 const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
303 if (!selectionPosition || normalizedText.length === 0) {
304 return null;
305 }
306 const lineStart = selectionPosition.start.y + 1;
307 const lineCount = normalizedText.split("\n").length;
308 const lineEnd = Math.max(lineStart, lineStart + lineCount - 1);
309 const bounds = mountElement.getBoundingClientRect();
310 const selectionRect = getTerminalSelectionRect(mountElement);
311 const position = resolveTerminalSelectionActionPosition({
312 bounds,
313 selectionRect:
314 selectionRect === null
315 ? null
316 : { right: selectionRect.right, bottom: selectionRect.bottom },
317 pointer: selectionPointerRef.current,
318 });
319 return {
320 position,
321 selection: {
322 terminalId,
323 terminalLabel: readTerminalLabel(),
324 lineStart,
325 lineEnd,
326 text: normalizedText,
327 },
328 };
329 };
330​
331 const showSelectionAction = async () => {
332 if (selectionActionOpenRef.current) {
333 return;
334 }
335 const nextAction = readSelectionAction();
336 if (!nextAction) {
337 clearSelectionAction();
338 return;
339 }
340 const requestId = ++selectionActionRequestIdRef.current;
341 selectionActionOpenRef.current = true;
342 try {
343 const clicked = await api.contextMenu.show(
344 [{ id: "add-to-chat", label: "Add to chat" }],
345 nextAction.position,
346 );
347 if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
348 return;
349 }
350 handleAddTerminalContext(nextAction.selection);
351 terminalRef.current?.clearSelection();
352 terminalRef.current?.focus();
353 } finally {
354 selectionActionOpenRef.current = false;
355 }
356 };
357​
358 const sendTerminalInput = async (data: string, fallbackError: string) => {
359 const activeTerminal = terminalRef.current;
360 if (!activeTerminal) return;
361 try {
362 await api.terminal.write({ threadId, terminalId, data });
363 } catch (error) {
364 writeSystemMessage(activeTerminal, error instanceof Error ? error.message : fallbackError);
365 }
366 };
367​
368 terminal.attachCustomKeyEventHandler((event) => {
369 const navigationData = terminalNavigationShortcutData(event);
370 if (navigationData !== null) {
371 event.preventDefault();
372 event.stopPropagation();
373 void sendTerminalInput(navigationData, "Failed to move cursor");
374 return false;
375 }
376​
377 if (!isTerminalClearShortcut(event)) return true;
378 event.preventDefault();
379 event.stopPropagation();
380 void sendTerminalInput("\u000c", "Failed to clear terminal");
381 return false;
382 });
383​
384 const terminalLinksDisposable = terminal.registerLinkProvider({
385 provideLinks: (bufferLineNumber, callback) => {
386 const activeTerminal = terminalRef.current;
387 if (!activeTerminal) {
388 callback(undefined);
389 return;
390 }
391​
392 const line = activeTerminal.buffer.active.getLine(bufferLineNumber - 1);
393 if (!line) {
394 callback(undefined);
395 return;
396 }
397​
398 const lineText = line.translateToString(true);
399 const matches = extractTerminalLinks(lineText);
400 if (matches.length === 0) {
401 callback(undefined);
402 return;
403 }
404​
405 callback(
406 matches.map((match) => ({
407 text: match.text,
408 range: {
409 start: { x: match.start + 1, y: bufferLineNumber },
410 end: { x: match.end, y: bufferLineNumber },
411 },
412 activate: (event: MouseEvent) => {
413 if (!isTerminalLinkActivation(event)) return;
414​
415 const latestTerminal = terminalRef.current;
416 if (!latestTerminal) return;
417​
418 if (match.kind === "url") {
419 void api.shell.openExternal(match.text).catch((error) => {
420 writeSystemMessage(
421 latestTerminal,
422 error instanceof Error ? error.message : "Unable to open link",
423 );
424 });
425 return;
426 }
427​
428 const target = resolvePathLinkTarget(match.text, cwd);
429 void openInPreferredEditor(api, target).catch((error) => {
430 writeSystemMessage(
431 latestTerminal,
432 error instanceof Error ? error.message : "Unable to open path",
433 );
434 });
435 },
436 })),
437 );
438 },
439 });
440​
441 const inputDisposable = terminal.onData((data) => {
442 void api.terminal
443 .write({ threadId, terminalId, data })
444 .catch((err) =>
445 writeSystemMessage(
446 terminal,
447 err instanceof Error ? err.message : "Terminal write failed",
448 ),
449 );
450 });
451​
452 const selectionDisposable = terminal.onSelectionChange(() => {
453 if (terminalRef.current?.hasSelection()) {
454 return;
455 }
456 clearSelectionAction();
457 });
458​
459 const handleMouseUp = (event: MouseEvent) => {
460 const shouldHandle = shouldHandleTerminalSelectionMouseUp(
461 selectionGestureActiveRef.current,
462 event.button,
463 );
464 selectionGestureActiveRef.current = false;
465 if (!shouldHandle) {
466 return;
467 }
468 selectionPointerRef.current = { x: event.clientX, y: event.clientY };
469 const delay = terminalSelectionActionDelayForClickCount(event.detail);
470 selectionActionTimerRef.current = window.setTimeout(() => {
471 selectionActionTimerRef.current = null;
472 window.requestAnimationFrame(() => {
473 void showSelectionAction();
474 });
475 }, delay);
476 };
477 const handlePointerDown = (event: PointerEvent) => {
478 clearSelectionAction();
479 selectionGestureActiveRef.current = event.button === 0;
480 };
481 window.addEventListener("mouseup", handleMouseUp);
482 mount.addEventListener("pointerdown", handlePointerDown);
483​
484 const themeObserver = new MutationObserver(() => {
485 const activeTerminal = terminalRef.current;
486 if (!activeTerminal) return;
487 activeTerminal.options.theme = terminalThemeFromApp();
488 activeTerminal.refresh(0, activeTerminal.rows - 1);
489 });
490 themeObserver.observe(document.documentElement, {
491 attributes: true,
492 attributeFilter: ["class", "style"],
493 });
494​
495 const applyTerminalEvent = (event: TerminalEvent) => {
496 const activeTerminal = terminalRef.current;
497 if (!activeTerminal) {
498 return;
499 }
500​
501 if (event.type === "activity") {
502 return;
503 }
504​
505 if (event.type === "output") {
506 activeTerminal.write(event.data);
507 clearSelectionAction();
508 return;
509 }
510​
511 if (event.type === "started" || event.type === "restarted") {
512 hasHandledExitRef.current = false;
513 clearSelectionAction();
514 writeTerminalSnapshot(activeTerminal, event.snapshot);
515 return;
516 }
517​
518 if (event.type === "cleared") {
519 clearSelectionAction();
520 activeTerminal.clear();
521 activeTerminal.write("\u001bc");
522 return;
523 }
524​
525 if (event.type === "error") {
526 writeSystemMessage(activeTerminal, event.message);
527 return;
528 }
529​
530 const details = [
531 typeof event.exitCode === "number" ? `code ${event.exitCode}` : null,
532 typeof event.exitSignal === "number" ? `signal ${event.exitSignal}` : null,
533 ]
534 .filter((value): value is string => value !== null)
535 .join(", ");
536 writeSystemMessage(
537 activeTerminal,
538 details.length > 0 ? `Process exited (${details})` : "Process exited",
539 );
540 if (hasHandledExitRef.current) {
541 return;
542 }
543 hasHandledExitRef.current = true;
544 window.setTimeout(() => {
545 if (!hasHandledExitRef.current) {
546 return;
547 }
548 handleSessionExited();
549 }, 0);
550 };
551 const applyPendingTerminalEvents = (
552 terminalEventEntries: ReadonlyArray<{ id: number; event: TerminalEvent }>,
553 ) => {
554 const pendingEntries = selectPendingTerminalEventEntries(
555 terminalEventEntries,
556 lastAppliedTerminalEventIdRef.current,
557 );
558 if (pendingEntries.length === 0) {
559 return;
560 }
561 for (const entry of pendingEntries) {
562 applyTerminalEvent(entry.event);
563 }
564 lastAppliedTerminalEventIdRef.current =
565 pendingEntries.at(-1)?.id ?? lastAppliedTerminalEventIdRef.current;
566 };
567​
568 const unsubscribeTerminalEvents = useTerminalStateStore.subscribe((state, previousState) => {
569 if (!terminalHydratedRef.current) {
570 return;
571 }
572​
573 const previousLastEntryId =
574 selectTerminalEventEntries(
575 previousState.terminalEventEntriesByKey,
576 threadId,
577 terminalId,
578 ).at(-1)?.id ?? 0;
579 const nextEntries = selectTerminalEventEntries(
580 state.terminalEventEntriesByKey,
581 threadId,
582 terminalId,
583 );
584 const nextLastEntryId = nextEntries.at(-1)?.id ?? 0;
585 if (nextLastEntryId === previousLastEntryId) {
586 return;
587 }
588​
589 applyPendingTerminalEvents(nextEntries);
590 });
591​
592 const openTerminal = async () => {
593 try {
594 const activeTerminal = terminalRef.current;
595 const activeFitAddon = fitAddonRef.current;
596 if (!activeTerminal || !activeFitAddon) return;
597 activeFitAddon.fit();
598 const snapshot = await api.terminal.open({
599 threadId,
600 terminalId,
601 cwd,
602 ...(worktreePath !== undefined ? { worktreePath } : {}),
603 cols: activeTerminal.cols,
604 rows: activeTerminal.rows,
605 ...(runtimeEnv ? { env: runtimeEnv } : {}),
606 });
607 if (disposed) return;
608 writeTerminalSnapshot(activeTerminal, snapshot);
609 const bufferedEntries = selectTerminalEventEntries(
610 useTerminalStateStore.getState().terminalEventEntriesByKey,
611 threadId,
612 terminalId,
613 );
614 const replayEntries = selectTerminalEventEntriesAfterSnapshot(
615 bufferedEntries,
616 snapshot.updatedAt,
617 );
618 for (const entry of replayEntries) {
619 applyTerminalEvent(entry.event);
620 }
621 lastAppliedTerminalEventIdRef.current = bufferedEntries.at(-1)?.id ?? 0;
622 terminalHydratedRef.current = true;
623 if (autoFocus) {
624 window.requestAnimationFrame(() => {
625 activeTerminal.focus();
626 });
627 }
628 } catch (err) {
629 if (disposed) return;
630 writeSystemMessage(
631 terminal,
632 err instanceof Error ? err.message : "Failed to open terminal",
633 );
634 }
635 };
636​
637 const fitTimer = window.setTimeout(() => {
638 const activeTerminal = terminalRef.current;
639 const activeFitAddon = fitAddonRef.current;
640 if (!activeTerminal || !activeFitAddon) return;
641 const wasAtBottom =
642 activeTerminal.buffer.active.viewportY >= activeTerminal.buffer.active.baseY;
643 activeFitAddon.fit();
644 if (wasAtBottom) {
645 activeTerminal.scrollToBottom();
646 }
647 void api.terminal
648 .resize({
649 threadId,
650 terminalId,
651 cols: activeTerminal.cols,
652 rows: activeTerminal.rows,
653 })
654 .catch(() => undefined);
655 }, 30);
656 void openTerminal();
657​
658 return () => {
659 disposed = true;
660 terminalHydratedRef.current = false;
661 lastAppliedTerminalEventIdRef.current = 0;
662 unsubscribeTerminalEvents();
663 window.clearTimeout(fitTimer);
664 inputDisposable.dispose();
665 selectionDisposable.dispose();
666 terminalLinksDisposable.dispose();
667 if (selectionActionTimerRef.current !== null) {
668 window.clearTimeout(selectionActionTimerRef.current);
669 }
670 window.removeEventListener("mouseup", handleMouseUp);
671 mount.removeEventListener("pointerdown", handlePointerDown);
672 themeObserver.disconnect();
673 terminalRef.current = null;
674 fitAddonRef.current = null;
675 terminal.dispose();
676 };
677 // autoFocus is intentionally omitted;
678 // it is only read at mount time and must not trigger terminal teardown/recreation.
679 // eslint-disable-next-line react-hooks/exhaustive-deps
680 }, [cwd, runtimeEnv, terminalId, threadId]);
681​
682 useEffect(() => {
683 if (!autoFocus) return;
684 const terminal = terminalRef.current;
685 if (!terminal) return;
686 const frame = window.requestAnimationFrame(() => {
687 terminal.focus();
688 });
689 return () => {
690 window.cancelAnimationFrame(frame);
691 };
692 }, [autoFocus, focusRequestId]);
693​
694 useEffect(() => {
695 const api = readNativeApi();
696 const terminal = terminalRef.current;
697 const fitAddon = fitAddonRef.current;
698 if (!api || !terminal || !fitAddon) return;
699 const wasAtBottom = terminal.buffer.active.viewportY >= terminal.buffer.active.baseY;
700 const frame = window.requestAnimationFrame(() => {
701 fitAddon.fit();
702 if (wasAtBottom) {
703 terminal.scrollToBottom();
704 }
705 void api.terminal
706 .resize({
707 threadId,
708 terminalId,
709 cols: terminal.cols,
710 rows: terminal.rows,
711 })
712 .catch(() => undefined);
713 });
714 return () => {
715 window.cancelAnimationFrame(frame);
716 };
717 }, [drawerHeight, resizeEpoch, terminalId, threadId]);
718 return (
719 <div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
720 );
722​
723interface ThreadTerminalDrawerProps {
724 threadId: ThreadId;
725 cwd: string;
726 worktreePath?: string | null;
727 runtimeEnv?: Record<string, string>;
728 visible?: boolean;
729 height: number;
730 terminalIds: string[];
731 activeTerminalId: string;
732 terminalGroups: ThreadTerminalGroup[];
733 activeTerminalGroupId: string;
734 focusRequestId: number;
735 onSplitTerminal: () => void;
736 onNewTerminal: () => void;
737 splitShortcutLabel?: string | undefined;
738 newShortcutLabel?: string | undefined;
739 closeShortcutLabel?: string | undefined;
740 onActiveTerminalChange: (terminalId: string) => void;
741 onCloseTerminal: (terminalId: string) => void;
742 onHeightChange: (height: number) => void;
743 onAddTerminalContext: (selection: TerminalContextSelection) => void;
745​
746interface TerminalActionButtonProps {
747 label: string;
748 className: string;
749 onClick: () => void;
750 children: ReactNode;
752​
753function TerminalActionButton({ label, className, onClick, children }: TerminalActionButtonProps) {
754 return (
755 <Popover>
756 <PopoverTrigger
757 openOnHover
758 render={<button type="button" className={className} onClick={onClick} aria-label={label} />}
759 >
760 {children}
761 </PopoverTrigger>
762 <PopoverPopup
763 tooltipStyle
764 side="bottom"
765 sideOffset={6}
766 align="center"
767 className="pointer-events-none select-none"
768 >
769 {label}
770 </PopoverPopup>
771 </Popover>
772 );
774​
775export default function ThreadTerminalDrawer({
776 threadId,
777 cwd,
778 worktreePath,
779 runtimeEnv,
780 visible = true,
781 height,
782 terminalIds,
783 activeTerminalId,
784 terminalGroups,
785 activeTerminalGroupId,
786 focusRequestId,
787 onSplitTerminal,
788 onNewTerminal,
789 splitShortcutLabel,
790 newShortcutLabel,
791 closeShortcutLabel,
792 onActiveTerminalChange,
793 onCloseTerminal,
794 onHeightChange,
795 onAddTerminalContext,
796}: ThreadTerminalDrawerProps) {
797 const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
798 const [resizeEpoch, setResizeEpoch] = useState(0);
799 const drawerHeightRef = useRef(drawerHeight);
800 const lastSyncedHeightRef = useRef(clampDrawerHeight(height));
801 const onHeightChangeRef = useRef(onHeightChange);
802 const resizeStateRef = useRef<{
803 pointerId: number;
804 startY: number;
805 startHeight: number;
806 } | null>(null);
807 const didResizeDuringDragRef = useRef(false);
808​
809 const normalizedTerminalIds = useMemo(() => {
810 const cleaned = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
811 return cleaned.length > 0 ? cleaned : [DEFAULT_THREAD_TERMINAL_ID];
812 }, [terminalIds]);
813​
814 const resolvedActiveTerminalId = normalizedTerminalIds.includes(activeTerminalId)
815 ? activeTerminalId
816 : (normalizedTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID);
817​
818 const resolvedTerminalGroups = useMemo(() => {
819 const validTerminalIdSet = new Set(normalizedTerminalIds);
820 const assignedTerminalIds = new Set<string>();
821 const usedGroupIds = new Set<string>();
822 const nextGroups: ThreadTerminalGroup[] = [];
823​
824 const assignUniqueGroupId = (groupId: string): string => {
825 if (!usedGroupIds.has(groupId)) {
826 usedGroupIds.add(groupId);
827 return groupId;
828 }
829 let suffix = 2;
830 while (usedGroupIds.has(`${groupId}-${suffix}`)) {
831 suffix += 1;
832 }
833 const uniqueGroupId = `${groupId}-${suffix}`;
834 usedGroupIds.add(uniqueGroupId);
835 return uniqueGroupId;
836 };
837​
838 for (const terminalGroup of terminalGroups) {
839 const nextTerminalIds = [
840 ...new Set(terminalGroup.terminalIds.map((id) => id.trim()).filter((id) => id.length > 0)),
841 ].filter((terminalId) => {
842 if (!validTerminalIdSet.has(terminalId)) return false;
843 if (assignedTerminalIds.has(terminalId)) return false;
844 return true;
845 });
846 if (nextTerminalIds.length === 0) continue;
847​
848 for (const terminalId of nextTerminalIds) {
849 assignedTerminalIds.add(terminalId);
850 }
851​
852 const baseGroupId =
853 terminalGroup.id.trim().length > 0
854 ? terminalGroup.id.trim()
855 : `group-${nextTerminalIds[0] ?? DEFAULT_THREAD_TERMINAL_ID}`;
856 nextGroups.push({
857 id: assignUniqueGroupId(baseGroupId),
858 terminalIds: nextTerminalIds,
859 });
860 }
861​
862 for (const terminalId of normalizedTerminalIds) {
863 if (assignedTerminalIds.has(terminalId)) continue;
864 nextGroups.push({
865 id: assignUniqueGroupId(`group-${terminalId}`),
866 terminalIds: [terminalId],
867 });
868 }
869​
870 if (nextGroups.length > 0) {
871 return nextGroups;
872 }
873​
874 return [
875 {
876 id: `group-${resolvedActiveTerminalId}`,
877 terminalIds: [resolvedActiveTerminalId],
878 },
879 ];
880 }, [normalizedTerminalIds, resolvedActiveTerminalId, terminalGroups]);
881​
882 const resolvedActiveGroupIndex = useMemo(() => {
883 const indexById = resolvedTerminalGroups.findIndex(
884 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
885 );
886 if (indexById >= 0) return indexById;
887 const indexByTerminal = resolvedTerminalGroups.findIndex((terminalGroup) =>
888 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
889 );
890 return indexByTerminal >= 0 ? indexByTerminal : 0;
891 }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
892​
893 const visibleTerminalIds = resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ?? [
894 resolvedActiveTerminalId,
895 ];
896 const hasTerminalSidebar = normalizedTerminalIds.length > 1;
897 const isSplitView = visibleTerminalIds.length > 1;
898 const showGroupHeaders =
899 resolvedTerminalGroups.length > 1 ||
900 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
901 const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
902 const terminalLabelById = useMemo(
903 () =>
904 new Map(
905 normalizedTerminalIds.map((terminalId, index) => [terminalId, `Terminal ${index + 1}`]),
906 ),
907 [normalizedTerminalIds],
908 );
909 const splitTerminalActionLabel = hasReachedSplitLimit
910 ? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
911 : splitShortcutLabel
912 ? `Split Terminal (${splitShortcutLabel})`
913 : "Split Terminal";
914 const newTerminalActionLabel = newShortcutLabel
915 ? `New Terminal (${newShortcutLabel})`
916 : "New Terminal";
917 const closeTerminalActionLabel = closeShortcutLabel
918 ? `Close Terminal (${closeShortcutLabel})`
919 : "Close Terminal";
920 const onSplitTerminalAction = useCallback(() => {
921 if (hasReachedSplitLimit) return;
922 onSplitTerminal();
923 }, [hasReachedSplitLimit, onSplitTerminal]);
924 const onNewTerminalAction = useCallback(() => {
925 onNewTerminal();
926 }, [onNewTerminal]);
927​
928 useEffect(() => {
929 onHeightChangeRef.current = onHeightChange;
930 }, [onHeightChange]);
931​
932 useEffect(() => {
933 drawerHeightRef.current = drawerHeight;
934 }, [drawerHeight]);
935​
936 const syncHeight = useCallback((nextHeight: number) => {
937 const clampedHeight = clampDrawerHeight(nextHeight);
938 if (lastSyncedHeightRef.current === clampedHeight) return;
939 lastSyncedHeightRef.current = clampedHeight;
940 onHeightChangeRef.current(clampedHeight);
941 }, []);
942​
943 useEffect(() => {
944 const clampedHeight = clampDrawerHeight(height);
945 setDrawerHeight(clampedHeight);
946 drawerHeightRef.current = clampedHeight;
947 lastSyncedHeightRef.current = clampedHeight;
948 }, [height, threadId]);
949​
950 const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
951 if (event.button !== 0) return;
952 event.preventDefault();
953 event.currentTarget.setPointerCapture(event.pointerId);
954 didResizeDuringDragRef.current = false;
955 resizeStateRef.current = {
956 pointerId: event.pointerId,
957 startY: event.clientY,
958 startHeight: drawerHeightRef.current,
959 };
960 }, []);
961​
962 const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
963 const resizeState = resizeStateRef.current;
964 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
965 event.preventDefault();
966 const clampedHeight = clampDrawerHeight(
967 resizeState.startHeight + (resizeState.startY - event.clientY),
968 );
969 if (clampedHeight === drawerHeightRef.current) {
970 return;
971 }
972 didResizeDuringDragRef.current = true;
973 drawerHeightRef.current = clampedHeight;
974 setDrawerHeight(clampedHeight);
975 }, []);
976​
977 const handleResizePointerEnd = useCallback(
978 (event: ReactPointerEvent<HTMLDivElement>) => {
979 const resizeState = resizeStateRef.current;
980 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
981 resizeStateRef.current = null;
982 if (event.currentTarget.hasPointerCapture(event.pointerId)) {
983 event.currentTarget.releasePointerCapture(event.pointerId);
984 }
985 if (!didResizeDuringDragRef.current) {
986 return;
987 }
988 syncHeight(drawerHeightRef.current);
989 setResizeEpoch((value) => value + 1);
990 },
991 [syncHeight],
992 );
993​
994 useEffect(() => {
995 if (!visible) {
996 return;
997 }
998​
999 const onWindowResize = () => {
1000 const clampedHeight = clampDrawerHeight(drawerHeightRef.current);
1001 const changed = clampedHeight !== drawerHeightRef.current;
1002 if (changed) {
1003 setDrawerHeight(clampedHeight);
1004 drawerHeightRef.current = clampedHeight;
1006 if (!resizeStateRef.current) {
1007 syncHeight(clampedHeight);
1009 setResizeEpoch((value) => value + 1);
1010 };
1011 window.addEventListener("resize", onWindowResize);
1012 return () => {
1013 window.removeEventListener("resize", onWindowResize);
1014 };
1015 }, [syncHeight, visible]);
1016​
1017 useEffect(() => {
1018 if (!visible) {
1019 return;
1021 setResizeEpoch((value) => value + 1);
1022 }, [visible]);
1023​
1024 useEffect(() => {
1025 return () => {
1026 syncHeight(drawerHeightRef.current);
1027 };
1028 }, [syncHeight]);
1029​
1030 return (
1031 <aside
1032 className="thread-terminal-drawer relative flex min-w-0 shrink-0 flex-col overflow-hidden border-t border-border/80 bg-background"
1033 style={{ height: `${drawerHeight}px` }}
1035 <div
1036 className="absolute inset-x-0 top-0 z-20 h-1.5 cursor-row-resize"
1037 onPointerDown={handleResizePointerDown}
1038 onPointerMove={handleResizePointerMove}
1039 onPointerUp={handleResizePointerEnd}
1040 onPointerCancel={handleResizePointerEnd}
1041 />
1042​
1043 {!hasTerminalSidebar && (
1044 <div className="pointer-events-none absolute right-2 top-2 z-20">
1045 <div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
1046 <TerminalActionButton
1047 className={`p-1 text-foreground/90 transition-colors ${
1048 hasReachedSplitLimit
1049 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1050 : "hover:bg-accent"
1051 }`}
1052 onClick={onSplitTerminalAction}
1053 label={splitTerminalActionLabel}
1055 <SquareSplitHorizontal className="size-3.25" />
1056 </TerminalActionButton>
1057 <div className="h-4 w-px bg-border/80" />
1058 <TerminalActionButton
1059 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1060 onClick={onNewTerminalAction}
1061 label={newTerminalActionLabel}
1063 <Plus className="size-3.25" />
1064 </TerminalActionButton>
1065 <div className="h-4 w-px bg-border/80" />
1066 <TerminalActionButton
1067 className="p-1 text-foreground/90 transition-colors hover:bg-accent"
1068 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1069 label={closeTerminalActionLabel}
1071 <Trash2 className="size-3.25" />
1072 </TerminalActionButton>
1073 </div>
1074 </div>
1075 )}
1076​
1077 <div className="min-h-0 w-full flex-1">
1078 <div className={`flex h-full min-h-0 ${hasTerminalSidebar ? "gap-1.5" : ""}`}>
1079 <div className="min-w-0 flex-1">
1080 {isSplitView ? (
1081 <div
1082 className="grid h-full w-full min-w-0 gap-0 overflow-hidden"
1083 style={{
1084 gridTemplateColumns: `repeat(${visibleTerminalIds.length}, minmax(0, 1fr))`,
1085 }}
1087 {visibleTerminalIds.map((terminalId) => (
1088 <div
1089 key={terminalId}
1090 className={`min-h-0 min-w-0 border-l first:border-l-0 ${
1091 terminalId === resolvedActiveTerminalId ? "border-border" : "border-border/70"
1092 }`}
1093 onMouseDown={() => {
1094 if (terminalId !== resolvedActiveTerminalId) {
1095 onActiveTerminalChange(terminalId);
1097 }}
1099 <div className="h-full p-1">
1100 <TerminalViewport
1101 threadId={threadId}
1102 terminalId={terminalId}
1103 terminalLabel={terminalLabelById.get(terminalId) ?? "Terminal"}
1104 cwd={cwd}
1105 {...(worktreePath !== undefined ? { worktreePath } : {})}
1106 {...(runtimeEnv ? { runtimeEnv } : {})}
1107 onSessionExited={() => onCloseTerminal(terminalId)}
1108 onAddTerminalContext={onAddTerminalContext}
1109 focusRequestId={focusRequestId}
1110 autoFocus={terminalId === resolvedActiveTerminalId}
1111 resizeEpoch={resizeEpoch}
1112 drawerHeight={drawerHeight}
1113 />
1114 </div>
1115 </div>
1116 ))}
1117 </div>
1118 ) : (
1119 <div className="h-full p-1">
1120 <TerminalViewport
1121 key={resolvedActiveTerminalId}
1122 threadId={threadId}
1123 terminalId={resolvedActiveTerminalId}
1124 terminalLabel={terminalLabelById.get(resolvedActiveTerminalId) ?? "Terminal"}
1125 cwd={cwd}
1126 {...(worktreePath !== undefined ? { worktreePath } : {})}
1127 {...(runtimeEnv ? { runtimeEnv } : {})}
1128 onSessionExited={() => onCloseTerminal(resolvedActiveTerminalId)}
1129 onAddTerminalContext={onAddTerminalContext}
1130 focusRequestId={focusRequestId}
1131 autoFocus
1132 resizeEpoch={resizeEpoch}
1133 drawerHeight={drawerHeight}
1134 />
1135 </div>
1136 )}
1137 </div>
1138​
1139 {hasTerminalSidebar && (
1140 <aside className="flex w-36 min-w-36 flex-col border border-border/70 bg-muted/10">
1141 <div className="flex h-[22px] items-stretch justify-end border-b border-border/70">
1142 <div className="inline-flex h-full items-stretch">
1143 <TerminalActionButton
1144 className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
1145 hasReachedSplitLimit
1146 ? "cursor-not-allowed opacity-45 hover:bg-transparent"
1147 : "hover:bg-accent/70"
1148 }`}
1149 onClick={onSplitTerminalAction}
1150 label={splitTerminalActionLabel}
1152 <SquareSplitHorizontal className="size-3.25" />
1153 </TerminalActionButton>
1154 <TerminalActionButton
1155 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1156 onClick={onNewTerminalAction}
1157 label={newTerminalActionLabel}
1159 <Plus className="size-3.25" />
1160 </TerminalActionButton>
1161 <TerminalActionButton
1162 className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
1163 onClick={() => onCloseTerminal(resolvedActiveTerminalId)}
1164 label={closeTerminalActionLabel}
1166 <Trash2 className="size-3.25" />
1167 </TerminalActionButton>
1168 </div>
1169 </div>
1170​
1171 <div className="min-h-0 flex-1 overflow-y-auto px-1 py-1">
1172 {resolvedTerminalGroups.map((terminalGroup, groupIndex) => {
1173 const isGroupActive =
1174 terminalGroup.terminalIds.includes(resolvedActiveTerminalId);
1175 const groupActiveTerminalId = isGroupActive
1176 ? resolvedActiveTerminalId
1177 : (terminalGroup.terminalIds[0] ?? resolvedActiveTerminalId);
1178​
1179 return (
1180 <div key={terminalGroup.id} className="pb-0.5">
1181 {showGroupHeaders && (
1182 <button
1183 type="button"
1184 className={`flex w-full items-center rounded px-1 py-0.5 text-[10px] uppercase tracking-[0.08em] ${
1185 isGroupActive
1186 ? "bg-accent/70 text-foreground"
1187 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1188 }`}
1189 onClick={() => onActiveTerminalChange(groupActiveTerminalId)}
1191 {terminalGroup.terminalIds.length > 1
1192 ? `Split ${groupIndex + 1}`
1193 : `Terminal ${groupIndex + 1}`}
1194 </button>
1195 )}
1196​
1197 <div
1198 className={showGroupHeaders ? "ml-1 border-l border-border/60 pl-1.5" : ""}
1200 {terminalGroup.terminalIds.map((terminalId) => {
1201 const isActive = terminalId === resolvedActiveTerminalId;
1202 const closeTerminalLabel = `Close ${
1203 terminalLabelById.get(terminalId) ?? "terminal"
1204 }${isActive && closeShortcutLabel ? ` (${closeShortcutLabel})` : ""}`;
1205 return (
1206 <div
1207 key={terminalId}
1208 className={`group flex items-center gap-1 rounded px-1 py-0.5 text-[11px] ${
1209 isActive
1210 ? "bg-accent text-foreground"
1211 : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"
1212 }`}
1214 {showGroupHeaders && (
1215 <span className="text-[10px] text-muted-foreground/80">└</span>
1216 )}
1217 <button
1218 type="button"
1219 className="flex min-w-0 flex-1 items-center gap-1 text-left"
1220 onClick={() => onActiveTerminalChange(terminalId)}
1222 <TerminalSquare className="size-3 shrink-0" />
1223 <span className="truncate">
1224 {terminalLabelById.get(terminalId) ?? "Terminal"}
1225 </span>
1226 </button>
1227 {normalizedTerminalIds.length > 1 && (
1228 <Popover>
1229 <PopoverTrigger
1230 openOnHover
1231 render={
1232 <button
1233 type="button"
1234 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"
1235 onClick={() => onCloseTerminal(terminalId)}
1236 aria-label={closeTerminalLabel}
1237 />
1240 <XIcon className="size-2.5" />
1241 </PopoverTrigger>
1242 <PopoverPopup
1243 tooltipStyle
1244 side="bottom"
1245 sideOffset={6}
1246 align="center"
1247 className="pointer-events-none select-none"
1249 {closeTerminalLabel}
1250 </PopoverPopup>
1251 </Popover>
1252 )}
1253 </div>
1254 );
1255 })}
1256 </div>
1257 </div>
1258 );
1259 })}
1260 </div>
1261 </aside>
1262 )}
1263 </div>
1264 </div>
1265 </aside>
1266 );