feat: add integrated terminal with tab system and theme support

- Add terminal view with draggable split panels and multi-tab support
- Implement terminal WebSocket server with password protection
- Add per-terminal font size that persists when moving between tabs
- Support all 12 app themes with matching terminal colors
- Add keyboard shortcut (Ctrl+`) to toggle terminal view
- Include scrollback buffer for session history on reconnect

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
SuperComboGamer
2025-12-13 00:57:28 -05:00
parent 935316cb51
commit 04ccd6f81c
18 changed files with 2972 additions and 6 deletions

View File

@@ -609,6 +609,12 @@ export function Sidebar() {
icon: UserCircle,
shortcut: shortcuts.profiles,
},
{
id: "terminal",
label: "Terminal",
icon: Terminal,
shortcut: shortcuts.terminal,
},
],
},
];

View File

@@ -90,6 +90,7 @@ const SHORTCUT_LABELS: Record<keyof KeyboardShortcuts, string> = {
context: "Context",
settings: "Settings",
profiles: "AI Profiles",
terminal: "Terminal",
toggleSidebar: "Toggle Sidebar",
addFeature: "Add Feature",
addContextFile: "Add Context File",
@@ -100,6 +101,9 @@ const SHORTCUT_LABELS: Record<keyof KeyboardShortcuts, string> = {
cyclePrevProject: "Prev Project",
cycleNextProject: "Next Project",
addProfile: "Add Profile",
splitTerminalRight: "Split Right",
splitTerminalDown: "Split Down",
closeTerminal: "Close Terminal",
};
// Categorize shortcuts for color coding
@@ -110,6 +114,7 @@ const SHORTCUT_CATEGORIES: Record<keyof KeyboardShortcuts, "navigation" | "ui" |
context: "navigation",
settings: "navigation",
profiles: "navigation",
terminal: "navigation",
toggleSidebar: "ui",
addFeature: "action",
addContextFile: "action",
@@ -120,6 +125,9 @@ const SHORTCUT_CATEGORIES: Record<keyof KeyboardShortcuts, "navigation" | "ui" |
cyclePrevProject: "action",
cycleNextProject: "action",
addProfile: "action",
splitTerminalRight: "action",
splitTerminalDown: "action",
closeTerminal: "action",
};
// Category colors

View File

@@ -0,0 +1,621 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import {
Terminal as TerminalIcon,
Plus,
Lock,
Unlock,
SplitSquareHorizontal,
SplitSquareVertical,
Loader2,
AlertCircle,
RefreshCw,
X,
SquarePlus,
} from "lucide-react";
import { useAppStore, type TerminalPanelContent, type TerminalTab } from "@/store/app-store";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Panel,
PanelGroup,
PanelResizeHandle,
} from "react-resizable-panels";
import { TerminalPanel } from "./terminal-view/terminal-panel";
import {
DndContext,
DragEndEvent,
DragStartEvent,
DragOverEvent,
PointerSensor,
useSensor,
useSensors,
closestCenter,
DragOverlay,
useDroppable,
} from "@dnd-kit/core";
import { cn } from "@/lib/utils";
interface TerminalStatus {
enabled: boolean;
passwordRequired: boolean;
platform: {
platform: string;
isWSL: boolean;
defaultShell: string;
arch: string;
};
}
// Tab component with drop target support
function TerminalTabButton({
tab,
isActive,
onClick,
onClose,
isDropTarget,
}: {
tab: TerminalTab;
isActive: boolean;
onClick: () => void;
onClose: () => void;
isDropTarget: boolean;
}) {
const { setNodeRef, isOver } = useDroppable({
id: `tab-${tab.id}`,
data: { type: "tab", tabId: tab.id },
});
return (
<div
ref={setNodeRef}
className={cn(
"flex items-center gap-1 px-3 py-1.5 text-sm rounded-t-md border-b-2 cursor-pointer transition-colors",
isActive
? "bg-background border-brand-500 text-foreground"
: "bg-muted border-transparent text-muted-foreground hover:text-foreground hover:bg-accent",
isOver && isDropTarget && "ring-2 ring-green-500"
)}
onClick={onClick}
>
<TerminalIcon className="h-3 w-3" />
<span className="max-w-24 truncate">{tab.name}</span>
<button
className="ml-1 p-0.5 rounded hover:bg-accent text-muted-foreground hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
onClose();
}}
>
<X className="h-3 w-3" />
</button>
</div>
);
}
// New tab drop zone
function NewTabDropZone({ isDropTarget }: { isDropTarget: boolean }) {
const { setNodeRef, isOver } = useDroppable({
id: "new-tab-zone",
data: { type: "new-tab" },
});
return (
<div
ref={setNodeRef}
className={cn(
"flex items-center justify-center px-3 py-1.5 rounded-t-md border-2 border-dashed transition-all",
isOver && isDropTarget
? "border-green-500 bg-green-500/10 text-green-500"
: "border-transparent text-muted-foreground hover:border-border"
)}
>
<SquarePlus className="h-4 w-4" />
</div>
);
}
export function TerminalView() {
const {
terminalState,
setTerminalUnlocked,
addTerminalToLayout,
removeTerminalFromLayout,
setActiveTerminalSession,
swapTerminals,
currentProject,
addTerminalTab,
removeTerminalTab,
setActiveTerminalTab,
moveTerminalToTab,
setTerminalPanelFontSize,
} = useAppStore();
const [status, setStatus] = useState<TerminalStatus | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [password, setPassword] = useState("");
const [authLoading, setAuthLoading] = useState(false);
const [authError, setAuthError] = useState<string | null>(null);
const [activeDragId, setActiveDragId] = useState<string | null>(null);
const [dragOverTabId, setDragOverTabId] = useState<string | null>(null);
const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3008";
// Get active tab
const activeTab = terminalState.tabs.find(t => t.id === terminalState.activeTabId);
// DnD sensors with activation constraint to avoid accidental drags
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
})
);
// Handle drag start
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveDragId(event.active.id as string);
}, []);
// Handle drag over - track which tab we're hovering
const handleDragOver = useCallback((event: DragOverEvent) => {
const { over } = event;
if (over?.data?.current?.type === "tab") {
setDragOverTabId(over.data.current.tabId);
} else if (over?.data?.current?.type === "new-tab") {
setDragOverTabId("new");
} else {
setDragOverTabId(null);
}
}, []);
// Handle drag end
const handleDragEnd = useCallback((event: DragEndEvent) => {
const { active, over } = event;
setActiveDragId(null);
setDragOverTabId(null);
if (!over) return;
const activeId = active.id as string;
const overData = over.data?.current;
// If dropped on a tab, move terminal to that tab
if (overData?.type === "tab") {
moveTerminalToTab(activeId, overData.tabId);
return;
}
// If dropped on new tab zone, create new tab with this terminal
if (overData?.type === "new-tab") {
moveTerminalToTab(activeId, "new");
return;
}
// Otherwise, swap terminals within current tab
if (active.id !== over.id) {
swapTerminals(activeId, over.id as string);
}
}, [swapTerminals, moveTerminalToTab]);
// Fetch terminal status
const fetchStatus = useCallback(async () => {
try {
setLoading(true);
setError(null);
const response = await fetch(`${serverUrl}/api/terminal/status`);
const data = await response.json();
if (data.success) {
setStatus(data.data);
if (!data.data.passwordRequired) {
setTerminalUnlocked(true);
}
} else {
setError(data.error || "Failed to get terminal status");
}
} catch (err) {
setError("Failed to connect to server");
console.error("[Terminal] Status fetch error:", err);
} finally {
setLoading(false);
}
}, [serverUrl, setTerminalUnlocked]);
useEffect(() => {
fetchStatus();
}, [fetchStatus]);
// Handle password authentication
const handleAuth = async (e: React.FormEvent) => {
e.preventDefault();
setAuthLoading(true);
setAuthError(null);
try {
const response = await fetch(`${serverUrl}/api/terminal/auth`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ password }),
});
const data = await response.json();
if (data.success) {
setTerminalUnlocked(true, data.data.token);
setPassword("");
} else {
setAuthError(data.error || "Authentication failed");
}
} catch (err) {
setAuthError("Failed to authenticate");
console.error("[Terminal] Auth error:", err);
} finally {
setAuthLoading(false);
}
};
// Create a new terminal session
const createTerminal = async (direction?: "horizontal" | "vertical") => {
try {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (terminalState.authToken) {
headers["X-Terminal-Token"] = terminalState.authToken;
}
const response = await fetch(`${serverUrl}/api/terminal/sessions`, {
method: "POST",
headers,
body: JSON.stringify({
cwd: currentProject?.path || undefined,
cols: 80,
rows: 24,
}),
});
const data = await response.json();
if (data.success) {
addTerminalToLayout(data.data.id, direction);
} else {
console.error("[Terminal] Failed to create session:", data.error);
}
} catch (err) {
console.error("[Terminal] Create session error:", err);
}
};
// Create terminal in new tab
const createTerminalInNewTab = async () => {
const tabId = addTerminalTab();
try {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (terminalState.authToken) {
headers["X-Terminal-Token"] = terminalState.authToken;
}
const response = await fetch(`${serverUrl}/api/terminal/sessions`, {
method: "POST",
headers,
body: JSON.stringify({
cwd: currentProject?.path || undefined,
cols: 80,
rows: 24,
}),
});
const data = await response.json();
if (data.success) {
// Add to the newly created tab
const { addTerminalToTab } = useAppStore.getState();
addTerminalToTab(data.data.id, tabId);
}
} catch (err) {
console.error("[Terminal] Create session error:", err);
}
};
// Kill a terminal session
const killTerminal = async (sessionId: string) => {
try {
const headers: Record<string, string> = {};
if (terminalState.authToken) {
headers["X-Terminal-Token"] = terminalState.authToken;
}
await fetch(`${serverUrl}/api/terminal/sessions/${sessionId}`, {
method: "DELETE",
headers,
});
removeTerminalFromLayout(sessionId);
} catch (err) {
console.error("[Terminal] Kill session error:", err);
}
};
// Get a stable key for a panel
const getPanelKey = (panel: TerminalPanelContent): string => {
if (panel.type === "terminal") {
return panel.sessionId;
}
return `split-${panel.direction}-${panel.panels.map(getPanelKey).join("-")}`;
};
// Render panel content recursively
const renderPanelContent = (content: TerminalPanelContent): React.ReactNode => {
if (content.type === "terminal") {
// Use per-terminal fontSize or fall back to default
const terminalFontSize = content.fontSize ?? terminalState.defaultFontSize;
return (
<TerminalPanel
key={content.sessionId}
sessionId={content.sessionId}
authToken={terminalState.authToken}
isActive={terminalState.activeSessionId === content.sessionId}
onFocus={() => setActiveTerminalSession(content.sessionId)}
onClose={() => killTerminal(content.sessionId)}
onSplitHorizontal={() => createTerminal("horizontal")}
onSplitVertical={() => createTerminal("vertical")}
isDragging={activeDragId === content.sessionId}
isDropTarget={activeDragId !== null && activeDragId !== content.sessionId}
fontSize={terminalFontSize}
onFontSizeChange={(size) => setTerminalPanelFontSize(content.sessionId, size)}
/>
);
}
const isHorizontal = content.direction === "horizontal";
const defaultSizePerPanel = 100 / content.panels.length;
return (
<PanelGroup direction={content.direction}>
{content.panels.map((panel, index) => {
const panelSize = panel.type === "terminal" && panel.size
? panel.size
: defaultSizePerPanel;
return (
<React.Fragment key={getPanelKey(panel)}>
{index > 0 && (
<PanelResizeHandle
className={
isHorizontal
? "w-1 h-full bg-border hover:bg-brand-500 transition-colors data-[resize-handle-state=hover]:bg-brand-500 data-[resize-handle-state=drag]:bg-brand-500"
: "h-1 w-full bg-border hover:bg-brand-500 transition-colors data-[resize-handle-state=hover]:bg-brand-500 data-[resize-handle-state=drag]:bg-brand-500"
}
/>
)}
<Panel defaultSize={panelSize} minSize={15}>
{renderPanelContent(panel)}
</Panel>
</React.Fragment>
);
})}
</PanelGroup>
);
};
// Loading state
if (loading) {
return (
<div className="flex-1 flex items-center justify-center">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
// Error state
if (error) {
return (
<div className="flex-1 flex flex-col items-center justify-center text-center p-6">
<div className="p-4 rounded-full bg-destructive/10 mb-4">
<AlertCircle className="h-12 w-12 text-destructive" />
</div>
<h2 className="text-lg font-medium mb-2">Terminal Unavailable</h2>
<p className="text-muted-foreground max-w-md mb-4">{error}</p>
<Button variant="outline" onClick={fetchStatus}>
<RefreshCw className="h-4 w-4 mr-2" />
Retry
</Button>
</div>
);
}
// Disabled state
if (!status?.enabled) {
return (
<div className="flex-1 flex flex-col items-center justify-center text-center p-6">
<div className="p-4 rounded-full bg-muted/50 mb-4">
<TerminalIcon className="h-12 w-12 text-muted-foreground" />
</div>
<h2 className="text-lg font-medium mb-2">Terminal Disabled</h2>
<p className="text-muted-foreground max-w-md">
Terminal access has been disabled. Set <code className="px-1.5 py-0.5 rounded bg-muted">TERMINAL_ENABLED=true</code> in your server .env file to enable it.
</p>
</div>
);
}
// Password gate
if (status.passwordRequired && !terminalState.isUnlocked) {
return (
<div className="flex-1 flex flex-col items-center justify-center text-center p-6">
<div className="p-4 rounded-full bg-muted/50 mb-4">
<Lock className="h-12 w-12 text-muted-foreground" />
</div>
<h2 className="text-lg font-medium mb-2">Terminal Protected</h2>
<p className="text-muted-foreground max-w-md mb-6">
Terminal access requires authentication. Enter the password to unlock.
</p>
<form onSubmit={handleAuth} className="w-full max-w-xs space-y-4">
<Input
type="password"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={authLoading}
autoFocus
/>
{authError && (
<p className="text-sm text-destructive">{authError}</p>
)}
<Button type="submit" className="w-full" disabled={authLoading || !password}>
{authLoading ? (
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
) : (
<Unlock className="h-4 w-4 mr-2" />
)}
Unlock Terminal
</Button>
</form>
{status.platform && (
<p className="text-xs text-muted-foreground mt-6">
Platform: {status.platform.platform}
{status.platform.isWSL && " (WSL)"}
{" | "}Shell: {status.platform.defaultShell}
</p>
)}
</div>
);
}
// No terminals yet - show welcome screen
if (terminalState.tabs.length === 0) {
return (
<div className="flex-1 flex flex-col items-center justify-center text-center p-6">
<div className="p-4 rounded-full bg-brand-500/10 mb-4">
<TerminalIcon className="h-12 w-12 text-brand-500" />
</div>
<h2 className="text-lg font-medium mb-2">Terminal</h2>
<p className="text-muted-foreground max-w-md mb-6">
Create a new terminal session to start executing commands.
{currentProject && (
<span className="block mt-2 text-sm">
Working directory: <code className="px-1.5 py-0.5 rounded bg-muted">{currentProject.path}</code>
</span>
)}
</p>
<Button onClick={() => createTerminal()}>
<Plus className="h-4 w-4 mr-2" />
New Terminal
</Button>
{status?.platform && (
<p className="text-xs text-muted-foreground mt-6">
Platform: {status.platform.platform}
{status.platform.isWSL && " (WSL)"}
{" | "}Shell: {status.platform.defaultShell}
</p>
)}
</div>
);
}
// Terminal view with tabs
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
<div className="flex-1 flex flex-col overflow-hidden">
{/* Tab bar */}
<div className="flex items-center bg-card border-b border-border px-2">
{/* Tabs */}
<div className="flex items-center gap-1 flex-1 overflow-x-auto py-1">
{terminalState.tabs.map((tab) => (
<TerminalTabButton
key={tab.id}
tab={tab}
isActive={tab.id === terminalState.activeTabId}
onClick={() => setActiveTerminalTab(tab.id)}
onClose={() => removeTerminalTab(tab.id)}
isDropTarget={activeDragId !== null}
/>
))}
{/* New tab drop zone (visible when dragging) */}
{activeDragId && (
<NewTabDropZone isDropTarget={true} />
)}
{/* New tab button */}
<button
className="flex items-center justify-center p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground"
onClick={createTerminalInNewTab}
title="New Tab"
>
<Plus className="h-4 w-4" />
</button>
</div>
{/* Toolbar buttons */}
<div className="flex items-center gap-1 pl-2 border-l border-border">
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-foreground"
onClick={() => createTerminal("horizontal")}
title="Split Right"
>
<SplitSquareHorizontal className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-muted-foreground hover:text-foreground"
onClick={() => createTerminal("vertical")}
title="Split Down"
>
<SplitSquareVertical className="h-4 w-4" />
</Button>
</div>
</div>
{/* Active tab content */}
<div className="flex-1 overflow-hidden bg-background">
{activeTab?.layout ? (
renderPanelContent(activeTab.layout)
) : (
<div className="flex-1 flex flex-col items-center justify-center text-center p-6">
<p className="text-muted-foreground mb-4">This tab is empty</p>
<Button
variant="outline"
size="sm"
onClick={() => createTerminal()}
>
<Plus className="h-4 w-4 mr-2" />
New Terminal
</Button>
</div>
)}
</div>
</div>
{/* Drag overlay */}
<DragOverlay dropAnimation={null} zIndex={1000}>
{activeDragId ? (
<div className="relative inline-flex items-center gap-2 px-3.5 py-2 bg-card border-2 border-brand-500 rounded-lg shadow-xl pointer-events-none overflow-hidden">
<TerminalIcon className="h-4 w-4 text-brand-500 shrink-0" />
<span className="text-sm font-medium text-foreground whitespace-nowrap">
{dragOverTabId === "new"
? "New tab"
: dragOverTabId
? "Move to tab"
: "Terminal"}
</span>
</div>
) : null}
</DragOverlay>
</DndContext>
);
}

View File

@@ -0,0 +1,562 @@
"use client";
import { useEffect, useRef, useCallback, useState } from "react";
import {
X,
SplitSquareHorizontal,
SplitSquareVertical,
GripHorizontal,
Terminal,
ZoomIn,
ZoomOut,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useDraggable, useDroppable } from "@dnd-kit/core";
import { useAppStore } from "@/store/app-store";
import { getTerminalTheme } from "@/config/terminal-themes";
// Font size constraints
const MIN_FONT_SIZE = 8;
const MAX_FONT_SIZE = 32;
const DEFAULT_FONT_SIZE = 14;
interface TerminalPanelProps {
sessionId: string;
authToken: string | null;
isActive: boolean;
onFocus: () => void;
onClose: () => void;
onSplitHorizontal: () => void;
onSplitVertical: () => void;
isDragging?: boolean;
isDropTarget?: boolean;
fontSize: number;
onFontSizeChange: (size: number) => void;
}
// Type for xterm Terminal - we'll use any since we're dynamically importing
type XTerminal = InstanceType<typeof import("@xterm/xterm").Terminal>;
type XFitAddon = InstanceType<typeof import("@xterm/addon-fit").FitAddon>;
export function TerminalPanel({
sessionId,
authToken,
isActive,
onFocus,
onClose,
onSplitHorizontal,
onSplitVertical,
isDragging = false,
isDropTarget = false,
fontSize,
onFontSizeChange,
}: TerminalPanelProps) {
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const xtermRef = useRef<XTerminal | null>(null);
const fitAddonRef = useRef<XFitAddon | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const [isTerminalReady, setIsTerminalReady] = useState(false);
// Get effective theme from store
const getEffectiveTheme = useAppStore((state) => state.getEffectiveTheme);
const effectiveTheme = getEffectiveTheme();
// Use refs for callbacks and values to avoid effect re-runs
const onFocusRef = useRef(onFocus);
onFocusRef.current = onFocus;
const fontSizeRef = useRef(fontSize);
fontSizeRef.current = fontSize;
const themeRef = useRef(effectiveTheme);
themeRef.current = effectiveTheme;
// Zoom functions - use the prop callback
const zoomIn = useCallback(() => {
onFontSizeChange(Math.min(fontSize + 1, MAX_FONT_SIZE));
}, [fontSize, onFontSizeChange]);
const zoomOut = useCallback(() => {
onFontSizeChange(Math.max(fontSize - 1, MIN_FONT_SIZE));
}, [fontSize, onFontSizeChange]);
const resetZoom = useCallback(() => {
onFontSizeChange(DEFAULT_FONT_SIZE);
}, [onFontSizeChange]);
const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL || "http://localhost:3008";
const wsUrl = serverUrl.replace(/^http/, "ws");
// Draggable - only the drag handle triggers drag
const {
attributes: dragAttributes,
listeners: dragListeners,
setNodeRef: setDragRef,
} = useDraggable({
id: sessionId,
});
// Droppable - the entire panel is a drop target
const {
setNodeRef: setDropRef,
isOver,
} = useDroppable({
id: sessionId,
});
// Initialize terminal - dynamically import xterm to avoid SSR issues
useEffect(() => {
if (!terminalRef.current) return;
let mounted = true;
const initTerminal = async () => {
// Dynamically import xterm modules
const [
{ Terminal },
{ FitAddon },
{ WebglAddon },
] = await Promise.all([
import("@xterm/xterm"),
import("@xterm/addon-fit"),
import("@xterm/addon-webgl"),
]);
// Also import CSS
await import("@xterm/xterm/css/xterm.css");
if (!mounted || !terminalRef.current) return;
// Get terminal theme matching the app theme
const terminalTheme = getTerminalTheme(themeRef.current);
// Create terminal instance with the current global font size and theme
const terminal = new Terminal({
cursorBlink: true,
cursorStyle: "block",
fontSize: fontSizeRef.current,
fontFamily: "Menlo, Monaco, 'Courier New', monospace",
theme: terminalTheme,
allowProposedApi: true,
});
// Create fit addon
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
// Open terminal
terminal.open(terminalRef.current);
// Try to load WebGL addon for better performance
try {
const webglAddon = new WebglAddon();
webglAddon.onContextLoss(() => {
webglAddon.dispose();
});
terminal.loadAddon(webglAddon);
} catch {
console.warn("[Terminal] WebGL addon not available, falling back to canvas");
}
// Fit terminal to container
setTimeout(() => {
fitAddon.fit();
}, 0);
xtermRef.current = terminal;
fitAddonRef.current = fitAddon;
setIsTerminalReady(true);
// Handle focus - use ref to avoid re-running effect
terminal.onData(() => {
onFocusRef.current();
});
};
initTerminal();
// Cleanup
return () => {
mounted = false;
if (xtermRef.current) {
xtermRef.current.dispose();
xtermRef.current = null;
}
fitAddonRef.current = null;
setIsTerminalReady(false);
};
}, []); // No dependencies - only run once on mount
// Connect WebSocket - wait for terminal to be ready
useEffect(() => {
if (!isTerminalReady || !sessionId) return;
const terminal = xtermRef.current;
if (!terminal) return;
const connect = () => {
// Build WebSocket URL with token
let url = `${wsUrl}/api/terminal/ws?sessionId=${sessionId}`;
if (authToken) {
url += `&token=${encodeURIComponent(authToken)}`;
}
const ws = new WebSocket(url);
wsRef.current = ws;
ws.onopen = () => {
console.log(`[Terminal] WebSocket connected for session ${sessionId}`);
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
switch (msg.type) {
case "data":
terminal.write(msg.data);
break;
case "scrollback":
// Replay scrollback buffer (previous terminal output)
if (msg.data) {
terminal.write(msg.data);
}
break;
case "connected":
console.log(`[Terminal] Session connected: ${msg.shell} in ${msg.cwd}`);
break;
case "exit":
terminal.write(`\r\n\x1b[33m[Process exited with code ${msg.exitCode}]\x1b[0m\r\n`);
break;
case "pong":
// Heartbeat response
break;
}
} catch (err) {
console.error("[Terminal] Message parse error:", err);
}
};
ws.onclose = (event) => {
console.log(`[Terminal] WebSocket closed for session ${sessionId}:`, event.code, event.reason);
wsRef.current = null;
// Don't reconnect if closed normally or auth failed
if (event.code === 1000 || event.code === 4001 || event.code === 4003) {
return;
}
// Attempt reconnect after a delay
reconnectTimeoutRef.current = setTimeout(() => {
if (xtermRef.current) {
console.log(`[Terminal] Attempting reconnect for session ${sessionId}`);
connect();
}
}, 2000);
};
ws.onerror = (error) => {
console.error(`[Terminal] WebSocket error for session ${sessionId}:`, error);
};
};
connect();
// Handle terminal input
const dataHandler = terminal.onData((data) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "input", data }));
}
});
// Cleanup
return () => {
dataHandler.dispose();
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
}
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
};
}, [sessionId, authToken, wsUrl, isTerminalReady]);
// Handle resize
const handleResize = useCallback(() => {
if (fitAddonRef.current && xtermRef.current) {
fitAddonRef.current.fit();
const { cols, rows } = xtermRef.current;
// Send resize to server
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "resize", cols, rows }));
}
}
}, []);
// Resize observer
useEffect(() => {
const container = terminalRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() => {
handleResize();
});
resizeObserver.observe(container);
// Also handle window resize
window.addEventListener("resize", handleResize);
return () => {
resizeObserver.disconnect();
window.removeEventListener("resize", handleResize);
};
}, [handleResize]);
// Focus terminal when becoming active
useEffect(() => {
if (isActive && xtermRef.current) {
xtermRef.current.focus();
}
}, [isActive]);
// Update terminal font size when it changes
useEffect(() => {
if (xtermRef.current && isTerminalReady) {
xtermRef.current.options.fontSize = fontSize;
// Refit after font size change
if (fitAddonRef.current) {
fitAddonRef.current.fit();
// Notify server of new dimensions
const { cols, rows } = xtermRef.current;
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: "resize", cols, rows }));
}
}
}
}, [fontSize, isTerminalReady]);
// Update terminal theme when app theme changes
useEffect(() => {
if (xtermRef.current && isTerminalReady) {
const terminalTheme = getTerminalTheme(effectiveTheme);
xtermRef.current.options.theme = terminalTheme;
}
}, [effectiveTheme, isTerminalReady]);
// Handle keyboard shortcuts for zoom (Ctrl+Plus, Ctrl+Minus, Ctrl+0)
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const handleKeyDown = (e: KeyboardEvent) => {
// Only handle if Ctrl (or Cmd on Mac) is pressed
if (!e.ctrlKey && !e.metaKey) return;
// Ctrl/Cmd + Plus or Ctrl/Cmd + = (for keyboards without numpad)
if (e.key === "+" || e.key === "=") {
e.preventDefault();
e.stopPropagation();
zoomIn();
return;
}
// Ctrl/Cmd + Minus
if (e.key === "-") {
e.preventDefault();
e.stopPropagation();
zoomOut();
return;
}
// Ctrl/Cmd + 0 to reset
if (e.key === "0") {
e.preventDefault();
e.stopPropagation();
resetZoom();
return;
}
};
container.addEventListener("keydown", handleKeyDown);
return () => container.removeEventListener("keydown", handleKeyDown);
}, [zoomIn, zoomOut, resetZoom]);
// Handle mouse wheel zoom (Ctrl+Wheel)
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const handleWheel = (e: WheelEvent) => {
// Only zoom if Ctrl (or Cmd on Mac) is pressed
if (!e.ctrlKey && !e.metaKey) return;
e.preventDefault();
e.stopPropagation();
if (e.deltaY < 0) {
// Scroll up = zoom in
zoomIn();
} else if (e.deltaY > 0) {
// Scroll down = zoom out
zoomOut();
}
};
// Use passive: false to allow preventDefault
container.addEventListener("wheel", handleWheel, { passive: false });
return () => container.removeEventListener("wheel", handleWheel);
}, [zoomIn, zoomOut]);
// Combine refs for the container
const setRefs = useCallback((node: HTMLDivElement | null) => {
containerRef.current = node;
setDropRef(node);
}, [setDropRef]);
// Get current terminal theme for xterm styling
const currentTerminalTheme = getTerminalTheme(effectiveTheme);
return (
<div
ref={setRefs}
className={cn(
"flex flex-col h-full relative",
isActive && "ring-1 ring-brand-500 ring-inset",
// Visual feedback when dragging this terminal
isDragging && "opacity-50",
// Visual feedback when hovering over as drop target
isOver && isDropTarget && "ring-2 ring-green-500 ring-inset"
)}
onClick={onFocus}
tabIndex={0}
data-terminal-container="true"
>
{/* Drop indicator overlay */}
{isOver && isDropTarget && (
<div className="absolute inset-0 bg-green-500/10 z-10 pointer-events-none flex items-center justify-center">
<div className="px-3 py-2 bg-green-500/90 rounded-md text-white text-sm font-medium">
Drop to swap
</div>
</div>
)}
{/* Header bar with drag handle - uses app theme CSS variables */}
<div className="flex items-center h-7 px-1 shrink-0 bg-card border-b border-border">
{/* Drag handle */}
<button
ref={setDragRef}
{...dragAttributes}
{...dragListeners}
className={cn(
"p-1 rounded cursor-grab active:cursor-grabbing mr-1 transition-colors text-muted-foreground hover:text-foreground hover:bg-accent",
isDragging && "cursor-grabbing"
)}
title="Drag to swap terminals"
>
<GripHorizontal className="h-3 w-3" />
</button>
{/* Terminal icon and label */}
<div className="flex items-center gap-1.5 flex-1 min-w-0">
<Terminal className="h-3 w-3 shrink-0 text-muted-foreground" />
<span className="text-xs truncate text-foreground">
bash
</span>
{/* Font size indicator - only show when not default */}
{fontSize !== DEFAULT_FONT_SIZE && (
<button
onClick={(e) => {
e.stopPropagation();
resetZoom();
}}
className="text-[10px] px-1 rounded transition-colors text-muted-foreground hover:text-foreground hover:bg-accent"
title="Click to reset zoom (Ctrl+0)"
>
{fontSize}px
</button>
)}
</div>
{/* Zoom and action buttons */}
<div className="flex items-center gap-0.5">
{/* Zoom controls */}
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation();
zoomOut();
}}
title="Zoom Out (Ctrl+-)"
disabled={fontSize <= MIN_FONT_SIZE}
>
<ZoomOut className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation();
zoomIn();
}}
title="Zoom In (Ctrl++)"
disabled={fontSize >= MAX_FONT_SIZE}
>
<ZoomIn className="h-3 w-3" />
</Button>
<div className="w-px h-3 mx-0.5 bg-border" />
{/* Split/close buttons */}
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation();
onSplitHorizontal();
}}
title="Split Right (Cmd+D)"
>
<SplitSquareHorizontal className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation();
onSplitVertical();
}}
title="Split Down (Cmd+Shift+D)"
>
<SplitSquareVertical className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-5 w-5 text-muted-foreground hover:text-destructive"
onClick={(e) => {
e.stopPropagation();
onClose();
}}
title="Close Terminal (Cmd+W)"
>
<X className="h-3 w-3" />
</Button>
</div>
</div>
{/* Terminal container - uses terminal theme */}
<div
ref={terminalRef}
className="flex-1 overflow-hidden"
style={{ backgroundColor: currentTerminalTheme.background }}
/>
</div>
);
}