"use client" import type React from "react" import { useEffect, useRef, useState, useCallback } from "react" import { API_PORT } from "@/lib/api-config" import { Activity, Trash2, X, Search, Send, Wifi, WifiOff, Lightbulb, Terminal, Plus, LayoutGrid, Columns, Rows, } from "lucide-react" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog" import { Input } from "@/components/ui/input" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import type { CheatSheetResult } from "@/lib/cheat-sheet-result" // Declare CheatSheetResult here type TerminalPanelProps = { websocketUrl?: string onClose?: () => void } interface TerminalInstance { id: string title: string term: any ws: WebSocket | null isConnected: boolean // containerRef: React.RefObject // This is no longer needed as we use callback refs } function getWebSocketUrl(): string { if (typeof window === "undefined") { return "ws://localhost:8008/ws/terminal" } const { protocol, hostname, port } = window.location const isStandardPort = port === "" || port === "80" || port === "443" const wsProtocol = protocol === "https:" ? "wss:" : "ws:" if (isStandardPort) { return `${wsProtocol}//${hostname}/ws/terminal` } else { return `${wsProtocol}//${hostname}:${API_PORT}/ws/terminal` } } const proxmoxCommands = [ { cmd: "pvesh get /nodes", desc: "List all Proxmox nodes" }, { cmd: "pvesh get /nodes/{node}/qemu", desc: "List VMs on a node" }, { cmd: "pvesh get /nodes/{node}/lxc", desc: "List LXC containers on a node" }, { cmd: "pvesh get /nodes/{node}/storage", desc: "List storage on a node" }, { cmd: "pvesh get /nodes/{node}/network", desc: "List network interfaces" }, { cmd: "qm list", desc: "List all QEMU/KVM virtual machines" }, { cmd: "qm start ", desc: "Start a virtual machine" }, { cmd: "qm stop ", desc: "Stop a virtual machine" }, { cmd: "qm shutdown ", desc: "Shutdown a virtual machine gracefully" }, { cmd: "qm status ", desc: "Show VM status" }, { cmd: "qm config ", desc: "Show VM configuration" }, { cmd: "qm snapshot ", desc: "Create VM snapshot" }, { cmd: "pct list", desc: "List all LXC containers" }, { cmd: "pct start ", desc: "Start LXC container" }, { cmd: "pct stop ", desc: "Stop LXC container" }, { cmd: "pct enter ", desc: "Enter LXC container console" }, { cmd: "pct config ", desc: "Show container configuration" }, { cmd: "pvesm status", desc: "Show storage status" }, { cmd: "pvesm list ", desc: "List storage content" }, { cmd: "pveperf", desc: "Test Proxmox system performance" }, { cmd: "pveversion", desc: "Show Proxmox VE version" }, { cmd: "systemctl status pve-cluster", desc: "Check cluster status" }, { cmd: "pvecm status", desc: "Show cluster status" }, { cmd: "pvecm nodes", desc: "List cluster nodes" }, { cmd: "zpool status", desc: "Show ZFS pool status" }, { cmd: "zpool list", desc: "List all ZFS pools" }, { cmd: "zfs list", desc: "List all ZFS datasets" }, { cmd: "ls -la", desc: "List all files with details" }, { cmd: "cd /path/to/dir", desc: "Change directory" }, { cmd: "mkdir dirname", desc: "Create new directory" }, { cmd: "rm -rf dirname", desc: "Remove directory recursively" }, { cmd: "cp source dest", desc: "Copy files or directories" }, { cmd: "mv source dest", desc: "Move or rename files" }, { cmd: "cat filename", desc: "Display file contents" }, { cmd: "grep 'pattern' file", desc: "Search for pattern in file" }, { cmd: "find . -name 'file'", desc: "Find files by name" }, { cmd: "chmod 755 file", desc: "Change file permissions" }, { cmd: "chown user:group file", desc: "Change file owner" }, { cmd: "tar -xzf file.tar.gz", desc: "Extract tar.gz archive" }, { cmd: "tar -czf archive.tar.gz dir/", desc: "Create tar.gz archive" }, { cmd: "df -h", desc: "Show disk usage" }, { cmd: "du -sh *", desc: "Show directory sizes" }, { cmd: "free -h", desc: "Show memory usage" }, { cmd: "top", desc: "Show running processes" }, { cmd: "ps aux | grep process", desc: "Find running process" }, { cmd: "kill -9 PID", desc: "Force kill process" }, { cmd: "systemctl status service", desc: "Check service status" }, { cmd: "systemctl start service", desc: "Start a service" }, { cmd: "systemctl stop service", desc: "Stop a service" }, { cmd: "systemctl restart service", desc: "Restart a service" }, { cmd: "apt update && apt upgrade", desc: "Update Debian/Ubuntu packages" }, { cmd: "apt install package", desc: "Install package on Debian/Ubuntu" }, { cmd: "apt remove package", desc: "Remove package" }, { cmd: "docker ps", desc: "List running containers" }, { cmd: "docker images", desc: "List Docker images" }, { cmd: "docker exec -it container bash", desc: "Enter container shell" }, { cmd: "ip addr show", desc: "Show IP addresses" }, { cmd: "ping host", desc: "Test network connectivity" }, { cmd: "curl -I url", desc: "Get HTTP headers" }, { cmd: "wget url", desc: "Download file from URL" }, { cmd: "ssh user@host", desc: "Connect via SSH" }, { cmd: "scp file user@host:/path", desc: "Copy file via SSH" }, { cmd: "tail -f /var/log/syslog", desc: "Follow log file in real-time" }, { cmd: "history", desc: "Show command history" }, { cmd: "clear", desc: "Clear terminal screen" }, ] export const TerminalPanel: React.FC = ({ websocketUrl, onClose }) => { const [terminals, setTerminals] = useState([]) const [activeTerminalId, setActiveTerminalId] = useState("") const [layout, setLayout] = useState<"single" | "vertical" | "horizontal" | "grid">("single") const [isMobile, setIsMobile] = useState(false) const [searchModalOpen, setSearchModalOpen] = useState(false) const [searchQuery, setSearchQuery] = useState("") const [filteredCommands, setFilteredCommands] = useState>(proxmoxCommands) const [lastKeyPressed, setLastKeyPressed] = useState(null) const [isSearching, setIsSearching] = useState(false) const [searchResults, setSearchResults] = useState([]) const [useOnline, setUseOnline] = useState(true) const containerRefs = useRef<{ [key: string]: HTMLDivElement | null }>({}) const setContainerRef = useCallback( (id: string) => (el: HTMLDivElement | null) => { containerRefs.current[id] = el }, [], ) useEffect(() => { setIsMobile(window.innerWidth < 768) const handleResize = () => setIsMobile(window.innerWidth < 768) window.addEventListener("resize", handleResize) return () => window.removeEventListener("resize", handleResize) }, []) useEffect(() => { if (terminals.length === 0) { addNewTerminal() } }, []) useEffect(() => { const searchCheatSh = async (query: string) => { if (!query.trim()) { setSearchResults([]) setFilteredCommands(proxmoxCommands) return } try { setIsSearching(true) setUseOnline(true) // Format query: replace spaces with + for cheat.sh API const formattedQuery = query.trim().replace(/\s+/g, "+") // Use ?QT options: Q=no comments (code only), T=no syntax highlighting const url = `https://cht.sh/${formattedQuery}?QT` console.log("[v0] Fetching from cheat.sh:", url) const response = await fetch(url, { signal: AbortSignal.timeout(10000), headers: { "User-Agent": "curl/7.68.0", // cheat.sh works better with curl user agent }, }) if (!response.ok) { console.log("[v0] API response not OK:", response.status) throw new Error(`API request failed: ${response.status}`) } const text = await response.text() console.log("[v0] Received response, length:", text.length) if (!text || text.includes("Unknown topic") || text.includes("nothing found")) { throw new Error("No results found") } // Split by double newlines to get separate examples const blocks = text.split(/\n\s*\n/).filter((block) => block.trim()) const examples: string[] = [] for (const block of blocks) { const lines = block.split("\n").filter((line) => { const trimmed = line.trim() // Filter out URLs, metadata, and empty lines return trimmed && !trimmed.startsWith("http") && !trimmed.includes("cheat.sh") && !trimmed.includes("[") // Remove attribution lines like [user] [source] }) if (lines.length > 0) { const example = lines.join("\n").trim() if (example.length > 10 && example.length < 500) { examples.push(example) } } } console.log("[v0] Parsed examples:", examples.length) if (examples.length > 0) { setSearchResults([ { command: query, description: `Results from cheat.sh for "${query}"`, examples: examples.slice(0, 8), // Show up to 8 examples }, ]) } else { throw new Error("No valid examples found") } } catch (error) { console.log("[v0] Falling back to offline mode:", error) setUseOnline(false) const filtered = proxmoxCommands.filter( (item) => item.cmd.toLowerCase().includes(query.toLowerCase()) || item.desc.toLowerCase().includes(query.toLowerCase()), ) setFilteredCommands(filtered) setSearchResults([]) } finally { setIsSearching(false) } } const debounce = setTimeout(() => { if (searchQuery) { searchCheatSh(searchQuery) } else { setSearchResults([]) setFilteredCommands(proxmoxCommands) } }, 500) return () => clearTimeout(debounce) }, [searchQuery]) const addNewTerminal = () => { if (terminals.length >= 4) return const newId = `terminal-${Date.now()}` // containerRefs.current[newId] = useRef(null) // No longer needed setTerminals((prev) => [ ...prev, { id: newId, title: `Terminal ${prev.length + 1}`, term: null, ws: null, isConnected: false, // containerRef: containerRefs.current[newId], // No longer needed }, ]) setActiveTerminalId(newId) } const closeTerminal = (id: string) => { const terminal = terminals.find((t) => t.id === id) if (terminal) { if (terminal.ws) { terminal.ws.close() } if (terminal.term) { terminal.term.dispose() } } setTerminals((prev) => { const filtered = prev.filter((t) => t.id !== id) if (filtered.length > 0 && activeTerminalId === id) { setActiveTerminalId(filtered[0].id) } return filtered }) delete containerRefs.current[id] // Clean up the ref } useEffect(() => { terminals.forEach((terminal) => { const container = containerRefs.current[terminal.id] if (!terminal.term && container) { initializeTerminal(terminal, container) } }) }, [terminals, isMobile]) const initializeTerminal = async (terminal: TerminalInstance, container: HTMLDivElement) => { const [Terminal, FitAddon] = await Promise.all([ import("xterm").then((mod) => mod.Terminal), import("xterm-addon-fit").then((mod) => mod.FitAddon), import("xterm/css/xterm.css"), ]).then(([Terminal, FitAddon]) => [Terminal, FitAddon]) const term = new Terminal({ fontFamily: "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace", fontSize: isMobile ? 11 : 13, cursorBlink: true, scrollback: 2000, disableStdin: false, cols: isMobile ? 40 : layout === "grid" ? 60 : 120, rows: isMobile ? 20 : layout === "grid" ? 15 : 30, theme: { background: "#000000", foreground: "#ffffff", cursor: "#ffffff", cursorAccent: "#000000", black: "#2e3436", red: "#cc0000", green: "#4e9a06", yellow: "#c4a000", blue: "#3465a4", magenta: "#75507b", cyan: "#06989a", white: "#d3d7cf", brightBlack: "#555753", brightRed: "#ef2929", brightGreen: "#8ae234", brightYellow: "#fce94f", brightBlue: "#729fcf", brightMagenta: "#ad7fa8", brightCyan: "#34e2e2", brightWhite: "#eeeeec", }, }) const fitAddon = new FitAddon() term.loadAddon(fitAddon) term.open(container) fitAddon.fit() const wsUrl = websocketUrl || getWebSocketUrl() const ws = new WebSocket(wsUrl) ws.onopen = () => { setTerminals((prev) => prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: true, term, ws } : t))) term.writeln("\x1b[32mConnected to ProxMenux terminal.\x1b[0m") } ws.onmessage = (event) => { term.write(event.data) } ws.onerror = (error) => { console.error("[v0] TerminalPanel: WebSocket error:", error) setTerminals((prev) => prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: false } : t))) term.writeln("\r\n\x1b[31m[ERROR] WebSocket connection error\x1b[0m") } ws.onclose = () => { setTerminals((prev) => prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: false } : t))) term.writeln("\r\n\x1b[33m[INFO] Connection closed\x1b[0m") } term.onData((data) => { if (ws.readyState === WebSocket.OPEN) { ws.send(data) } }) const handleResize = () => { try { fitAddon.fit() } catch { // Ignore resize errors } } window.addEventListener("resize", handleResize) return () => { window.removeEventListener("resize", handleResize) ws.close() term.dispose() } } const handleKeyButton = (key: string) => { const activeTerminal = terminals.find((t) => t.id === activeTerminalId) if (!activeTerminal || !activeTerminal.ws || activeTerminal.ws.readyState !== WebSocket.OPEN) return let seq = "" switch (key) { case "UP": seq = "\x1b[A" break case "DOWN": seq = "\x1b[B" break case "RIGHT": seq = "\x1b[C" break case "LEFT": seq = "\x1b[D" break case "ESC": seq = "\x1b" break case "TAB": seq = "\t" break case "CTRL_C": seq = "\x03" break default: break } activeTerminal.ws.send(seq) if (key) { setLastKeyPressed(key) setTimeout(() => setLastKeyPressed(null), 2000) } } const handleClear = () => { const activeTerminal = terminals.find((t) => t.id === activeTerminalId) if (activeTerminal?.term) { activeTerminal.term.clear() } } const handleClose = () => { terminals.forEach((terminal) => { if (terminal.ws) terminal.ws.close() if (terminal.term) terminal.term.dispose() }) onClose?.() } const sendToActiveTerminal = (command: string) => { const activeTerminal = terminals.find((t) => t.id === activeTerminalId) if (activeTerminal?.ws && activeTerminal.ws.readyState === WebSocket.OPEN) { activeTerminal.ws.send(command + "\n") setSearchModalOpen(false) // Close the search modal after sending a command } } const sendSequence = (seq: string, keyName?: string) => { const activeTerminal = terminals.find((t) => t.id === activeTerminalId) if (activeTerminal?.ws && activeTerminal.ws.readyState === WebSocket.OPEN) { activeTerminal.ws.send(seq) if (keyName) { setLastKeyPressed(keyName) setTimeout(() => setLastKeyPressed(null), 2000) } } } const getLayoutClass = () => { const count = terminals.length if (isMobile || count === 1) return "grid grid-cols-1" if (layout === "vertical" || count === 2) return "grid grid-cols-2" if (layout === "horizontal") return "grid grid-rows-2" if (layout === "grid" || count >= 3) return "grid grid-cols-2 grid-rows-2" return "grid grid-cols-1" } const activeTerminal = terminals.find((t) => t.id === activeTerminalId) return (
{activeTerminal?.isConnected ? "Connected" : "Disconnected"}
{terminals.length} / 4 terminals
{!isMobile && terminals.length > 1 && ( <> {terminals.length >= 3 && ( )} )}
{isMobile ? ( {terminals.map((terminal) => ( {terminal.title} {terminals.length > 1 && ( )} ))} {terminals.map((terminal) => (
))} ) : (
{terminals.map((terminal) => (
{terminals.length > 1 && ( )}
))}
)}
{isMobile && (
{lastKeyPressed && ( Sent: {lastKeyPressed} )}
)} Search Commands {useOnline ? ( <> Online Mode ) : ( <> Offline Mode )} Search for Linux and Proxmox commands
setSearchQuery(e.target.value)} className="pl-10 bg-zinc-900 border-zinc-700 focus:border-blue-500 focus:ring-1 focus:ring-blue-500" />
{isSearching && (

Searching cheat.sh...

)}
{searchResults.length > 0 ? ( searchResults.map((result, index) => (
{result.command} {result.description &&

{result.description}

}
{result.examples.length > 0 && (

Examples:

{result.examples.slice(0, 3).map((example, idx) => (
{ e.stopPropagation() sendToActiveTerminal(example) }} className="flex items-center justify-between p-2 rounded bg-zinc-900/50 hover:bg-zinc-900 group cursor-pointer transition-colors" > {example}
))}
)}
)) ) : filteredCommands.length > 0 && !useOnline ? ( filteredCommands.map((item, index) => (
sendToActiveTerminal(item.cmd)} className="p-3 rounded-lg border border-zinc-700 bg-zinc-800/50 hover:bg-zinc-800 hover:border-blue-500 cursor-pointer transition-colors" >
{item.cmd}

{item.desc}

)) ) : !isSearching && !searchQuery && !useOnline ? ( proxmoxCommands.map((item, index) => (
sendToActiveTerminal(item.cmd)} className="p-3 rounded-lg border border-zinc-700 bg-zinc-800/50 hover:bg-zinc-800 hover:border-blue-500 cursor-pointer transition-colors" >
{item.cmd}

{item.desc}

)) ) : !isSearching ? (
{searchQuery ? ( <>

No results found for "{searchQuery}"

Try a different command or check your spelling

) : ( <>

Search for any command

Try searching for:

{["tar", "grep", "docker ps", "qm list", "systemctl"].map((cmd) => ( setSearchQuery(cmd)} className="px-2 py-1 bg-zinc-800 rounded text-blue-400 cursor-pointer hover:bg-zinc-700" > {cmd} ))}
{useOnline && (
Powered by cheat.sh
)} )}
) : null}
Tip: Search for any Linux command (tar, grep, docker, etc.) or Proxmox commands (qm, pct, pvesh)
{useOnline && searchResults.length > 0 && Powered by cheat.sh}
) }