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