Update AppImage

This commit is contained in:
MacRimi
2025-12-06 12:25:57 +01:00
parent 72006aff21
commit c627c65a7d
3 changed files with 148 additions and 38 deletions

View File

@@ -2043,7 +2043,9 @@ export default function Hardware() {
}}
scriptPath="/usr/local/share/proxmenux/scripts/gpu_tpu/nvidia_installer.sh"
scriptName="nvidia_installer"
params={{}}
params={{
EXECUTION_MODE: "web",
}}
title="NVIDIA Driver Installation"
description="Installing NVIDIA proprietary drivers for GPU monitoring..."
/>

View File

@@ -10,11 +10,12 @@ import { TerminalPanel } from "./terminal-panel"
import { API_PORT } from "@/lib/api-config"
interface WebInteraction {
type: "yesno" | "menu" | "msgbox" | "input"
type: "yesno" | "menu" | "msgbox" | "input" | "inputbox"
id: string
title: string
message: string
options?: Array<{ label: string; value: string }>
default?: string
}
interface ScriptTerminalModalProps {
@@ -42,6 +43,7 @@ export function ScriptTerminalModal({
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
const [interactionInput, setInteractionInput] = useState("")
const terminalRef = useRef<any>(null)
const wsRef = useRef<WebSocket | null>(null)
useEffect(() => {
if (open) {
@@ -57,10 +59,34 @@ export function ScriptTerminalModal({
useEffect(() => {
if (!open) return
// We'll pass initMessage prop to TerminalPanel instead
const handleWebSocketMessage = (event: MessageEvent) => {
try {
const data = JSON.parse(event.data)
console.log("[v0] Received WebSocket message:", data)
if (data.type === "web_interaction") {
console.log("[v0] Detected web interaction:", data.interaction)
setCurrentInteraction(data.interaction)
}
} catch (e) {
// Not JSON, ignore (it's terminal output)
}
}
const checkWs = setInterval(() => {
if (terminalRef.current?.ws) {
wsRef.current = terminalRef.current.ws
wsRef.current.addEventListener("message", handleWebSocketMessage)
clearInterval(checkWs)
console.log("[v0] Attached WebSocket message listener")
}
}, 100)
return () => {
// Cleanup if needed
clearInterval(checkWs)
if (wsRef.current) {
wsRef.current.removeEventListener("message", handleWebSocketMessage)
}
}
}, [open])
@@ -82,7 +108,7 @@ export function ScriptTerminalModal({
})
const handleInteractionResponse = (value: string) => {
if (!terminalRef.current || !currentInteraction) return
if (!wsRef.current || !currentInteraction) return
const response = JSON.stringify({
type: "interaction_response",
@@ -91,7 +117,7 @@ export function ScriptTerminalModal({
})
console.log("[v0] Sending interaction response:", response)
terminalRef.current.send(response)
wsRef.current.send(response)
setCurrentInteraction(null)
setInteractionInput("")
}
@@ -148,7 +174,7 @@ export function ScriptTerminalModal({
<DialogContent>
<DialogTitle>{currentInteraction.title}</DialogTitle>
<div className="space-y-4">
<p>{currentInteraction.message}</p>
<p className="whitespace-pre-wrap">{currentInteraction.message}</p>
{currentInteraction.type === "yesno" && (
<div className="flex gap-2">
@@ -176,23 +202,25 @@ export function ScriptTerminalModal({
</div>
)}
{currentInteraction.type === "input" && (
<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)
}
}}
/>
<Button onClick={() => handleInteractionResponse(interactionInput)} className="w-full">
Submit
</Button>
</div>
)}
{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 || ""}
/>
<Button onClick={() => handleInteractionResponse(interactionInput)} className="w-full">
Submit
</Button>
</div>
))}
{currentInteraction.type === "msgbox" && (
<Button onClick={() => handleInteractionResponse("ok")} className="w-full">

View File

@@ -17,6 +17,8 @@ import threading
import time
import requests
import json
import tempfile
import base64
terminal_bp = Blueprint('terminal', __name__)
sock = Sock()
@@ -282,21 +284,24 @@ def script_websocket(ws, session_id):
ws.send(error_msg)
return
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
master_fd, slave_fd = pty.openpty()
print(f"[DEBUG] Created PTY: master_fd={master_fd}, slave_fd={slave_fd}")
env = os.environ.copy()
env['EXECUTION_MODE'] = 'web'
env['WEB_LOG'] = web_log_path
for key, value in params.items():
env[key] = str(value)
# Force unbuffered output
env['PYTHONUNBUFFERED'] = '1'
env['TERM'] = 'xterm-256color'
# Add stdbuf to force unbuffered output for the script
print(f"[DEBUG] Starting script process with unbuffered output: {script_path}")
print(f"[DEBUG] Starting script in hybrid web mode: {script_path}")
script_process = subprocess.Popen(
['script', '-qefc', f'/bin/bash {script_path}', '/dev/null'],
['/bin/bash', script_path],
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
@@ -312,6 +317,70 @@ def script_websocket(ws, session_id):
# Set terminal size
set_winsize(master_fd, 30, 120)
def monitor_web_log():
print(f"[DEBUG] WEB_LOG monitor thread started")
last_position = 0
while script_process.poll() is None:
try:
if os.path.exists(web_log_path):
with open(web_log_path, 'r') as f:
f.seek(last_position)
new_lines = f.readlines()
last_position = f.tell()
for line in new_lines:
line = line.strip()
if line.startswith('WEB_INTERACTION:'):
print(f"[DEBUG] Detected web interaction: {line[:100]}")
try:
# Parse: WEB_INTERACTION:type:id:title_b64:message_b64[:options_json]
parts = line[16:].split(':', 4)
interaction_type = parts[0]
interaction_id = parts[1]
title_b64 = parts[2]
message_b64 = parts[3]
title = base64.b64decode(title_b64).decode('utf-8')
message = base64.b64decode(message_b64).decode('utf-8')
interaction_data = {
'type': 'web_interaction',
'interaction': {
'type': interaction_type,
'id': interaction_id,
'title': title,
'message': message
}
}
# Parse options for menu
if interaction_type == 'menu' and len(parts) > 4:
options_json = parts[4]
interaction_data['interaction']['options'] = json.loads(options_json)
# Parse default for inputbox
if interaction_type == 'inputbox' and len(parts) > 4:
default_b64 = parts[4]
interaction_data['interaction']['default'] = base64.b64decode(default_b64).decode('utf-8')
# Send interaction to WebSocket
ws.send(json.dumps(interaction_data))
print(f"[DEBUG] Sent web interaction to client: {interaction_type}")
except Exception as e:
print(f"[DEBUG] Error parsing web interaction: {e}")
time.sleep(0.1)
except Exception as e:
print(f"[DEBUG] Error monitoring WEB_LOG: {e}")
break
print(f"[DEBUG] WEB_LOG monitor thread stopped")
web_log_thread = threading.Thread(target=monitor_web_log, daemon=True)
web_log_thread.start()
# Thread to read script output and forward to WebSocket
def read_script_output():
print(f"[DEBUG] Output reader thread started")
@@ -326,12 +395,10 @@ def script_websocket(ws, session_id):
break
text = data.decode('utf-8', errors='ignore')
print(f"[DEBUG] Read {len(data)} bytes ({len(text)} chars) from script: {text[:100]}")
# Send raw text to terminal (TerminalPanel expects plain text)
# Send raw text to terminal
try:
ws.send(text)
print(f"[DEBUG] Sent {len(text)} chars to WebSocket")
except Exception as e:
print(f"[DEBUG] Error sending to WebSocket: {e}")
break
@@ -347,7 +414,6 @@ def script_websocket(ws, session_id):
exit_code = script_process.returncode if script_process.returncode is not None else 0
print(f"[DEBUG] Script exited with code: {exit_code}")
# Only send exit message if WebSocket is still open
try:
ws.send(f'\r\n[Script exited with code {exit_code}]\r\n')
except Exception as e:
@@ -359,18 +425,28 @@ def script_websocket(ws, session_id):
try:
while True:
# Receive user input or interaction responses
data = ws.receive(timeout=None)
if data is None:
print(f"[DEBUG] WebSocket closed by client")
break
print(f"[DEBUG] Received from client: {data[:100] if len(data) > 100 else data}")
try:
msg = json.loads(data)
if msg.get('type') == 'interaction_response':
interaction_id = msg.get('id')
value = msg.get('value')
# Write response to the file the script is waiting for
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:
f.write(value)
continue
# Handle resize
if msg.get('type') == 'resize':
cols = int(msg.get('cols', 120))
@@ -383,12 +459,10 @@ def script_websocket(ws, session_id):
# Raw text input, send to script
try:
os.write(master_fd, data.encode('utf-8'))
print(f"[DEBUG] Sent input to script")
except OSError as e:
print(f"[DEBUG] Error writing to script: {e}")
break
# Check if process is still alive
if script_process.poll() is not None:
print(f"[DEBUG] Script process terminated")
break
@@ -397,7 +471,6 @@ def script_websocket(ws, session_id):
print(f"[DEBUG] Script session error: {e}")
finally:
print(f"[DEBUG] Cleaning up script session")
# Cleanup
try:
script_process.terminate()
script_process.wait(timeout=1)
@@ -417,6 +490,13 @@ def script_websocket(ws, session_id):
except:
pass
try:
os.close(web_log_fd)
os.unlink(web_log_path)
print(f"[DEBUG] Removed WEB_LOG file: {web_log_path}")
except:
pass
def init_terminal_routes(app):
"""Initialize terminal routes with Flask app"""
sock.init_app(app)