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

578 lines
19 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 11:19:26 +01:00
import { useState, useEffect, useRef } from "react"
2025-12-01 01:22:04 +01:00
import { Dialog, DialogContent, 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-06 18:36:34 +01:00
import { CheckCircle2, XCircle, Loader2, Activity, GripHorizontal } from "lucide-react"
2025-12-06 21:37:43 +01:00
import { API_PORT } from "@/lib/api-config"
2025-12-06 18:36:34 +01:00
import { useIsMobile } from "@/hooks/use-mobile"
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
}
export function ScriptTerminalModal({
open,
onClose,
scriptPath,
scriptName,
params = {},
title,
description,
}: ScriptTerminalModalProps) {
2025-12-06 21:50:15 +01:00
const sessionIdRef = useRef<string | null>(null)
const hasInitializedRef = useRef(false)
2025-12-01 01:04:31 +01:00
const [isComplete, setIsComplete] = useState(false)
const [exitCode, setExitCode] = useState<number | null>(null)
2025-12-06 11:25:27 +01:00
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
const [interactionInput, setInteractionInput] = useState("")
2025-12-06 13:54:37 +01:00
const wsRef = useRef<WebSocket | null>(null)
2025-12-06 18:36:34 +01:00
const [isConnected, setIsConnected] = useState(false)
const checkConnectionInterval = useRef<NodeJS.Timeout | null>(null)
const isMobile = useIsMobile()
2025-12-06 19:31:07 +01:00
const [isWaitingNextInteraction, setIsWaitingNextInteraction] = useState(false)
const waitingTimeoutRef = useRef<NodeJS.Timeout | null>(null)
2025-12-06 18:36:34 +01:00
const [modalHeight, setModalHeight] = useState(80)
const [isResizing, setIsResizing] = useState(false)
const startYRef = useRef(0)
const startHeightRef = useRef(80)
2025-12-06 13:28:56 +01:00
2025-12-06 21:20:23 +01:00
const terminalRef = useRef<any>(null)
const fitAddonRef = useRef<any>(null)
2025-12-06 22:09:54 +01:00
const terminalContainerRef = useRef<((node: HTMLDivElement | null) => void) | null>(null)
const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => {
setIsResizing(true)
startYRef.current = e.clientY || e.touches[0].clientY
startHeightRef.current = modalHeight
document.addEventListener("mousemove", handleResize)
document.addEventListener("touchmove", handleResize)
document.addEventListener("mouseup", handleResizeEnd)
document.addEventListener("touchend", handleResizeEnd)
}
const handleResize = (e: React.MouseEvent | React.TouchEvent) => {
if (!isResizing) return
const currentY = e.clientY || e.touches[0].clientY
const newHeight = startHeightRef.current + (currentY - startYRef.current)
setModalHeight(Math.max(20, Math.min(80, newHeight)))
}
const handleResizeEnd = () => {
setIsResizing(false)
document.removeEventListener("mousemove", handleResize)
document.removeEventListener("touchmove", handleResize)
document.removeEventListener("mouseup", handleResizeEnd)
document.removeEventListener("touchend", handleResizeEnd)
}
2025-12-06 11:54:36 +01:00
useEffect(() => {
2025-12-06 21:30:17 +01:00
if (!open) {
2025-12-06 21:55:31 +01:00
// Cleanup
2025-12-06 21:50:15 +01:00
if (checkConnectionInterval.current) {
clearInterval(checkConnectionInterval.current)
}
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
}
if (terminalRef.current) {
terminalRef.current.dispose()
terminalRef.current = null
}
if (wsRef.current) {
wsRef.current.close()
wsRef.current = null
}
2025-12-06 21:55:31 +01:00
// Reset for next open
2025-12-06 21:50:15 +01:00
sessionIdRef.current = null
hasInitializedRef.current = false
2025-12-06 21:55:31 +01:00
setIsComplete(false)
setExitCode(null)
setInteractionInput("")
setCurrentInteraction(null)
setIsConnected(false)
setIsWaitingNextInteraction(false)
2025-12-06 21:20:23 +01:00
}
2025-12-06 21:50:15 +01:00
}, [open])
2025-12-06 21:20:23 +01:00
2025-12-06 22:09:54 +01:00
const handleTerminalContainerRef = (node: HTMLDivElement | null) => {
if (!node || !open || hasInitializedRef.current) {
2025-12-06 21:20:23 +01:00
return
}
2025-12-06 22:09:54 +01:00
console.log("[v0] Terminal container mounted, starting initialization")
2025-12-06 21:50:15 +01:00
hasInitializedRef.current = true
2025-12-06 21:55:31 +01:00
// Generate session ID once
if (!sessionIdRef.current) {
sessionIdRef.current = Math.random().toString(36).substring(2, 8)
2025-12-06 22:03:12 +01:00
console.log("[v0] Generated session ID:", sessionIdRef.current)
2025-12-06 21:55:31 +01:00
}
2025-12-06 21:20:23 +01:00
const initTerminal = async () => {
2025-12-06 22:03:12 +01:00
console.log("[v0] Loading xterm modules...")
2025-12-06 21:20:23 +01:00
const [TerminalClass, FitAddonClass] = await Promise.all([
import("xterm").then((mod) => mod.Terminal),
import("xterm-addon-fit").then((mod) => mod.FitAddon),
import("xterm/css/xterm.css"),
])
2025-12-06 22:03:12 +01:00
console.log("[v0] Creating terminal instance...")
2025-12-06 21:20:23 +01:00
const fontSize = window.innerWidth < 768 ? 12 : 16
const term = new TerminalClass({
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",
},
})
const fitAddon = new FitAddonClass()
term.loadAddon(fitAddon)
2025-12-06 22:09:54 +01:00
term.open(node)
2025-12-06 22:03:12 +01:00
console.log("[v0] Terminal opened in container")
2025-12-06 21:30:17 +01:00
setTimeout(() => {
try {
fitAddon.fit()
2025-12-06 22:03:12 +01:00
console.log("[v0] Initial fit completed")
2025-12-06 21:30:17 +01:00
} catch (err) {
2025-12-06 22:03:12 +01:00
console.error("[v0] Initial fit failed:", err)
2025-12-06 21:30:17 +01:00
}
}, 50)
2025-12-06 21:20:23 +01:00
terminalRef.current = term
fitAddonRef.current = fitAddon
2025-12-06 21:50:15 +01:00
const wsUrl = getScriptWebSocketUrl(sessionIdRef.current!)
2025-12-06 22:03:12 +01:00
console.log("[v0] Connecting to WebSocket:", wsUrl)
2025-12-06 21:20:23 +01:00
const ws = new WebSocket(wsUrl)
ws.onopen = () => {
2025-12-06 22:03:12 +01:00
console.log("[v0] WebSocket connected!")
2025-12-06 21:20:23 +01:00
setIsConnected(true)
2025-12-06 21:37:43 +01:00
2025-12-06 21:55:31 +01:00
const initMessage = {
2025-12-06 21:37:43 +01:00
script_path: scriptPath,
params: {
EXECUTION_MODE: "web",
...params,
},
2025-12-06 21:30:17 +01:00
}
2025-12-06 21:37:43 +01:00
2025-12-06 22:03:12 +01:00
console.log("[v0] Sending init message:", initMessage)
2025-12-06 21:55:31 +01:00
ws.send(JSON.stringify(initMessage))
2025-12-06 21:37:43 +01:00
2025-12-06 21:55:31 +01:00
// Fit and resize after connection
2025-12-06 21:37:43 +01:00
setTimeout(() => {
try {
2025-12-06 21:50:15 +01:00
fitAddon.fit()
2025-12-06 22:03:12 +01:00
const cols = term.cols
const rows = term.rows
console.log("[v0] Sending resize:", { cols, rows })
2025-12-06 21:37:43 +01:00
ws.send(
JSON.stringify({
type: "resize",
2025-12-06 22:03:12 +01:00
cols: cols,
rows: rows,
2025-12-06 21:37:43 +01:00
}),
)
} catch (err) {
2025-12-06 22:03:12 +01:00
console.error("[v0] Resize after connect failed:", err)
2025-12-06 21:37:43 +01:00
}
}, 100)
2025-12-06 21:20:23 +01:00
}
ws.onmessage = (event) => {
2025-12-06 22:03:12 +01:00
console.log("[v0] Received message:", event.data)
2025-12-06 21:20:23 +01:00
try {
const msg = JSON.parse(event.data)
2025-12-06 21:55:31 +01:00
// Detect web interactions
if (msg.type === "web_interaction" && msg.interaction) {
2025-12-06 22:03:12 +01:00
console.log("[v0] Web interaction detected:", msg.interaction)
2025-12-06 21:20:23 +01:00
setIsWaitingNextInteraction(false)
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
}
setCurrentInteraction({
2025-12-06 21:37:43 +01:00
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-06 21:20:23 +01:00
})
2025-12-06 21:55:31 +01:00
return // Don't write JSON to terminal
}
if (msg.type === "error") {
2025-12-06 22:03:12 +01:00
console.error("[v0] Error message:", msg.message)
2025-12-06 21:37:43 +01:00
term.writeln(`\x1b[31m${msg.message}\x1b[0m`)
2025-12-06 21:55:31 +01:00
return
2025-12-06 21:20:23 +01:00
}
} catch {
2025-12-06 21:55:31 +01:00
// Not JSON, it's regular terminal output
2025-12-06 22:03:12 +01:00
console.log("[v0] Regular terminal output received")
2025-12-06 21:55:31 +01:00
}
// Write regular output to terminal
term.write(event.data)
// Hide spinner when output arrives
setIsWaitingNextInteraction(false)
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
2025-12-06 21:20:23 +01:00
}
}
2025-12-06 21:37:43 +01:00
ws.onerror = (error) => {
2025-12-06 22:03:12 +01:00
console.error("[v0] WebSocket error:", error)
2025-12-06 21:20:23 +01:00
setIsConnected(false)
term.writeln("\x1b[31mWebSocket error occurred\x1b[0m")
}
2025-12-06 21:37:43 +01:00
ws.onclose = (event) => {
2025-12-06 22:03:12 +01:00
console.log("[v0] WebSocket closed:", event.code, event.reason)
2025-12-06 21:20:23 +01:00
setIsConnected(false)
term.writeln("\x1b[33mConnection closed\x1b[0m")
2025-12-06 21:37:43 +01:00
if (!isComplete) {
setIsComplete(true)
setExitCode(event.code === 1000 ? 0 : 1)
}
2025-12-06 21:20:23 +01:00
}
term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) {
2025-12-06 22:03:12 +01:00
console.log("[v0] Sending user input to WebSocket")
2025-12-06 21:20:23 +01:00
ws.send(data)
}
})
wsRef.current = ws
2025-12-06 21:30:17 +01:00
2025-12-06 21:55:31 +01:00
// Monitor connection status
2025-12-06 21:30:17 +01:00
checkConnectionInterval.current = setInterval(() => {
if (ws) {
setIsConnected(ws.readyState === WebSocket.OPEN)
}
}, 500)
2025-12-06 21:20:23 +01:00
2025-12-06 22:09:54 +01:00
// Setup ResizeObserver for the terminal container
let resizeTimeout: NodeJS.Timeout | null = null
2025-12-06 21:30:17 +01:00
2025-12-06 22:09:54 +01:00
const resizeObserver = new ResizeObserver(() => {
if (resizeTimeout) {
clearTimeout(resizeTimeout)
2025-12-06 21:30:17 +01:00
}
2025-12-06 21:20:23 +01:00
2025-12-06 22:09:54 +01:00
resizeTimeout = setTimeout(() => {
if (fitAddon && term && ws?.readyState === WebSocket.OPEN) {
try {
fitAddon.fit()
const cols = term.cols
const rows = term.rows
console.log("[v0] Terminal resized to:", cols, "x", rows)
ws.send(
JSON.stringify({
type: "resize",
cols: cols,
rows: rows,
}),
)
} catch (err) {
console.warn("[v0] Resize failed:", err)
}
}
}, 100)
})
2025-12-06 21:20:23 +01:00
2025-12-06 22:09:54 +01:00
resizeObserver.observe(node)
2025-12-06 11:54:36 +01:00
}
2025-12-06 18:36:34 +01:00
2025-12-06 22:09:54 +01:00
initTerminal()
2025-12-06 21:30:17 +01:00
}
2025-12-06 18:36:34 +01:00
2025-12-06 21:30:17 +01:00
const getScriptWebSocketUrl = (sid: string): string => {
2025-12-01 01:15:19 +01:00
if (typeof window === "undefined") {
2025-12-06 21:30:17 +01:00
return `ws://localhost:${API_PORT}/ws/script/${sid}`
2025-12-01 01:15:19 +01:00
}
2025-12-01 01:40:04 +01:00
const { hostname, protocol } = window.location
const wsProtocol = protocol === "https:" ? "wss:" : "ws:"
2025-12-06 21:30:17 +01:00
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 13:54:37 +01:00
if (!wsRef.current || !currentInteraction) {
2025-12-06 13:28:56 +01:00
return
}
2025-12-06 11:25:27 +01:00
2025-12-06 19:03:19 +01:00
if (value === "cancel" || value === "") {
setCurrentInteraction(null)
setInteractionInput("")
handleCloseModal()
return
}
2025-12-06 11:25:27 +01:00
const response = JSON.stringify({
type: "interaction_response",
id: currentInteraction.id,
value: value,
})
2025-12-06 13:54:37 +01:00
if (wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(response)
}
2025-12-06 12:46:41 +01:00
2025-12-06 11:25:27 +01:00
setCurrentInteraction(null)
setInteractionInput("")
2025-12-06 19:31:07 +01:00
waitingTimeoutRef.current = setTimeout(() => {
setIsWaitingNextInteraction(true)
}, 300)
2025-12-06 11:25:27 +01:00
}
2025-12-06 18:36:34 +01:00
const handleCloseModal = () => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.close()
}
if (checkConnectionInterval.current) {
clearInterval(checkConnectionInterval.current)
}
2025-12-06 21:20:23 +01:00
if (terminalRef.current) {
terminalRef.current.dispose()
terminalRef.current = null
}
2025-12-06 18:36:34 +01:00
onClose()
}
2025-12-01 01:04:31 +01:00
return (
<>
2025-12-06 18:36:34 +01:00
<Dialog open={open}>
<DialogContent
className="max-w-4xl p-0 flex flex-col"
style={{ height: isMobile ? "80vh" : `${modalHeight}vh` }}
onInteractOutside={(e) => e.preventDefault()}
onEscapeKeyDown={(e) => e.preventDefault()}
>
2025-12-01 01:22:04 +01:00
<DialogTitle className="sr-only">{title}</DialogTitle>
2025-12-06 18:36:34 +01:00
<div className="flex items-center gap-2 p-4 border-b">
2025-12-06 20:46:13 +01:00
{isComplete &&
(exitCode === 0 ? (
2025-12-06 18:36:34 +01:00
<CheckCircle2 className="h-5 w-5 text-green-500" />
2025-12-01 01:15:19 +01:00
) : (
2025-12-06 18:36:34 +01:00
<XCircle className="h-5 w-5 text-red-500" />
2025-12-06 20:46:13 +01:00
))}
2025-12-06 18:36:34 +01:00
<div>
<h2 className="text-lg font-semibold">{title}</h2>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
2025-12-01 01:15:19 +01:00
</div>
2025-12-01 01:04:31 +01:00
</div>
2025-12-06 21:30:17 +01:00
<div className="overflow-hidden relative" style={{ height: "calc(100% - 120px)" }}>
2025-12-06 21:20:23 +01:00
<div ref={terminalContainerRef} className="w-full h-full" />
2025-12-06 19:31:07 +01:00
{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 19:03:19 +01:00
className={`h-2 cursor-ns-resize flex items-center justify-center transition-colors ${
isResizing ? "bg-blue-500" : "bg-zinc-800 hover:bg-blue-500/50"
}`}
2025-12-06 18:36:34 +01:00
onMouseDown={handleResizeStart}
onTouchStart={handleResizeStart}
>
2025-12-06 19:03:19 +01:00
<GripHorizontal className={`h-4 w-4 ${isResizing ? "text-white" : "text-zinc-500"}`} />
2025-12-06 18:36:34 +01:00
</div>
)}
2025-12-01 01:15:19 +01:00
<div className="flex items-center justify-between p-4 border-t">
2025-12-06 18:36:34 +01:00
<div className="flex items-center gap-3">
<Activity className="h-5 w-5 text-blue-500" />
<div
className={`w-2 h-2 rounded-full ${isConnected ? "bg-green-500" : "bg-red-500"}`}
title={isConnected ? "Connected" : "Disconnected"}
></div>
<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>
2025-12-01 01:04:31 +01:00
</div>
</DialogContent>
</Dialog>
2025-12-06 11:25:27 +01:00
{currentInteraction && (
2025-12-06 13:54:37 +01:00
<Dialog open={true}>
2025-12-06 13:11:04 +01:00
<DialogContent
className="max-w-4xl max-h-[80vh] overflow-y-auto"
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-06 12:25:57 +01:00
<p className="whitespace-pre-wrap">{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")}
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
>
2025-12-06 11:25:27 +01:00
Yes
</Button>
2025-12-06 19:03:19 +01:00
<Button
onClick={() => handleInteractionResponse("cancel")}
variant="outline"
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600"
>
Cancel
</Button>
2025-12-06 11:25:27 +01:00
</div>
)}
{currentInteraction.type === "menu" && currentInteraction.options && (
<div className="space-y-2">
{currentInteraction.options.map((option) => (
<Button
key={option.value}
onClick={() => handleInteractionResponse(option.value)}
variant="outline"
2025-12-06 18:36:34 +01:00
className="w-full justify-start hover:bg-blue-600 hover:text-white"
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"
className="w-full hover:bg-red-600 hover:text-white hover:border-red-600"
>
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
value={interactionInput}
onChange={(e) => setInteractionInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleInteractionResponse(interactionInput)
}
}}
placeholder={currentInteraction.default || ""}
/>
2025-12-06 18:36:34 +01:00
<div className="flex gap-2">
<Button
onClick={() => handleInteractionResponse(interactionInput)}
className="flex-1 bg-blue-600 hover:bg-blue-700"
>
Submit
</Button>
<Button
2025-12-06 19:03:19 +01:00
onClick={() => handleInteractionResponse("cancel")}
2025-12-06 18:36:34 +01:00
variant="outline"
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600"
>
Cancel
</Button>
</div>
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")}
className="flex-1 bg-blue-600 hover:bg-blue-700"
>
OK
</Button>
<Button
onClick={() => handleInteractionResponse("cancel")}
variant="outline"
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600"
>
Cancel
</Button>
</div>
2025-12-06 11:25:27 +01:00
)}
</div>
</DialogContent>
</Dialog>
)}
2025-12-01 01:04:31 +01:00
</>
)
}