mirror of
https://github.com/MacRimi/ProxMenux.git
synced 2025-12-14 16:16:21 +00:00
Update AppImage
This commit is contained in:
@@ -1,13 +1,16 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import type React from "react"
|
||||||
|
|
||||||
import { useState, useEffect, useRef } from "react"
|
import { useState, useEffect, useRef } from "react"
|
||||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
|
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button"
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input"
|
||||||
import { Label } from "@/components/ui/label"
|
import { Label } from "@/components/ui/label"
|
||||||
import { X, CheckCircle2, XCircle, Loader2 } from "lucide-react"
|
import { CheckCircle2, XCircle, Loader2, Activity, GripHorizontal } from "lucide-react"
|
||||||
import { TerminalPanel } from "./terminal-panel"
|
import { TerminalPanel } from "./terminal-panel"
|
||||||
import { API_PORT } from "@/lib/api-config"
|
import { API_PORT } from "@/lib/api-config"
|
||||||
|
import { useIsMobile } from "@/hooks/use-mobile"
|
||||||
|
|
||||||
interface WebInteraction {
|
interface WebInteraction {
|
||||||
type: "yesno" | "menu" | "msgbox" | "input" | "inputbox"
|
type: "yesno" | "menu" | "msgbox" | "input" | "inputbox"
|
||||||
@@ -43,6 +46,14 @@ export function ScriptTerminalModal({
|
|||||||
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
|
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
|
||||||
const [interactionInput, setInteractionInput] = useState("")
|
const [interactionInput, setInteractionInput] = useState("")
|
||||||
const wsRef = useRef<WebSocket | null>(null)
|
const wsRef = useRef<WebSocket | null>(null)
|
||||||
|
const [isConnected, setIsConnected] = useState(false)
|
||||||
|
const checkConnectionInterval = useRef<NodeJS.Timeout | null>(null)
|
||||||
|
const isMobile = useIsMobile()
|
||||||
|
|
||||||
|
const [modalHeight, setModalHeight] = useState(80)
|
||||||
|
const [isResizing, setIsResizing] = useState(false)
|
||||||
|
const startYRef = useRef(0)
|
||||||
|
const startHeightRef = useRef(80)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
@@ -50,9 +61,62 @@ export function ScriptTerminalModal({
|
|||||||
setExitCode(null)
|
setExitCode(null)
|
||||||
setInteractionInput("")
|
setInteractionInput("")
|
||||||
setCurrentInteraction(null)
|
setCurrentInteraction(null)
|
||||||
|
setIsConnected(false)
|
||||||
|
|
||||||
|
checkConnectionInterval.current = setInterval(() => {
|
||||||
|
if (wsRef.current) {
|
||||||
|
setIsConnected(wsRef.current.readyState === WebSocket.OPEN)
|
||||||
|
}
|
||||||
|
}, 500)
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (checkConnectionInterval.current) {
|
||||||
|
clearInterval(checkConnectionInterval.current)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [open])
|
}, [open])
|
||||||
|
|
||||||
|
const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => {
|
||||||
|
if (isMobile) return
|
||||||
|
|
||||||
|
setIsResizing(true)
|
||||||
|
startYRef.current = "touches" in e ? e.touches[0].clientY : e.clientY
|
||||||
|
startHeightRef.current = modalHeight
|
||||||
|
|
||||||
|
e.preventDefault()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isResizing) return
|
||||||
|
|
||||||
|
const handleResizeMove = (e: MouseEvent | TouchEvent) => {
|
||||||
|
const currentY = "touches" in e ? e.touches[0].clientY : e.clientY
|
||||||
|
const deltaY = startYRef.current - currentY
|
||||||
|
const viewportHeight = window.innerHeight
|
||||||
|
const deltaVh = (deltaY / viewportHeight) * 100
|
||||||
|
|
||||||
|
const newHeight = Math.min(Math.max(startHeightRef.current + deltaVh, 50), 95)
|
||||||
|
setModalHeight(newHeight)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleResizeEnd = () => {
|
||||||
|
setIsResizing(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("mousemove", handleResizeMove)
|
||||||
|
document.addEventListener("mouseup", handleResizeEnd)
|
||||||
|
document.addEventListener("touchmove", handleResizeMove)
|
||||||
|
document.addEventListener("touchend", handleResizeEnd)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("mousemove", handleResizeMove)
|
||||||
|
document.removeEventListener("mouseup", handleResizeEnd)
|
||||||
|
document.removeEventListener("touchmove", handleResizeMove)
|
||||||
|
document.removeEventListener("touchend", handleResizeEnd)
|
||||||
|
}
|
||||||
|
}, [isResizing])
|
||||||
|
|
||||||
const getScriptWebSocketUrl = (): string => {
|
const getScriptWebSocketUrl = (): string => {
|
||||||
if (typeof window === "undefined") {
|
if (typeof window === "undefined") {
|
||||||
return `ws://localhost:${API_PORT}/ws/script/${sessionId}`
|
return `ws://localhost:${API_PORT}/ws/script/${sessionId}`
|
||||||
@@ -67,6 +131,7 @@ export function ScriptTerminalModal({
|
|||||||
|
|
||||||
const handleWebSocketCreated = (ws: WebSocket) => {
|
const handleWebSocketCreated = (ws: WebSocket) => {
|
||||||
wsRef.current = ws
|
wsRef.current = ws
|
||||||
|
setIsConnected(ws.readyState === WebSocket.OPEN)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleWebInteraction = (interaction: WebInteraction) => {
|
const handleWebInteraction = (interaction: WebInteraction) => {
|
||||||
@@ -92,32 +157,41 @@ export function ScriptTerminalModal({
|
|||||||
setInteractionInput("")
|
setInteractionInput("")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleCloseModal = () => {
|
||||||
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||||
|
wsRef.current.close()
|
||||||
|
}
|
||||||
|
if (checkConnectionInterval.current) {
|
||||||
|
clearInterval(checkConnectionInterval.current)
|
||||||
|
}
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Dialog open={open} onOpenChange={onClose}>
|
<Dialog open={open}>
|
||||||
<DialogContent className="max-w-4xl h-[80vh] p-0 flex flex-col">
|
<DialogContent
|
||||||
|
className="max-w-4xl p-0 flex flex-col"
|
||||||
|
style={{ height: isMobile ? "80vh" : `${modalHeight}vh` }}
|
||||||
|
onInteractOutside={(e) => e.preventDefault()}
|
||||||
|
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
<DialogTitle className="sr-only">{title}</DialogTitle>
|
<DialogTitle className="sr-only">{title}</DialogTitle>
|
||||||
|
|
||||||
{/* Header */}
|
<div className="flex items-center gap-2 p-4 border-b">
|
||||||
<div className="flex items-center justify-between p-4 border-b">
|
{isComplete ? (
|
||||||
<div className="flex items-center gap-2">
|
exitCode === 0 ? (
|
||||||
{isComplete ? (
|
<CheckCircle2 className="h-5 w-5 text-green-500" />
|
||||||
exitCode === 0 ? (
|
|
||||||
<CheckCircle2 className="h-5 w-5 text-green-500" />
|
|
||||||
) : (
|
|
||||||
<XCircle className="h-5 w-5 text-red-500" />
|
|
||||||
)
|
|
||||||
) : (
|
) : (
|
||||||
<Loader2 className="h-5 w-5 animate-spin" />
|
<XCircle className="h-5 w-5 text-red-500" />
|
||||||
)}
|
)
|
||||||
<div>
|
) : (
|
||||||
<h2 className="text-lg font-semibold">{title}</h2>
|
<Loader2 className="h-5 w-5 animate-spin" />
|
||||||
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
)}
|
||||||
</div>
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold">{title}</h2>
|
||||||
|
{description && <p className="text-sm text-muted-foreground">{description}</p>}
|
||||||
</div>
|
</div>
|
||||||
<Button variant="ghost" size="icon" onClick={onClose}>
|
|
||||||
<X className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-1 overflow-hidden">
|
<div className="flex-1 overflow-hidden">
|
||||||
@@ -129,13 +203,37 @@ export function ScriptTerminalModal({
|
|||||||
}}
|
}}
|
||||||
onWebInteraction={handleWebInteraction}
|
onWebInteraction={handleWebInteraction}
|
||||||
onWebSocketCreated={handleWebSocketCreated}
|
onWebSocketCreated={handleWebSocketCreated}
|
||||||
|
isScriptModal={true}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Footer */}
|
{!isMobile && (
|
||||||
|
<div
|
||||||
|
className="h-2 bg-border hover:bg-primary/20 cursor-ns-resize flex items-center justify-center transition-colors"
|
||||||
|
onMouseDown={handleResizeStart}
|
||||||
|
onTouchStart={handleResizeStart}
|
||||||
|
>
|
||||||
|
<GripHorizontal className="h-4 w-4 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="flex items-center justify-between p-4 border-t">
|
<div className="flex items-center justify-between p-4 border-t">
|
||||||
<div className="text-sm text-muted-foreground">Session ID: {sessionId}</div>
|
<div className="flex items-center gap-3">
|
||||||
{isComplete && <Button onClick={onClose}>Close</Button>}
|
<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>
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
@@ -176,11 +274,18 @@ export function ScriptTerminalModal({
|
|||||||
key={option.value}
|
key={option.value}
|
||||||
onClick={() => handleInteractionResponse(option.value)}
|
onClick={() => handleInteractionResponse(option.value)}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className="w-full justify-start"
|
className="w-full justify-start hover:bg-blue-600 hover:text-white"
|
||||||
>
|
>
|
||||||
{option.label}
|
{option.label}
|
||||||
</Button>
|
</Button>
|
||||||
))}
|
))}
|
||||||
|
<Button
|
||||||
|
onClick={() => handleInteractionResponse("cancel")}
|
||||||
|
variant="outline"
|
||||||
|
className="w-full hover:bg-red-600 hover:text-white hover:border-red-600"
|
||||||
|
>
|
||||||
|
Cancel / Go Back
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -197,14 +302,29 @@ export function ScriptTerminalModal({
|
|||||||
}}
|
}}
|
||||||
placeholder={currentInteraction.default || ""}
|
placeholder={currentInteraction.default || ""}
|
||||||
/>
|
/>
|
||||||
<Button onClick={() => handleInteractionResponse(interactionInput)} className="w-full">
|
<div className="flex gap-2">
|
||||||
Submit
|
<Button
|
||||||
</Button>
|
onClick={() => handleInteractionResponse(interactionInput)}
|
||||||
|
className="flex-1 bg-blue-600 hover:bg-blue-700"
|
||||||
|
>
|
||||||
|
Submit
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => handleInteractionResponse("")}
|
||||||
|
variant="outline"
|
||||||
|
className="flex-1 hover:bg-red-600 hover:text-white hover:border-red-600"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{currentInteraction.type === "msgbox" && (
|
{currentInteraction.type === "msgbox" && (
|
||||||
<Button onClick={() => handleInteractionResponse("ok")} className="w-full">
|
<Button
|
||||||
|
onClick={() => handleInteractionResponse("ok")}
|
||||||
|
className="w-full bg-blue-600 hover:bg-blue-700"
|
||||||
|
>
|
||||||
OK
|
OK
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ type TerminalPanelProps = {
|
|||||||
initMessage?: Record<string, any>
|
initMessage?: Record<string, any>
|
||||||
onWebInteraction?: (interaction: any) => void
|
onWebInteraction?: (interaction: any) => void
|
||||||
onWebSocketCreated?: (ws: WebSocket) => void
|
onWebSocketCreated?: (ws: WebSocket) => void
|
||||||
|
isScriptModal?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TerminalInstance {
|
interface TerminalInstance {
|
||||||
@@ -141,6 +142,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
initMessage,
|
initMessage,
|
||||||
onWebInteraction,
|
onWebInteraction,
|
||||||
onWebSocketCreated,
|
onWebSocketCreated,
|
||||||
|
isScriptModal = false,
|
||||||
}) => {
|
}) => {
|
||||||
const [terminals, setTerminals] = useState<TerminalInstance[]>([])
|
const [terminals, setTerminals] = useState<TerminalInstance[]>([])
|
||||||
const [activeTerminalId, setActiveTerminalId] = useState<string>("")
|
const [activeTerminalId, setActiveTerminalId] = useState<string>("")
|
||||||
@@ -246,8 +248,6 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
throw new Error("No examples found")
|
throw new Error("No examples found")
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("[v0] Received parsed examples from server:", data.examples.length)
|
|
||||||
|
|
||||||
const formattedResults: CheatSheetResult[] = data.examples.map((example: any) => ({
|
const formattedResults: CheatSheetResult[] = data.examples.map((example: any) => ({
|
||||||
command: example.command,
|
command: example.command,
|
||||||
description: example.description || "",
|
description: example.description || "",
|
||||||
@@ -257,7 +257,6 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
setUseOnline(true)
|
setUseOnline(true)
|
||||||
setSearchResults(formattedResults)
|
setSearchResults(formattedResults)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log("[v0] Error fetching from cheat.sh proxy, using offline commands:", error)
|
|
||||||
const filtered = proxmoxCommands.filter(
|
const filtered = proxmoxCommands.filter(
|
||||||
(item) =>
|
(item) =>
|
||||||
item.cmd.toLowerCase().includes(query.toLowerCase()) ||
|
item.cmd.toLowerCase().includes(query.toLowerCase()) ||
|
||||||
@@ -442,7 +441,6 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (initMessage) {
|
if (initMessage) {
|
||||||
console.log("[v0] TerminalPanel: Sending init message:", initMessage)
|
|
||||||
ws.send(JSON.stringify(initMessage))
|
ws.send(JSON.stringify(initMessage))
|
||||||
} else {
|
} else {
|
||||||
term.writeln("\x1b[32mConnected to ProxMenux terminal.\x1b[0m")
|
term.writeln("\x1b[32mConnected to ProxMenux terminal.\x1b[0m")
|
||||||
@@ -454,8 +452,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
ws.onmessage = (event) => {
|
ws.onmessage = (event) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(event.data)
|
const data = JSON.parse(event.data)
|
||||||
if (data.type === "web_interaction" && onWebInteraction) {
|
if (data.type === "web_interaction" && data.interaction && onWebInteraction) {
|
||||||
console.log("[v0] TerminalPanel: Intercepted web_interaction:", data.interaction)
|
|
||||||
onWebInteraction(data.interaction)
|
onWebInteraction(data.interaction)
|
||||||
return // Don't write to terminal
|
return // Don't write to terminal
|
||||||
}
|
}
|
||||||
@@ -466,8 +463,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
term.write(event.data)
|
term.write(event.data)
|
||||||
}
|
}
|
||||||
|
|
||||||
ws.onerror = (error) => {
|
ws.onerror = () => {
|
||||||
console.error("[v0] TerminalPanel: WebSocket error:", error)
|
|
||||||
setTerminals((prev) => prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: false } : t)))
|
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")
|
term.writeln("\r\n\x1b[31m[ERROR] WebSocket connection error\x1b[0m")
|
||||||
}
|
}
|
||||||
@@ -603,80 +599,88 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full bg-zinc-950 rounded-md overflow-hidden">
|
<div className="flex flex-col h-full bg-zinc-950 rounded-md overflow-hidden">
|
||||||
<div className="flex items-center justify-between px-4 py-2 bg-zinc-900 border-b border-zinc-800">
|
{!isScriptModal && (
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center justify-between px-4 py-2 bg-zinc-900 border-b border-zinc-800">
|
||||||
<Activity className="h-5 w-5 text-blue-500" />
|
<div className="flex items-center gap-3">
|
||||||
<div
|
<Activity className="h-5 w-5 text-blue-500" />
|
||||||
className={`w-2 h-2 rounded-full ${activeTerminal?.isConnected ? "bg-green-500" : "bg-red-500"}`}
|
<div
|
||||||
title={activeTerminal?.isConnected ? "Connected" : "Disconnected"}
|
className={`w-2 h-2 rounded-full ${activeTerminal?.isConnected ? "bg-green-500" : "bg-red-500"}`}
|
||||||
></div>
|
title={activeTerminal?.isConnected ? "Connected" : "Disconnected"}
|
||||||
<span className="text-xs text-zinc-500">{terminals.length} / 4 terminals</span>
|
></div>
|
||||||
</div>
|
<span className="text-xs text-zinc-500">{terminals.length} / 4 terminals</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
{!isMobile && terminals.length > 1 && (
|
{!isMobile && terminals.length > 1 && (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => setLayout("single")}
|
onClick={() => setLayout("single")}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className={`h-8 px-2 ${layout === "single" ? "bg-blue-500/20 border-blue-500" : ""}`}
|
className={`h-8 px-2 ${layout === "single" ? "bg-blue-500/20 border-blue-500" : ""}`}
|
||||||
title="Vista apilada (filas)"
|
title="Vista apilada (filas)"
|
||||||
>
|
>
|
||||||
<AlignJustify className="h-4 w-4" />
|
<AlignJustify className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => setLayout("grid")}
|
onClick={() => setLayout("grid")}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className={`h-8 px-2 ${layout === "grid" ? "bg-blue-500/20 border-blue-500" : ""}`}
|
className={`h-8 px-2 ${layout === "grid" ? "bg-blue-500/20 border-blue-500" : ""}`}
|
||||||
title="Vista cuadrícula 2x2"
|
title="Vista cuadrícula 2x2"
|
||||||
>
|
>
|
||||||
<Grid2X2 className="h-4 w-4" />
|
<Grid2X2 className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<Button
|
<Button
|
||||||
onClick={addNewTerminal}
|
onClick={addNewTerminal}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
disabled={terminals.length >= 4}
|
disabled={terminals.length >= 4}
|
||||||
className="h-8 gap-2 bg-green-600 hover:bg-green-700 border-green-500 text-white disabled:opacity-50"
|
className="h-8 gap-2 bg-green-600 hover:bg-green-700 border-green-500 text-white disabled:opacity-50"
|
||||||
>
|
>
|
||||||
<Plus className="h-4 w-4" />
|
<Plus className="h-4 w-4" />
|
||||||
<span className="hidden sm:inline">New</span>
|
<span className="hidden sm:inline">New</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => setSearchModalOpen(true)}
|
onClick={() => setSearchModalOpen(true)}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
disabled={!activeTerminal?.isConnected}
|
disabled={!activeTerminal?.isConnected}
|
||||||
className="h-8 gap-2 bg-blue-600 hover:bg-blue-700 border-blue-500 text-white disabled:opacity-50"
|
className="h-8 gap-2 bg-blue-600 hover:bg-blue-700 border-blue-500 text-white disabled:opacity-50"
|
||||||
>
|
>
|
||||||
<Search className="h-4 w-4" />
|
<Search className="h-4 w-4" />
|
||||||
<span className="hidden sm:inline">Search</span>
|
<span className="hidden sm:inline">Search</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleClear}
|
onClick={handleClear}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
disabled={!activeTerminal?.isConnected}
|
disabled={!activeTerminal?.isConnected}
|
||||||
className="h-8 gap-2 bg-yellow-600 hover:bg-yellow-700 border-yellow-500 text-white disabled:opacity-50"
|
className="h-8 gap-2 bg-yellow-600 hover:bg-yellow-700 border-yellow-500 text-white disabled:opacity-50"
|
||||||
>
|
>
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4" />
|
||||||
<span className="hidden sm:inline">Clear</span>
|
<span className="hidden sm:inline">Clear</span>
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleClose}
|
onClick={handleClose}
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="h-8 gap-2 bg-red-600 hover:bg-red-700 border-red-500 text-white"
|
className="h-8 gap-2 bg-red-600 hover:bg-red-700 border-red-500 text-white"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
<span className="hidden sm:inline">Close</span>
|
<span className="hidden sm:inline">Close</span>
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
|
|
||||||
|
{isScriptModal && (
|
||||||
|
<div className="sr-only" data-connection-status={activeTerminal?.isConnected ? "connected" : "disconnected"}>
|
||||||
|
Connection Status
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
data-terminal-container
|
data-terminal-container
|
||||||
|
|||||||
@@ -242,54 +242,38 @@ def terminal_websocket(ws):
|
|||||||
def script_websocket(ws, session_id):
|
def script_websocket(ws, session_id):
|
||||||
"""WebSocket endpoint for executing scripts with hybrid web mode"""
|
"""WebSocket endpoint for executing scripts with hybrid web mode"""
|
||||||
|
|
||||||
print(f"[DEBUG] Script WebSocket connected for session: {session_id}")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
print(f"[DEBUG] Waiting for init data...")
|
|
||||||
init_data = ws.receive(timeout=10)
|
init_data = ws.receive(timeout=10)
|
||||||
print(f"[DEBUG] Received init data: {init_data}")
|
|
||||||
|
|
||||||
if not init_data:
|
if not init_data:
|
||||||
error_msg = '{"type": "error", "message": "No script data received"}\r\n'
|
error_msg = '{"type": "error", "message": "No script data received"}\r\n'
|
||||||
print(f"[DEBUG] Error: No init data received")
|
|
||||||
ws.send(error_msg)
|
ws.send(error_msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
script_data = json.loads(init_data)
|
script_data = json.loads(init_data)
|
||||||
print(f"[DEBUG] Parsed script data: {script_data}")
|
|
||||||
|
|
||||||
script_path = script_data.get('script_path')
|
script_path = script_data.get('script_path')
|
||||||
params = script_data.get('params', {})
|
params = script_data.get('params', {})
|
||||||
|
|
||||||
print(f"[DEBUG] Script path: {script_path}")
|
|
||||||
print(f"[DEBUG] Params: {params}")
|
|
||||||
|
|
||||||
if not script_path:
|
if not script_path:
|
||||||
error_msg = '{"type": "error", "message": "No script_path provided"}\r\n'
|
error_msg = '{"type": "error", "message": "No script_path provided"}\r\n'
|
||||||
print(f"[DEBUG] Error: No script_path in data")
|
|
||||||
ws.send(error_msg)
|
ws.send(error_msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
if not os.path.exists(script_path):
|
if not os.path.exists(script_path):
|
||||||
error_msg = f'{{"type": "error", "message": "Script not found: {script_path}"}}\r\n'
|
error_msg = f'{{"type": "error", "message": "Script not found: {script_path}"}}\r\n'
|
||||||
print(f"[DEBUG] Error: Script file not found: {script_path}")
|
|
||||||
ws.send(error_msg)
|
ws.send(error_msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
print(f"[DEBUG] Script file exists, starting execution...")
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
error_msg = f'{{"type": "error", "message": "Invalid init data: {str(e)}"}}\r\n'
|
error_msg = f'{{"type": "error", "message": "Invalid init data: {str(e)}"}}\r\n'
|
||||||
print(f"[DEBUG] Exception parsing init data: {e}")
|
|
||||||
ws.send(error_msg)
|
ws.send(error_msg)
|
||||||
return
|
return
|
||||||
|
|
||||||
web_log_fd, web_log_path = tempfile.mkstemp(suffix='.log', prefix='proxmenux_web_')
|
web_log_fd, web_log_path = tempfile.mkstemp(suffix='.log', prefix='proxmenux_web_')
|
||||||
print(f"[DEBUG] Created WEB_LOG file: {web_log_path}")
|
|
||||||
|
|
||||||
# Create pseudo-terminal for script execution
|
# Create pseudo-terminal for script execution
|
||||||
master_fd, slave_fd = pty.openpty()
|
master_fd, slave_fd = pty.openpty()
|
||||||
print(f"[DEBUG] Created PTY: master_fd={master_fd}, slave_fd={slave_fd}")
|
|
||||||
|
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
env['EXECUTION_MODE'] = 'web'
|
env['EXECUTION_MODE'] = 'web'
|
||||||
@@ -299,7 +283,6 @@ def script_websocket(ws, session_id):
|
|||||||
env['PYTHONUNBUFFERED'] = '1'
|
env['PYTHONUNBUFFERED'] = '1'
|
||||||
env['TERM'] = 'xterm-256color'
|
env['TERM'] = 'xterm-256color'
|
||||||
|
|
||||||
print(f"[DEBUG] Starting script in hybrid web mode: {script_path}")
|
|
||||||
script_process = subprocess.Popen(
|
script_process = subprocess.Popen(
|
||||||
['/bin/bash', script_path],
|
['/bin/bash', script_path],
|
||||||
stdin=slave_fd,
|
stdin=slave_fd,
|
||||||
@@ -308,7 +291,6 @@ def script_websocket(ws, session_id):
|
|||||||
preexec_fn=os.setsid,
|
preexec_fn=os.setsid,
|
||||||
env=env
|
env=env
|
||||||
)
|
)
|
||||||
print(f"[DEBUG] Script process started with PID: {script_process.pid}")
|
|
||||||
|
|
||||||
# Set non-blocking mode for master_fd
|
# Set non-blocking mode for master_fd
|
||||||
flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
|
flags = fcntl.fcntl(master_fd, fcntl.F_GETFL)
|
||||||
@@ -318,7 +300,6 @@ def script_websocket(ws, session_id):
|
|||||||
set_winsize(master_fd, 30, 120)
|
set_winsize(master_fd, 30, 120)
|
||||||
|
|
||||||
def monitor_web_log():
|
def monitor_web_log():
|
||||||
print(f"[DEBUG] WEB_LOG monitor thread started")
|
|
||||||
last_position = 0
|
last_position = 0
|
||||||
|
|
||||||
while script_process.poll() is None:
|
while script_process.poll() is None:
|
||||||
@@ -332,7 +313,6 @@ def script_websocket(ws, session_id):
|
|||||||
for line in new_lines:
|
for line in new_lines:
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line.startswith('WEB_INTERACTION:'):
|
if line.startswith('WEB_INTERACTION:'):
|
||||||
print(f"[DEBUG] Detected web interaction: {line[:100]}")
|
|
||||||
try:
|
try:
|
||||||
# Parse: WEB_INTERACTION:type:id:title_b64:message_b64[:options_json]
|
# Parse: WEB_INTERACTION:type:id:title_b64:message_b64[:options_json]
|
||||||
parts = line[16:].split(':', 4)
|
parts = line[16:].split(':', 4)
|
||||||
@@ -366,24 +346,19 @@ def script_websocket(ws, session_id):
|
|||||||
|
|
||||||
# Send interaction to WebSocket
|
# Send interaction to WebSocket
|
||||||
ws.send(json.dumps(interaction_data))
|
ws.send(json.dumps(interaction_data))
|
||||||
print(f"[DEBUG] Sent web interaction to client: {interaction_type}")
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Error parsing web interaction: {e}")
|
pass
|
||||||
|
|
||||||
time.sleep(0.1)
|
time.sleep(0.1)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Error monitoring WEB_LOG: {e}")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
print(f"[DEBUG] WEB_LOG monitor thread stopped")
|
|
||||||
|
|
||||||
web_log_thread = threading.Thread(target=monitor_web_log, daemon=True)
|
web_log_thread = threading.Thread(target=monitor_web_log, daemon=True)
|
||||||
web_log_thread.start()
|
web_log_thread.start()
|
||||||
|
|
||||||
# Thread to read script output and forward to WebSocket
|
# Thread to read script output and forward to WebSocket
|
||||||
def read_script_output():
|
def read_script_output():
|
||||||
print(f"[DEBUG] Output reader thread started")
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
r, _, _ = select.select([master_fd], [], [], 0.01)
|
r, _, _ = select.select([master_fd], [], [], 0.01)
|
||||||
@@ -391,7 +366,6 @@ def script_websocket(ws, session_id):
|
|||||||
try:
|
try:
|
||||||
data = os.read(master_fd, 4096)
|
data = os.read(master_fd, 4096)
|
||||||
if not data:
|
if not data:
|
||||||
print(f"[DEBUG] No more data from script")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
text = data.decode('utf-8', errors='ignore')
|
text = data.decode('utf-8', errors='ignore')
|
||||||
@@ -400,35 +374,29 @@ def script_websocket(ws, session_id):
|
|||||||
try:
|
try:
|
||||||
ws.send(text)
|
ws.send(text)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Error sending to WebSocket: {e}")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
print(f"[DEBUG] OSError reading from PTY: {e}")
|
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Error reading script output: {e}")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
script_process.wait()
|
script_process.wait()
|
||||||
exit_code = script_process.returncode if script_process.returncode is not None else 0
|
exit_code = script_process.returncode if script_process.returncode is not None else 0
|
||||||
print(f"[DEBUG] Script exited with code: {exit_code}")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
ws.send(f'\r\n[Script exited with code {exit_code}]\r\n')
|
ws.send(f'\r\n[Script exited with code {exit_code}]\r\n')
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Could not send exit message: {e}")
|
pass
|
||||||
|
|
||||||
output_thread = threading.Thread(target=read_script_output, daemon=True)
|
output_thread = threading.Thread(target=read_script_output, daemon=True)
|
||||||
output_thread.start()
|
output_thread.start()
|
||||||
print(f"[DEBUG] Output thread started")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
data = ws.receive(timeout=None)
|
data = ws.receive(timeout=None)
|
||||||
|
|
||||||
if data is None:
|
if data is None:
|
||||||
print(f"[DEBUG] WebSocket closed by client")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -440,7 +408,6 @@ def script_websocket(ws, session_id):
|
|||||||
|
|
||||||
# Write response to the file the script is waiting for
|
# Write response to the file the script is waiting for
|
||||||
response_file = f"/tmp/proxmenux_response_{interaction_id}"
|
response_file = f"/tmp/proxmenux_response_{interaction_id}"
|
||||||
print(f"[DEBUG] Writing interaction response to {response_file}: {value}")
|
|
||||||
|
|
||||||
with open(response_file, 'w') as f:
|
with open(response_file, 'w') as f:
|
||||||
f.write(value)
|
f.write(value)
|
||||||
@@ -452,7 +419,6 @@ def script_websocket(ws, session_id):
|
|||||||
cols = int(msg.get('cols', 120))
|
cols = int(msg.get('cols', 120))
|
||||||
rows = int(msg.get('rows', 30))
|
rows = int(msg.get('rows', 30))
|
||||||
set_winsize(master_fd, rows, cols)
|
set_winsize(master_fd, rows, cols)
|
||||||
print(f"[DEBUG] Resized terminal to {cols}x{rows}")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
@@ -460,17 +426,14 @@ def script_websocket(ws, session_id):
|
|||||||
try:
|
try:
|
||||||
os.write(master_fd, data.encode('utf-8'))
|
os.write(master_fd, data.encode('utf-8'))
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
print(f"[DEBUG] Error writing to script: {e}")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
if script_process.poll() is not None:
|
if script_process.poll() is not None:
|
||||||
print(f"[DEBUG] Script process terminated")
|
|
||||||
break
|
break
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[DEBUG] Script session error: {e}")
|
pass
|
||||||
finally:
|
finally:
|
||||||
print(f"[DEBUG] Cleaning up script session")
|
|
||||||
try:
|
try:
|
||||||
script_process.terminate()
|
script_process.terminate()
|
||||||
script_process.wait(timeout=1)
|
script_process.wait(timeout=1)
|
||||||
@@ -493,7 +456,6 @@ def script_websocket(ws, session_id):
|
|||||||
try:
|
try:
|
||||||
os.close(web_log_fd)
|
os.close(web_log_fd)
|
||||||
os.unlink(web_log_path)
|
os.unlink(web_log_path)
|
||||||
print(f"[DEBUG] Removed WEB_LOG file: {web_log_path}")
|
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user