Files
ProxMenux/AppImage/components/script-terminal-modal.tsx

594 lines
20 KiB
TypeScript
Raw Normal View History

2025-12-01 01:04:31 +01:00
"use client"
2025-12-06 18:36:34 +01:00
import type React from "react"
2025-12-06 23:06:18 +01:00
import { useState, useEffect, useRef, useCallback } from "react"
2025-12-10 16:56:56 +01:00
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
2025-12-01 01:04:31 +01:00
import { Button } from "@/components/ui/button"
2025-12-06 11:25:27 +01:00
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
2025-12-10 16:56:56 +01:00
import { Loader2, GripHorizontal, X } from "lucide-react"
import { API_PORT } from "@/lib/api-config"
2025-12-06 18:36:34 +01:00
import { useIsMobile } from "@/hooks/use-mobile"
2025-12-10 17:01:17 +01:00
import { Terminal as XTerm, FitAddon } from "xterm"
import "xterm/css/xterm.css"
2025-12-01 01:04:31 +01:00
2025-12-06 11:25:27 +01:00
interface WebInteraction {
2025-12-06 12:25:57 +01:00
type: "yesno" | "menu" | "msgbox" | "input" | "inputbox"
2025-12-06 11:25:27 +01:00
id: string
title: string
message: string
options?: Array<{ label: string; value: string }>
2025-12-06 12:25:57 +01:00
default?: string
2025-12-06 11:25:27 +01:00
}
2025-12-01 01:04:31 +01:00
interface ScriptTerminalModalProps {
open: boolean
onClose: () => void
scriptPath: string
scriptName: string
params?: Record<string, string>
title: string
description: string
}
2025-12-10 16:50:52 +01:00
const processMessageText = (text: string): string => {
return text
.replace(/\\r\\n/g, "\n") // Windows line endings
.replace(/\\n/g, "\n") // Unix line endings
.replace(/\n\n+/g, "\n\n") // Multiple newlines to double newline
}
export default function ScriptTerminalModal({
2025-12-01 01:04:31 +01:00
open,
onClose,
scriptPath,
scriptName,
params = {},
title,
description,
}: ScriptTerminalModalProps) {
2025-12-10 17:01:17 +01:00
const termRef = useRef<XTerm | null>(null)
const fitAddonRef = useRef<FitAddon | null>(null)
2025-12-06 23:06:18 +01:00
const wsRef = useRef<WebSocket | null>(null)
const sessionIdRef = useRef<string>(Math.random().toString(36).substring(2, 8))
2025-12-01 01:04:31 +01:00
const [exitCode, setExitCode] = useState<number | null>(null)
2025-12-10 16:50:52 +01:00
const [isComplete, setIsComplete] = useState(false)
const [isConnected, setIsConnected] = useState(false)
2025-12-06 11:25:27 +01:00
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
2025-12-06 23:06:18 +01:00
const [isWaitingNextInteraction, setIsWaitingNextInteraction] = useState(false)
2025-12-10 16:50:52 +01:00
const [showingInteraction, setShowingInteraction] = useState(false)
2025-12-06 23:06:18 +01:00
2025-12-10 16:50:52 +01:00
const [modalHeight, setModalHeight] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("scriptModalHeight")
return saved ? Number.parseInt(saved) : 600
}
return 600
})
2025-12-06 18:36:34 +01:00
const [isResizing, setIsResizing] = useState(false)
2025-12-06 23:25:35 +01:00
const resizeHandlersRef = useRef<{
handleMove: ((e: MouseEvent | TouchEvent) => void) | null
handleEnd: (() => void) | null
}>({ handleMove: null, handleEnd: null })
2025-12-06 13:28:56 +01:00
2025-12-10 16:50:52 +01:00
const isMobile = useIsMobile()
2025-12-06 23:06:18 +01:00
const terminalContainerRef = useCallback(
(node: HTMLDivElement | null) => {
if (!node || !open || termRef.current) {
return
}
console.log("[v0] Terminal container mounted, initializing...")
const initializeTerminal = async () => {
console.log("[v0] Creating terminal instance...")
const fontSize = window.innerWidth < 768 ? 12 : 16
2025-12-10 17:01:17 +01:00
const term = new XTerm({
2025-12-06 23:06:18 +01:00
rendererType: "dom",
fontFamily: '"Courier", "Courier New", "Liberation Mono", "DejaVu Sans Mono", monospace',
fontSize: fontSize,
lineHeight: 1,
cursorBlink: true,
scrollback: 2000,
disableStdin: false,
customGlyphs: true,
fontWeight: "500",
fontWeightBold: "700",
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",
},
})
2025-12-10 16:50:52 +01:00
const fitAddon = new FitAddon()
2025-12-06 23:06:18 +01:00
term.loadAddon(fitAddon)
console.log("[v0] Opening terminal in container...")
term.open(node)
termRef.current = term
fitAddonRef.current = fitAddon
setTimeout(() => {
try {
fitAddon.fit()
console.log("[v0] Terminal fitted, cols:", term.cols, "rows:", term.rows)
} catch (err) {
console.log("[v0] Fit error:", err)
}
}, 50)
const wsUrl = getScriptWebSocketUrl(sessionIdRef.current)
console.log("[v0] Connecting to WebSocket:", wsUrl)
const ws = new WebSocket(wsUrl)
wsRef.current = ws
ws.onopen = () => {
console.log("[v0] WebSocket connected!")
setIsConnected(true)
const initMessage = {
script_path: scriptPath,
params: {
EXECUTION_MODE: "web",
...params,
},
}
console.log("[v0] Sending init message:", initMessage)
ws.send(JSON.stringify(initMessage))
setTimeout(() => {
try {
fitAddon.fit()
const cols = term.cols
const rows = term.rows
console.log("[v0] Sending resize:", { cols, rows })
ws.send(
JSON.stringify({
type: "resize",
cols: cols,
rows: rows,
}),
)
} catch (err) {
console.log("[v0] Resize error:", err)
}
}, 100)
}
ws.onmessage = (event) => {
console.log("[v0] WebSocket message received:", event.data.substring(0, 100))
try {
const msg = JSON.parse(event.data)
if (msg.type === "web_interaction" && msg.interaction) {
console.log("[v0] Web interaction detected:", msg.interaction.type)
setIsWaitingNextInteraction(false)
2025-12-10 16:50:52 +01:00
if (resizeHandlersRef.current.handleMove) {
clearTimeout(resizeHandlersRef.current.handleMove)
2025-12-06 23:06:18 +01:00
}
setCurrentInteraction({
type: msg.interaction.type,
id: msg.interaction.id,
title: msg.interaction.title || "",
message: msg.interaction.message || "",
options: msg.interaction.options,
default: msg.interaction.default,
})
2025-12-10 16:50:52 +01:00
setShowingInteraction(true)
2025-12-06 23:06:18 +01:00
return
}
if (msg.type === "error") {
console.log("[v0] Error message:", msg.message)
term.writeln(`\x1b[31m${msg.message}\x1b[0m`)
return
}
} catch {
// Not JSON, es output normal de terminal
}
term.write(event.data)
setIsWaitingNextInteraction(false)
2025-12-10 16:50:52 +01:00
if (resizeHandlersRef.current.handleMove) {
clearTimeout(resizeHandlersRef.current.handleMove)
2025-12-06 23:06:18 +01:00
}
}
ws.onerror = (error) => {
console.log("[v0] WebSocket error:", error)
setIsConnected(false)
term.writeln("\x1b[31mWebSocket error occurred\x1b[0m")
}
ws.onclose = (event) => {
console.log("[v0] WebSocket closed:", event.code, event.reason)
setIsConnected(false)
term.writeln("\x1b[33mConnection closed\x1b[0m")
2025-12-10 16:50:52 +01:00
if (!isComplete && event.code !== 1006) {
2025-12-06 23:06:18 +01:00
setIsComplete(true)
setExitCode(event.code === 1000 ? 0 : 1)
}
}
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(data)
}
})
2025-12-10 16:50:52 +01:00
const checkConnectionInterval = setInterval(() => {
2025-12-06 23:06:18 +01:00
if (ws) {
setIsConnected(ws.readyState === WebSocket.OPEN)
}
}, 500)
let resizeTimeout: NodeJS.Timeout | null = null
const resizeObserver = new ResizeObserver(() => {
if (resizeTimeout) clearTimeout(resizeTimeout)
resizeTimeout = setTimeout(() => {
if (fitAddon && term && ws?.readyState === WebSocket.OPEN) {
try {
fitAddon.fit()
ws.send(
JSON.stringify({
type: "resize",
cols: term.cols,
rows: term.rows,
}),
)
} catch (err) {
// Ignore
}
}
}, 100)
})
resizeObserver.observe(node)
2025-12-10 16:50:52 +01:00
return () => {
clearInterval(checkConnectionInterval)
resizeObserver.disconnect()
}
2025-12-06 23:06:18 +01:00
}
initializeTerminal()
2025-12-06 22:40:24 +01:00
},
2025-12-06 23:06:18 +01:00
[open, scriptPath, params],
)
useEffect(() => {
if (!open) {
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
if (termRef.current) {
termRef.current.dispose()
termRef.current = null
}
2025-12-06 23:25:35 +01:00
if (resizeHandlersRef.current.handleMove) {
document.removeEventListener("mousemove", resizeHandlersRef.current.handleMove as any)
document.removeEventListener("touchmove", resizeHandlersRef.current.handleMove as any)
}
if (resizeHandlersRef.current.handleEnd) {
document.removeEventListener("mouseup", resizeHandlersRef.current.handleEnd)
document.removeEventListener("touchend", resizeHandlersRef.current.handleEnd)
}
resizeHandlersRef.current = { handleMove: null, handleEnd: null }
2025-12-10 16:50:52 +01:00
setModalHeight(() => {
if (typeof window !== "undefined") {
return Number.parseInt(localStorage.getItem("scriptModalHeight") || "600")
}
return 600
})
2025-12-06 23:06:18 +01:00
setIsComplete(false)
setExitCode(null)
2025-12-10 16:50:52 +01:00
setShowingInteraction(false)
2025-12-06 23:06:18 +01:00
setCurrentInteraction(null)
setIsWaitingNextInteraction(false)
setIsConnected(false)
}
}, [open])
const getScriptWebSocketUrl = (sid: string): string => {
if (typeof window === "undefined") {
return `ws://localhost:${API_PORT}/ws/script/${sid}`
}
const { hostname, protocol } = window.location
const wsProtocol = protocol === "https:" ? "wss:" : "ws:"
return `${wsProtocol}//${hostname}:${API_PORT}/ws/script/${sid}`
2025-12-01 01:15:19 +01:00
}
2025-12-06 11:25:27 +01:00
const handleInteractionResponse = (value: string) => {
2025-12-06 23:06:18 +01:00
if (!wsRef.current || !currentInteraction) {
return
}
2025-12-06 19:03:19 +01:00
if (value === "cancel" || value === "") {
setCurrentInteraction(null)
2025-12-10 16:50:52 +01:00
setShowingInteraction(false)
2025-12-06 23:06:18 +01:00
handleCloseModal()
2025-12-06 19:03:19 +01:00
return
}
2025-12-06 23:06:18 +01:00
const response = JSON.stringify({
type: "interaction_response",
id: currentInteraction.id,
value: value,
})
if (wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(response)
}
2025-12-06 11:25:27 +01:00
setCurrentInteraction(null)
2025-12-10 16:50:52 +01:00
setShowingInteraction(false)
2025-12-06 23:06:18 +01:00
2025-12-10 16:50:52 +01:00
setIsWaitingNextInteraction(true)
2025-12-06 23:06:18 +01:00
}
const handleCloseModal = () => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.close()
}
if (termRef.current) {
termRef.current.dispose()
}
onClose()
2025-12-06 18:36:34 +01:00
}
2025-12-06 22:20:34 +01:00
const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => {
2025-12-06 23:25:35 +01:00
e.preventDefault()
e.stopPropagation()
2025-12-06 22:20:34 +01:00
setIsResizing(true)
2025-12-06 23:25:35 +01:00
const startY = "clientY" in e ? e.clientY : e.touches[0].clientY
const startHeight = modalHeight
2025-12-06 22:20:34 +01:00
2025-12-06 23:25:35 +01:00
const handleMove = (moveEvent: MouseEvent | TouchEvent) => {
const currentY = moveEvent instanceof MouseEvent ? moveEvent.clientY : moveEvent.touches[0].clientY
const deltaY = currentY - startY
2025-12-10 16:50:52 +01:00
const newHeight = Math.max(300, Math.min(2400, startHeight + deltaY))
2025-12-06 23:25:35 +01:00
setModalHeight(newHeight)
if (fitAddonRef.current && termRef.current && wsRef.current?.readyState === WebSocket.OPEN) {
try {
setTimeout(() => {
fitAddonRef.current.fit()
wsRef.current?.send(
JSON.stringify({
type: "resize",
cols: termRef.current.cols,
rows: termRef.current.rows,
}),
)
}, 10)
} catch (err) {
// Ignore
}
}
}
const handleEnd = () => {
setIsResizing(false)
if (fitAddonRef.current && termRef.current && wsRef.current?.readyState === WebSocket.OPEN) {
try {
setTimeout(() => {
fitAddonRef.current.fit()
wsRef.current?.send(
JSON.stringify({
type: "resize",
cols: termRef.current.cols,
rows: termRef.current.rows,
}),
)
}, 50)
} catch (err) {
// Ignore
}
}
2025-12-10 16:50:52 +01:00
localStorage.setItem("scriptModalHeight", modalHeight.toString())
2025-12-06 23:25:35 +01:00
document.removeEventListener("mousemove", handleMove as any)
document.removeEventListener("touchmove", handleMove as any)
document.removeEventListener("mouseup", handleEnd)
document.removeEventListener("touchend", handleEnd)
resizeHandlersRef.current = { handleMove: null, handleEnd: null }
}
resizeHandlersRef.current = { handleMove, handleEnd }
2025-12-06 22:20:34 +01:00
2025-12-06 23:25:35 +01:00
document.addEventListener("mousemove", handleMove as any)
document.addEventListener("touchmove", handleMove as any, { passive: false })
document.addEventListener("mouseup", handleEnd)
document.addEventListener("touchend", handleEnd)
2025-12-06 22:20:34 +01:00
}
2025-12-01 01:04:31 +01:00
return (
<>
2025-12-06 18:36:34 +01:00
<Dialog open={open}>
<DialogContent
2025-12-10 16:50:52 +01:00
className="max-w-7xl flex flex-col overflow-hidden p-0"
style={{
height: isMobile ? "80vh" : `${Math.min(modalHeight, window.innerHeight * 0.9)}px`,
maxHeight: isMobile ? "80vh" : "2400px",
}}
2025-12-06 18:36:34 +01:00
onInteractOutside={(e) => e.preventDefault()}
onEscapeKeyDown={(e) => e.preventDefault()}
>
2025-12-10 16:56:56 +01:00
<DialogHeader className="flex items-center justify-between border-b px-6 py-4">
<DialogTitle className="text-xl font-semibold">{scriptName}</DialogTitle>
2025-12-10 16:50:52 +01:00
<Button variant="ghost" size="icon" onClick={onClose}>
2025-12-10 16:56:56 +01:00
<X className="h-4 w-4" />
2025-12-10 16:50:52 +01:00
</Button>
2025-12-10 16:56:56 +01:00
</DialogHeader>
2025-12-01 01:04:31 +01:00
2025-12-06 23:06:18 +01:00
<div className="overflow-hidden relative flex-1">
<div ref={terminalContainerRef} className="w-full h-full" />
{isWaitingNextInteraction && !currentInteraction && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm">
<div className="flex flex-col items-center gap-3">
<Loader2 className="h-8 w-8 animate-spin text-blue-500" />
<p className="text-sm text-muted-foreground">Processing...</p>
</div>
</div>
)}
2025-12-01 01:15:19 +01:00
</div>
2025-12-01 01:04:31 +01:00
2025-12-06 18:36:34 +01:00
{!isMobile && (
<div
2025-12-06 23:25:35 +01:00
className={`h-2 cursor-ns-resize flex items-center justify-center transition-all duration-150 ${
isResizing ? "bg-blue-500 h-3" : "bg-zinc-800 hover:bg-blue-500/50"
2025-12-06 19:03:19 +01:00
}`}
2025-12-06 18:36:34 +01:00
onMouseDown={handleResizeStart}
onTouchStart={handleResizeStart}
>
2025-12-06 23:25:35 +01:00
<GripHorizontal
className={`h-4 w-4 transition-all duration-150 ${isResizing ? "text-white scale-110" : "text-zinc-500"}`}
/>
2025-12-06 18:36:34 +01:00
</div>
)}
2025-12-06 23:06:18 +01:00
<div className="flex items-center justify-between p-4 border-t">
<div className="flex items-center gap-3">
<span className="text-xs text-muted-foreground">{isConnected ? "Online" : "Offline"}</span>
</div>
<Button
onClick={handleCloseModal}
variant="outline"
className="bg-red-600 hover:bg-red-700 border-red-500 text-white"
>
Close
</Button>
</div>
2025-12-01 01:04:31 +01:00
</DialogContent>
</Dialog>
2025-12-06 11:25:27 +01:00
2025-12-10 16:50:52 +01:00
{showingInteraction && currentInteraction && (
2025-12-06 13:54:37 +01:00
<Dialog open={true}>
2025-12-06 13:11:04 +01:00
<DialogContent
2025-12-06 23:25:35 +01:00
className="max-w-4xl max-h-[80vh] overflow-y-auto animate-in fade-in-0 zoom-in-95 duration-100"
2025-12-06 13:54:37 +01:00
onInteractOutside={(e) => e.preventDefault()}
onEscapeKeyDown={(e) => e.preventDefault()}
2025-12-06 19:03:19 +01:00
hideClose
2025-12-06 13:11:04 +01:00
>
2025-12-06 11:25:27 +01:00
<DialogTitle>{currentInteraction.title}</DialogTitle>
<div className="space-y-4">
2025-12-10 16:50:52 +01:00
<p className="whitespace-pre-wrap">{processMessageText(currentInteraction.message)}</p>
2025-12-06 11:25:27 +01:00
{currentInteraction.type === "yesno" && (
<div className="flex gap-2">
2025-12-06 13:00:29 +01:00
<Button
onClick={() => handleInteractionResponse("yes")}
2025-12-06 23:25:35 +01:00
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white transition-all duration-150"
2025-12-06 13:00:29 +01:00
>
2025-12-06 11:25:27 +01:00
Yes
</Button>
2025-12-06 19:03:19 +01:00
<Button
onClick={() => handleInteractionResponse("cancel")}
variant="outline"
2025-12-06 23:25:35 +01:00
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600 transition-all duration-150"
2025-12-06 19:03:19 +01:00
>
Cancel
</Button>
2025-12-06 11:25:27 +01:00
</div>
)}
{currentInteraction.type === "menu" && currentInteraction.options && (
<div className="space-y-2">
2025-12-06 23:25:35 +01:00
{currentInteraction.options.map((option, index) => (
2025-12-06 11:25:27 +01:00
<Button
key={option.value}
onClick={() => handleInteractionResponse(option.value)}
variant="outline"
2025-12-06 23:25:35 +01:00
className="w-full justify-start hover:bg-blue-600 hover:text-white transition-all duration-100 animate-in fade-in-0 slide-in-from-left-2"
style={{ animationDelay: `${index * 30}ms` }}
2025-12-06 11:25:27 +01:00
>
{option.label}
</Button>
))}
2025-12-06 18:36:34 +01:00
<Button
onClick={() => handleInteractionResponse("cancel")}
variant="outline"
2025-12-06 23:25:35 +01:00
className="w-full hover:bg-red-600 hover:text-white hover:border-red-600 transition-all duration-150"
2025-12-06 18:36:34 +01:00
>
2025-12-06 19:03:19 +01:00
Cancel
2025-12-06 18:36:34 +01:00
</Button>
2025-12-06 11:25:27 +01:00
</div>
)}
2025-12-06 13:54:37 +01:00
{(currentInteraction.type === "input" || currentInteraction.type === "inputbox") && (
<div className="space-y-2">
<Label>Your input:</Label>
<Input
2025-12-10 16:50:52 +01:00
value={currentInteraction.default || ""}
onChange={(e) => handleInteractionResponse(e.target.value)}
2025-12-06 13:54:37 +01:00
onKeyDown={(e) => {
if (e.key === "Enter") {
2025-12-10 16:50:52 +01:00
handleInteractionResponse(currentInteraction.default || "")
2025-12-06 13:54:37 +01:00
}
}}
placeholder={currentInteraction.default || ""}
2025-12-06 23:25:35 +01:00
className="transition-all duration-150"
2025-12-06 13:54:37 +01:00
/>
</div>
)}
2025-12-06 11:25:27 +01:00
{currentInteraction.type === "msgbox" && (
2025-12-06 19:03:19 +01:00
<div className="flex gap-2">
<Button
onClick={() => handleInteractionResponse("ok")}
2025-12-06 23:25:35 +01:00
className="flex-1 bg-blue-600 hover:bg-blue-700 transition-all duration-150"
2025-12-06 19:03:19 +01:00
>
OK
</Button>
<Button
onClick={() => handleInteractionResponse("cancel")}
variant="outline"
2025-12-06 23:25:35 +01:00
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600 transition-all duration-150"
2025-12-06 19:03:19 +01:00
>
Cancel
</Button>
</div>
2025-12-06 11:25:27 +01:00
)}
</div>
</DialogContent>
</Dialog>
)}
2025-12-01 01:04:31 +01:00
</>
)
}