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

ThreadTerminalDrawer.tsx

1,304 lines45.8 KB

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