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

ThreadTerminalDrawer.tsx

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