Update AppImage

This commit is contained in:
MacRimi
2025-12-06 21:30:17 +01:00
parent 9bd403ec51
commit 4378a5843c
2 changed files with 125 additions and 113 deletions

View File

@@ -8,7 +8,7 @@ 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 { CheckCircle2, XCircle, Loader2, Activity, GripHorizontal } from "lucide-react" import { CheckCircle2, XCircle, Loader2, Activity, GripHorizontal } from "lucide-react"
import { API_PORT } from "@/lib/api-config" import { fetchApi, API_PORT } from "@/lib/api-config"
import { useIsMobile } from "@/hooks/use-mobile" import { useIsMobile } from "@/hooks/use-mobile"
interface WebInteraction { interface WebInteraction {
@@ -39,7 +39,7 @@ export function ScriptTerminalModal({
title, title,
description, description,
}: ScriptTerminalModalProps) { }: ScriptTerminalModalProps) {
const [sessionId] = useState(() => Math.random().toString(36).substring(7)) const [sessionId, setSessionId] = useState<string | null>(null)
const [isComplete, setIsComplete] = useState(false) const [isComplete, setIsComplete] = useState(false)
const [exitCode, setExitCode] = useState<number | null>(null) const [exitCode, setExitCode] = useState<number | null>(null)
const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null) const [currentInteraction, setCurrentInteraction] = useState<WebInteraction | null>(null)
@@ -62,21 +62,46 @@ export function ScriptTerminalModal({
const fitAddonRef = useRef<any>(null) const fitAddonRef = useRef<any>(null)
useEffect(() => { useEffect(() => {
if (open) { if (!open) {
setIsComplete(false) return
setExitCode(null)
setInteractionInput("")
setCurrentInteraction(null)
setIsConnected(false)
setIsWaitingNextInteraction(false)
checkConnectionInterval.current = setInterval(() => {
if (wsRef.current) {
setIsConnected(wsRef.current.readyState === WebSocket.OPEN)
}
}, 500)
} }
const executeScript = async () => {
try {
console.log("[v0] Executing script:", scriptPath)
const response = await fetchApi<{ success: boolean; session_id: string }>("/api/scripts/execute", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
script_name: scriptName,
script_relative_path: scriptPath,
params: params,
}),
})
if (response.success && response.session_id) {
console.log("[v0] Script started with session:", response.session_id)
setSessionId(response.session_id)
} else {
console.error("[v0] Failed to start script")
}
} catch (error) {
console.error("[v0] Error executing script:", error)
}
}
setIsComplete(false)
setExitCode(null)
setInteractionInput("")
setCurrentInteraction(null)
setIsConnected(false)
setIsWaitingNextInteraction(false)
setSessionId(null)
executeScript()
return () => { return () => {
if (checkConnectionInterval.current) { if (checkConnectionInterval.current) {
clearInterval(checkConnectionInterval.current) clearInterval(checkConnectionInterval.current)
@@ -93,10 +118,10 @@ export function ScriptTerminalModal({
wsRef.current = null wsRef.current = null
} }
} }
}, [open]) }, [open, scriptPath, scriptName, params])
useEffect(() => { useEffect(() => {
if (!open || !terminalContainerRef.current || terminalRef.current) { if (!open || !sessionId || !terminalContainerRef.current || terminalRef.current) {
return return
} }
@@ -147,29 +172,36 @@ export function ScriptTerminalModal({
const fitAddon = new FitAddonClass() const fitAddon = new FitAddonClass()
term.loadAddon(fitAddon) term.loadAddon(fitAddon)
term.open(terminalContainerRef.current!) term.open(terminalContainerRef.current!)
fitAddon.fit()
setTimeout(() => {
try {
fitAddon.fit()
} catch (err) {
console.warn("[v0] Initial fit failed:", err)
}
}, 50)
terminalRef.current = term terminalRef.current = term
fitAddonRef.current = fitAddon fitAddonRef.current = fitAddon
const wsUrl = getScriptWebSocketUrl() const wsUrl = getScriptWebSocketUrl(sessionId)
console.log("[v0] Connecting to WebSocket:", wsUrl)
const ws = new WebSocket(wsUrl) const ws = new WebSocket(wsUrl)
ws.onopen = () => { ws.onopen = () => {
console.log("[v0] WebSocket connected")
setIsConnected(true) setIsConnected(true)
ws.send( try {
JSON.stringify({ ws.send(
script_path: scriptPath, JSON.stringify({
params: params, type: "resize",
}), cols: term.cols,
) rows: term.rows,
ws.send( }),
JSON.stringify({ )
type: "resize", } catch (err) {
cols: term.cols, console.warn("[v0] Failed to send initial resize:", err)
rows: term.rows, }
}),
)
} }
ws.onmessage = (event) => { ws.onmessage = (event) => {
@@ -219,39 +251,59 @@ export function ScriptTerminalModal({
}) })
wsRef.current = ws wsRef.current = ws
checkConnectionInterval.current = setInterval(() => {
if (ws) {
setIsConnected(ws.readyState === WebSocket.OPEN)
}
}, 500)
} }
initTerminal() initTerminal()
}, [open, scriptPath, params]) }, [open, sessionId])
useEffect(() => { useEffect(() => {
if (!terminalContainerRef.current || !terminalRef.current || !fitAddonRef.current) { if (!terminalContainerRef.current || !terminalRef.current || !fitAddonRef.current) {
return return
} }
let resizeTimeout: NodeJS.Timeout | null = null
const resizeObserver = new ResizeObserver(() => { const resizeObserver = new ResizeObserver(() => {
if (fitAddonRef.current && terminalRef.current && wsRef.current?.readyState === WebSocket.OPEN) { if (resizeTimeout) {
try { clearTimeout(resizeTimeout)
fitAddonRef.current.fit()
wsRef.current.send(
JSON.stringify({
type: "resize",
cols: terminalRef.current.cols,
rows: terminalRef.current.rows,
}),
)
} catch (err) {
console.warn("[ScriptTerminal] resize failed:", err)
}
} }
resizeTimeout = setTimeout(() => {
if (fitAddonRef.current && terminalRef.current && wsRef.current?.readyState === WebSocket.OPEN) {
try {
fitAddonRef.current.fit()
const cols = terminalRef.current.cols
const rows = terminalRef.current.rows
console.log("[v0] Terminal resized to:", cols, "x", rows)
wsRef.current.send(
JSON.stringify({
type: "resize",
cols: cols,
rows: rows,
}),
)
} catch (err) {
console.warn("[v0] Resize failed:", err)
}
}
}, 100)
}) })
resizeObserver.observe(terminalContainerRef.current) resizeObserver.observe(terminalContainerRef.current)
return () => { return () => {
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeObserver.disconnect() resizeObserver.disconnect()
} }
}, [open]) }, [open, sessionId])
const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => { const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => {
if (isMobile) return if (isMobile) return
@@ -263,23 +315,23 @@ export function ScriptTerminalModal({
e.preventDefault() e.preventDefault()
} }
const handleResizeMove = (e: MouseEvent | TouchEvent) => {
const currentY = "touches" in e ? e.touches[0].clientY : e.clientY
const deltaY = currentY - startYRef.current
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)
}
useEffect(() => { useEffect(() => {
if (!isResizing) return if (!isResizing) return
const handleResizeMove = (e: MouseEvent | TouchEvent) => {
const currentY = "touches" in e ? e.touches[0].clientY : e.clientY
const deltaY = currentY - startYRef.current
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("mousemove", handleResizeMove)
document.addEventListener("mouseup", handleResizeEnd) document.addEventListener("mouseup", handleResizeEnd)
document.addEventListener("touchmove", handleResizeMove) document.addEventListener("touchmove", handleResizeMove)
@@ -293,14 +345,14 @@ export function ScriptTerminalModal({
} }
}, [isResizing]) }, [isResizing])
const getScriptWebSocketUrl = (): string => { const getScriptWebSocketUrl = (sid: string): string => {
if (typeof window === "undefined") { if (typeof window === "undefined") {
return `ws://localhost:${API_PORT}/ws/script/${sessionId}` return `ws://localhost:${API_PORT}/ws/script/${sid}`
} }
const { hostname, protocol } = window.location const { hostname, protocol } = window.location
const wsProtocol = protocol === "https:" ? "wss:" : "ws:" const wsProtocol = protocol === "https:" ? "wss:" : "ws:"
return `${wsProtocol}//${hostname}:${API_PORT}/ws/script/${sessionId}` return `${wsProtocol}//${hostname}:${API_PORT}/ws/script/${sid}`
} }
const handleInteractionResponse = (value: string) => { const handleInteractionResponse = (value: string) => {
@@ -371,7 +423,7 @@ export function ScriptTerminalModal({
</div> </div>
</div> </div>
<div className="flex-1 overflow-hidden relative"> <div className="overflow-hidden relative" style={{ height: "calc(100% - 120px)" }}>
<div ref={terminalContainerRef} className="w-full h-full" /> <div ref={terminalContainerRef} className="w-full h-full" />
{isWaitingNextInteraction && !currentInteraction && ( {isWaitingNextInteraction && !currentInteraction && (

View File

@@ -26,10 +26,6 @@ import type { CheatSheetResult } from "@/lib/cheat-sheet-result" // Declare Chea
type TerminalPanelProps = { type TerminalPanelProps = {
websocketUrl?: string websocketUrl?: string
onClose?: () => void onClose?: () => void
initMessage?: Record<string, any>
onWebInteraction?: (interaction: any) => void
onWebSocketCreated?: (ws: WebSocket) => void
isScriptModal?: boolean
} }
interface TerminalInstance { interface TerminalInstance {
@@ -136,14 +132,7 @@ const proxmoxCommands = [
{ cmd: "clear", desc: "Clear terminal screen" }, { cmd: "clear", desc: "Clear terminal screen" },
] ]
export const TerminalPanel: React.FC<TerminalPanelProps> = ({ export const TerminalPanel: React.FC<TerminalPanelProps> = ({ websocketUrl, onClose }) => {
websocketUrl,
onClose,
initMessage,
onWebInteraction,
onWebSocketCreated,
isScriptModal = false,
}) => {
const [terminals, setTerminals] = useState<TerminalInstance[]>([]) const [terminals, setTerminals] = useState<TerminalInstance[]>([])
const [activeTerminalId, setActiveTerminalId] = useState<string>("") const [activeTerminalId, setActiveTerminalId] = useState<string>("")
const [layout, setLayout] = useState<"single" | "grid">("grid") const [layout, setLayout] = useState<"single" | "grid">("grid")
@@ -248,6 +237,8 @@ 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,6 +248,7 @@ 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()) ||
@@ -435,35 +427,16 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
setTerminals((prev) => setTerminals((prev) =>
prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: true, term, ws, fitAddon } : t)), prev.map((t) => (t.id === terminal.id ? { ...t, isConnected: true, term, ws, fitAddon } : t)),
) )
term.writeln("\x1b[32mConnected to ProxMenux terminal.\x1b[0m")
if (onWebSocketCreated) {
onWebSocketCreated(ws)
}
if (initMessage) {
ws.send(JSON.stringify(initMessage))
} else {
term.writeln("\x1b[32mConnected to ProxMenux terminal.\x1b[0m")
}
syncSizeWithBackend() syncSizeWithBackend()
} }
ws.onmessage = (event) => { ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
if (data.type === "web_interaction" && data.interaction && onWebInteraction) {
onWebInteraction(data.interaction)
return // Don't write to terminal
}
} catch (e) {
// Not JSON, it's regular terminal output
}
term.write(event.data) term.write(event.data)
} }
ws.onerror = () => { ws.onerror = (error) => {
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")
} }
@@ -674,12 +647,6 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
</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
ref={(el) => { ref={(el) => {
@@ -688,14 +655,7 @@ export const TerminalPanel: React.FC<TerminalPanelProps> = ({
className={`overflow-hidden flex flex-col ${isMobile ? "flex-1 h-[60vh]" : "overflow-hidden"} w-full max-w-full`} className={`overflow-hidden flex flex-col ${isMobile ? "flex-1 h-[60vh]" : "overflow-hidden"} w-full max-w-full`}
style={!isMobile || isTablet ? { height: `${terminalHeight}px`, flexShrink: 0 } : undefined} style={!isMobile || isTablet ? { height: `${terminalHeight}px`, flexShrink: 0 } : undefined}
> >
{isScriptModal ? ( {isMobile ? (
// In script modal: render terminal container directly without tabs
<div
ref={(el) => (containerRefs.current[activeTerminalId] = el)}
className="w-full h-full flex-1 bg-black overflow-hidden"
/>
) : // Normal terminal page: show tabs/grid as usual
isMobile ? (
<Tabs value={activeTerminalId} onValueChange={setActiveTerminalId} className="h-full flex flex-col"> <Tabs value={activeTerminalId} onValueChange={setActiveTerminalId} className="h-full flex flex-col">
<TabsList className="w-full justify-start bg-zinc-900 rounded-none border-b border-zinc-800 overflow-x-auto"> <TabsList className="w-full justify-start bg-zinc-900 rounded-none border-b border-zinc-800 overflow-x-auto">
{terminals.map((terminal) => ( {terminals.map((terminal) => (