Update script-terminal-modal.tsx

This commit is contained in:
MacRimi
2025-12-06 22:20:34 +01:00
parent 7fc967c64c
commit f90f6f364a

View File

@@ -1,7 +1,6 @@
"use client" "use client"
import type React from "react" 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"
@@ -30,6 +29,13 @@ interface ScriptTerminalModalProps {
description: string description: string
} }
interface TerminalInstance {
term: any | null
ws: WebSocket | null
fitAddon: any | null
isConnected: boolean
}
export function ScriptTerminalModal({ export function ScriptTerminalModal({
open, open,
onClose, onClose,
@@ -39,14 +45,18 @@ export function ScriptTerminalModal({
title, title,
description, description,
}: ScriptTerminalModalProps) { }: ScriptTerminalModalProps) {
const sessionIdRef = useRef<string | null>(null) const [terminal, setTerminal] = useState<TerminalInstance>({
const hasInitializedRef = useRef(false) term: null,
ws: null,
fitAddon: null,
isConnected: false,
})
const sessionIdRef = useRef<string>(Math.random().toString(36).substring(2, 8))
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)
const [interactionInput, setInteractionInput] = useState("") const [interactionInput, setInteractionInput] = useState("")
const wsRef = useRef<WebSocket | null>(null)
const [isConnected, setIsConnected] = useState(false)
const checkConnectionInterval = useRef<NodeJS.Timeout | null>(null) const checkConnectionInterval = useRef<NodeJS.Timeout | null>(null)
const isMobile = useIsMobile() const isMobile = useIsMobile()
@@ -58,88 +68,45 @@ export function ScriptTerminalModal({
const startYRef = useRef(0) const startYRef = useRef(0)
const startHeightRef = useRef(80) const startHeightRef = useRef(80)
const terminalRef = useRef<any>(null) const terminalContainerRef = useRef<HTMLDivElement | null>(null)
const fitAddonRef = useRef<any>(null)
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)
}
useEffect(() => { useEffect(() => {
if (!open) { if (!open) {
// Cleanup
if (checkConnectionInterval.current) { if (checkConnectionInterval.current) {
clearInterval(checkConnectionInterval.current) clearInterval(checkConnectionInterval.current)
} }
if (waitingTimeoutRef.current) { if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current) clearTimeout(waitingTimeoutRef.current)
} }
if (terminalRef.current) { if (terminal.ws) {
terminalRef.current.dispose() terminal.ws.close()
terminalRef.current = null
} }
if (wsRef.current) { if (terminal.term) {
wsRef.current.close() terminal.term.dispose()
wsRef.current = null
} }
// Reset for next open setTerminal({ term: null, ws: null, fitAddon: null, isConnected: false })
sessionIdRef.current = null sessionIdRef.current = Math.random().toString(36).substring(2, 8)
hasInitializedRef.current = false
setIsComplete(false) setIsComplete(false)
setExitCode(null) setExitCode(null)
setInteractionInput("") setInteractionInput("")
setCurrentInteraction(null) setCurrentInteraction(null)
setIsConnected(false)
setIsWaitingNextInteraction(false) setIsWaitingNextInteraction(false)
} }
}, [open]) }, [open])
const handleTerminalContainerRef = (node: HTMLDivElement | null) => { useEffect(() => {
if (!node || !open || hasInitializedRef.current) { const container = terminalContainerRef.current
if (!open || !container || terminal.term) {
return return
} }
console.log("[v0] Terminal container mounted, starting initialization") const initializeTerminal = async () => {
hasInitializedRef.current = true
// Generate session ID once
if (!sessionIdRef.current) {
sessionIdRef.current = Math.random().toString(36).substring(2, 8)
console.log("[v0] Generated session ID:", sessionIdRef.current)
}
const initTerminal = async () => {
console.log("[v0] Loading xterm modules...")
const [TerminalClass, FitAddonClass] = await Promise.all([ const [TerminalClass, FitAddonClass] = await Promise.all([
import("xterm").then((mod) => mod.Terminal), import("xterm").then((mod) => mod.Terminal),
import("xterm-addon-fit").then((mod) => mod.FitAddon), import("xterm-addon-fit").then((mod) => mod.FitAddon),
import("xterm/css/xterm.css"), import("xterm/css/xterm.css"),
]) ])
console.log("[v0] Creating terminal instance...")
const fontSize = window.innerWidth < 768 ? 12 : 16 const fontSize = window.innerWidth < 768 ? 12 : 16
const term = new TerminalClass({ const term = new TerminalClass({
@@ -179,28 +146,21 @@ export function ScriptTerminalModal({
const fitAddon = new FitAddonClass() const fitAddon = new FitAddonClass()
term.loadAddon(fitAddon) term.loadAddon(fitAddon)
term.open(node) term.open(container)
console.log("[v0] Terminal opened in container")
setTimeout(() => { setTimeout(() => {
try { try {
fitAddon.fit() fitAddon.fit()
console.log("[v0] Initial fit completed")
} catch (err) { } catch (err) {
console.error("[v0] Initial fit failed:", err) // Ignore
} }
}, 50) }, 50)
terminalRef.current = term const wsUrl = getScriptWebSocketUrl(sessionIdRef.current)
fitAddonRef.current = fitAddon
const wsUrl = getScriptWebSocketUrl(sessionIdRef.current!)
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!") setTerminal((prev) => ({ ...prev, isConnected: true, term, ws, fitAddon }))
setIsConnected(true)
const initMessage = { const initMessage = {
script_path: scriptPath, script_path: scriptPath,
@@ -210,16 +170,13 @@ export function ScriptTerminalModal({
}, },
} }
console.log("[v0] Sending init message:", initMessage)
ws.send(JSON.stringify(initMessage)) ws.send(JSON.stringify(initMessage))
// Fit and resize after connection
setTimeout(() => { setTimeout(() => {
try { try {
fitAddon.fit() fitAddon.fit()
const cols = term.cols const cols = term.cols
const rows = term.rows const rows = term.rows
console.log("[v0] Sending resize:", { cols, rows })
ws.send( ws.send(
JSON.stringify({ JSON.stringify({
type: "resize", type: "resize",
@@ -228,19 +185,16 @@ export function ScriptTerminalModal({
}), }),
) )
} catch (err) { } catch (err) {
console.error("[v0] Resize after connect failed:", err) // Ignore
} }
}, 100) }, 100)
} }
ws.onmessage = (event) => { ws.onmessage = (event) => {
console.log("[v0] Received message:", event.data)
try { try {
const msg = JSON.parse(event.data) const msg = JSON.parse(event.data)
// Detect web interactions
if (msg.type === "web_interaction" && msg.interaction) { if (msg.type === "web_interaction" && msg.interaction) {
console.log("[v0] Web interaction detected:", msg.interaction)
setIsWaitingNextInteraction(false) setIsWaitingNextInteraction(false)
if (waitingTimeoutRef.current) { if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current) clearTimeout(waitingTimeoutRef.current)
@@ -257,19 +211,15 @@ export function ScriptTerminalModal({
} }
if (msg.type === "error") { if (msg.type === "error") {
console.error("[v0] Error message:", msg.message) terminal.term.writeln(`\x1b[31m${msg.message}\x1b[0m`)
term.writeln(`\x1b[31m${msg.message}\x1b[0m`)
return return
} }
} catch { } catch {
// Not JSON, it's regular terminal output // Not JSON, it's regular terminal output
console.log("[v0] Regular terminal output received")
} }
// Write regular output to terminal terminal.term.write(event.data)
term.write(event.data)
// Hide spinner when output arrives
setIsWaitingNextInteraction(false) setIsWaitingNextInteraction(false)
if (waitingTimeoutRef.current) { if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current) clearTimeout(waitingTimeoutRef.current)
@@ -277,15 +227,13 @@ export function ScriptTerminalModal({
} }
ws.onerror = (error) => { ws.onerror = (error) => {
console.error("[v0] WebSocket error:", error) setTerminal((prev) => ({ ...prev, isConnected: false }))
setIsConnected(false) terminal.term.writeln("\x1b[31mWebSocket error occurred\x1b[0m")
term.writeln("\x1b[31mWebSocket error occurred\x1b[0m")
} }
ws.onclose = (event) => { ws.onclose = (event) => {
console.log("[v0] WebSocket closed:", event.code, event.reason) setTerminal((prev) => ({ ...prev, isConnected: false }))
setIsConnected(false) terminal.term.writeln("\x1b[33mConnection closed\x1b[0m")
term.writeln("\x1b[33mConnection closed\x1b[0m")
if (!isComplete) { if (!isComplete) {
setIsComplete(true) setIsComplete(true)
@@ -295,54 +243,43 @@ export function ScriptTerminalModal({
term.onData((data) => { term.onData((data) => {
if (ws.readyState === WebSocket.OPEN) { if (ws.readyState === WebSocket.OPEN) {
console.log("[v0] Sending user input to WebSocket")
ws.send(data) ws.send(data)
} }
}) })
wsRef.current = ws
// Monitor connection status
checkConnectionInterval.current = setInterval(() => { checkConnectionInterval.current = setInterval(() => {
if (ws) { if (ws) {
setIsConnected(ws.readyState === WebSocket.OPEN) setTerminal((prev) => ({ ...prev, isConnected: ws.readyState === WebSocket.OPEN }))
} }
}, 500) }, 500)
// Setup ResizeObserver for the terminal container
let resizeTimeout: NodeJS.Timeout | null = null let resizeTimeout: NodeJS.Timeout | null = null
const resizeObserver = new ResizeObserver(() => { const resizeObserver = new ResizeObserver(() => {
if (resizeTimeout) { if (resizeTimeout) clearTimeout(resizeTimeout)
clearTimeout(resizeTimeout)
}
resizeTimeout = setTimeout(() => { resizeTimeout = setTimeout(() => {
if (fitAddon && term && ws?.readyState === WebSocket.OPEN) { if (fitAddon && term && ws?.readyState === WebSocket.OPEN) {
try { try {
fitAddon.fit() fitAddon.fit()
const cols = term.cols
const rows = term.rows
console.log("[v0] Terminal resized to:", cols, "x", rows)
ws.send( ws.send(
JSON.stringify({ JSON.stringify({
type: "resize", type: "resize",
cols: cols, cols: term.cols,
rows: rows, rows: term.rows,
}), }),
) )
} catch (err) { } catch (err) {
console.warn("[v0] Resize failed:", err) // Ignore
} }
} }
}, 100) }, 100)
}) })
resizeObserver.observe(node) resizeObserver.observe(container)
} }
initTerminal() initializeTerminal()
} }, [open, terminal.term])
const getScriptWebSocketUrl = (sid: string): string => { const getScriptWebSocketUrl = (sid: string): string => {
if (typeof window === "undefined") { if (typeof window === "undefined") {
@@ -355,7 +292,7 @@ export function ScriptTerminalModal({
} }
const handleInteractionResponse = (value: string) => { const handleInteractionResponse = (value: string) => {
if (!wsRef.current || !currentInteraction) { if (!terminal.ws || !currentInteraction) {
return return
} }
@@ -372,8 +309,8 @@ export function ScriptTerminalModal({
value: value, value: value,
}) })
if (wsRef.current.readyState === WebSocket.OPEN) { if (terminal.ws.readyState === WebSocket.OPEN) {
wsRef.current.send(response) terminal.ws.send(response)
} }
setCurrentInteraction(null) setCurrentInteraction(null)
@@ -385,19 +322,44 @@ export function ScriptTerminalModal({
} }
const handleCloseModal = () => { const handleCloseModal = () => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { if (terminal.ws && terminal.ws.readyState === WebSocket.OPEN) {
wsRef.current.close() terminal.ws.close()
} }
if (checkConnectionInterval.current) { if (checkConnectionInterval.current) {
clearInterval(checkConnectionInterval.current) clearInterval(checkConnectionInterval.current)
} }
if (terminalRef.current) { if (terminal.term) {
terminalRef.current.dispose() terminal.term.dispose()
terminalRef.current = null
} }
onClose() onClose()
} }
const handleResizeStart = (e: React.MouseEvent | React.TouchEvent) => {
setIsResizing(true)
startYRef.current = "clientY" in e ? e.clientY : e.touches[0].clientY
startHeightRef.current = modalHeight
document.addEventListener("mousemove", handleResize as any)
document.addEventListener("touchmove", handleResize as any)
document.addEventListener("mouseup", handleResizeEnd)
document.addEventListener("touchend", handleResizeEnd)
}
const handleResize = (e: MouseEvent | TouchEvent) => {
if (!isResizing) return
const currentY = e instanceof MouseEvent ? e.clientY : e.touches[0].clientY
const deltaY = currentY - startYRef.current
const newHeight = startHeightRef.current + (deltaY / window.innerHeight) * 100
setModalHeight(Math.max(50, Math.min(95, newHeight)))
}
const handleResizeEnd = () => {
setIsResizing(false)
document.removeEventListener("mousemove", handleResize as any)
document.removeEventListener("touchmove", handleResize as any)
document.removeEventListener("mouseup", handleResizeEnd)
document.removeEventListener("touchend", handleResizeEnd)
}
return ( return (
<> <>
<Dialog open={open}> <Dialog open={open}>
@@ -422,7 +384,7 @@ export function ScriptTerminalModal({
</div> </div>
</div> </div>
<div className="overflow-hidden relative" style={{ height: "calc(100% - 120px)" }}> <div className="overflow-hidden relative flex-1">
<div ref={terminalContainerRef} className="w-full h-full" /> <div ref={terminalContainerRef} className="w-full h-full" />
{isWaitingNextInteraction && !currentInteraction && ( {isWaitingNextInteraction && !currentInteraction && (
@@ -451,10 +413,10 @@ export function ScriptTerminalModal({
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Activity className="h-5 w-5 text-blue-500" /> <Activity className="h-5 w-5 text-blue-500" />
<div <div
className={`w-2 h-2 rounded-full ${isConnected ? "bg-green-500" : "bg-red-500"}`} className={`w-2 h-2 rounded-full ${terminal.isConnected ? "bg-green-500" : "bg-red-500"}`}
title={isConnected ? "Connected" : "Disconnected"} title={terminal.isConnected ? "Connected" : "Disconnected"}
></div> ></div>
<span className="text-xs text-muted-foreground">{isConnected ? "Online" : "Offline"}</span> <span className="text-xs text-muted-foreground">{terminal.isConnected ? "Online" : "Offline"}</span>
</div> </div>
<Button <Button