"use client" import { useEffect, useMemo, useState } from "react" import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" type BlueprintOption = { id: string label: string description: string supportsTailscale?: boolean } type WizardStep = "source" | "target" | "options" | "review" | "run" type ControllerPlan = { controller: { name: string url: string host: string dashboardPort: number terminalPort: number installDir: string } env: string commands: { ssh: string localBootstrap: string start: string terminal: string } checks: string[] } const steps: Array<{ key: WizardStep; label: string }> = [ { key: "source", label: "Source" }, { key: "target", label: "Target" }, { key: "options", label: "Options" }, { key: "review", label: "Review" }, { key: "run", label: "Run" }, ] function contentDispositionFileName(value: string | null, fallback: string) { const header = value || "" return decodeURIComponent(header.match(/filename\*=UTF-8''([^;]+)/)?.[1] || "") || header.match(/filename="([^"]+)"/)?.[1] || fallback } function defaultCloneName(source?: SandboxInventoryItem) { if (!source) return "" return `${source.name.replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "")}-clone`.slice(0, 63) } export default function WizardPanel({ sandboxes, onInventoryRefresh, }: { sandboxes: SandboxInventoryItem[] onInventoryRefresh: () => Promise }) { const [activeStep, setActiveStep] = useState("source") const [sourceSandboxId, setSourceSandboxId] = useState("") const [targetName, setTargetName] = useState("") const [blueprints, setBlueprints] = useState([]) const [selectedBlueprint, setSelectedBlueprint] = useState("custom-sandbox") const [enableTailscale, setEnableTailscale] = useState(false) const [backupPath, setBackupPath] = useState("/sandbox") const [restorePath, setRestorePath] = useState("/sandbox") const [replaceTarget, setReplaceTarget] = useState(true) const [running, setRunning] = useState(false) const [message, setMessage] = useState("") const [runLog, setRunLog] = useState([]) const [controllerName, setControllerName] = useState("remote-controller") const [controllerHost, setControllerHost] = useState("") const [sshTarget, setSshTarget] = useState("") const [installDir, setInstallDir] = useState("openshell-control") const [repoUrl, setRepoUrl] = useState("https://github.com/NVIDIA/nemoclaw-dashboard.git") const [dashboardPort, setDashboardPort] = useState("3000") const [terminalPort, setTerminalPort] = useState("3011") const [openClawDashboardUrl, setOpenClawDashboardUrl] = useState("http://127.0.0.1:18789/") const [openshellGateway, setOpenshellGateway] = useState("nemoclaw") const [exposePublicly, setExposePublicly] = useState(false) const [controllerPlan, setControllerPlan] = useState(null) const [controllerMessage, setControllerMessage] = useState("") const [controllerPlanning, setControllerPlanning] = useState(false) const sourceSandbox = useMemo( () => sandboxes.find((sandbox) => sandbox.id === sourceSandboxId) || null, [sandboxes, sourceSandboxId], ) const activeBlueprint = blueprints.find((blueprint) => blueprint.id === selectedBlueprint) const activeIndex = steps.findIndex((step) => step.key === activeStep) useEffect(() => { fetch("/api/sandbox/create", { cache: "no-store" }) .then((response) => response.json()) .then((data) => { if (Array.isArray(data?.blueprints)) setBlueprints(data.blueprints) }) .catch(() => {}) }, []) useEffect(() => { if (!sourceSandboxId && sandboxes[0]) { setSourceSandboxId(sandboxes[0].id) } }, [sandboxes, sourceSandboxId]) useEffect(() => { if (!targetName && sourceSandbox) { setTargetName(defaultCloneName(sourceSandbox)) } }, [sourceSandbox, targetName]) const canContinue = (() => { if (activeStep === "source") return Boolean(sourceSandbox) if (activeStep === "target") return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(targetName) && targetName.length <= 63 if (activeStep === "options") return Boolean(backupPath.trim() && restorePath.trim()) if (activeStep === "review") return Boolean(sourceSandbox && targetName.trim()) return false })() const goNext = () => { const next = steps[activeIndex + 1] if (next) setActiveStep(next.key) } const goBack = () => { const previous = steps[activeIndex - 1] if (previous) setActiveStep(previous.key) } const appendLog = (line: string) => { setRunLog((current) => [...current, line]) } async function runCloneWizard() { if (!sourceSandbox || running) return try { setRunning(true) setMessage("") setRunLog([]) setActiveStep("run") appendLog(`Creating target sandbox ${targetName}...`) const createResponse = await fetch("/api/sandbox/create", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: targetName.trim(), enableTailscale, policy: null, preset: null, }), }) const createData = await createResponse.json() if (!createResponse.ok) { throw new Error([createData.error, createData.verification?.summary, createData.verification?.error, createData.stdout, createData.stderr].filter(Boolean).join("\n\n") || "Failed to create target sandbox") } const createdSandboxId = createData.verification?.details?.id || createData.verification?.details?.name || createData.sandboxName appendLog(`Target sandbox ready: ${createdSandboxId}.`) appendLog(`Backing up ${sourceSandbox.name}:${backupPath.trim()}...`) const backupResponse = await fetch(`/api/sandbox/${encodeURIComponent(sourceSandbox.id)}/backup?${new URLSearchParams({ path: backupPath.trim() })}`) if (!backupResponse.ok) { const data = await backupResponse.json().catch(() => ({})) throw new Error(data.error || "Failed to create source backup") } const backupBlob = await backupResponse.blob() const backupFileName = contentDispositionFileName(backupResponse.headers.get("content-disposition"), `${sourceSandbox.name}-backup.tar.gz`) appendLog(`Backup captured: ${backupFileName} (${Math.ceil(backupBlob.size / 1024)} KiB).`) appendLog(`Restoring backup into ${createdSandboxId}:${restorePath.trim()}...`) const form = new FormData() form.set("archive", new File([backupBlob], backupFileName, { type: "application/gzip" })) form.set("targetPath", restorePath.trim()) form.set("replace", replaceTarget ? "true" : "false") const restoreResponse = await fetch(`/api/sandbox/${encodeURIComponent(createdSandboxId)}/restore`, { method: "POST", body: form, }) const restoreData = await restoreResponse.json() if (!restoreResponse.ok) throw new Error(restoreData.error || "Failed to restore backup into target sandbox") appendLog(restoreData.note || "Restore complete.") appendLog("Refreshing inventory...") await onInventoryRefresh() setMessage(`Clone complete: ${sourceSandbox.name} -> ${targetName.trim()}.`) } catch (error) { const text = error instanceof Error ? error.message : "Clone wizard failed" appendLog(text) setMessage(text) } finally { setRunning(false) } } async function generateControllerPlan() { try { setControllerPlanning(true) setControllerMessage("") setControllerPlan(null) const response = await fetch("/api/controller-node/plan", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ controllerName, controllerHost, sshTarget, installDir, repoUrl, dashboardPort, terminalPort, openClawDashboardUrl, openshellGateway, exposePublicly, }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to generate controller node plan") setControllerPlan(data) setControllerMessage(`Launch kit ready for ${data.controller.url}.`) } catch (error) { setControllerMessage(error instanceof Error ? error.message : "Failed to generate controller node plan") } finally { setControllerPlanning(false) } } async function copyText(value: string, label: string) { try { await navigator.clipboard.writeText(value) setControllerMessage(`${label} copied.`) } catch { setControllerMessage("Clipboard access was blocked. Select the command text manually.") } } return (

Guided Tasks

Wizards

Step-by-step workflows for common operations, including remote controller bootstrap and sandbox cloning.

Spawn a Controller Node

Prepare a remote VPS to run OpenShell Control near another OpenShell gateway or sandbox host.

remote control plane
{controllerMessage &&
{controllerMessage}
}

Topology

Controller VPS: {controllerHost || "not set"}

Sandbox host/gateway: {openshellGateway || "nemoclaw"}

OpenClaw upstream: {openClawDashboardUrl}

{controllerPlan ? (

SSH Bootstrap

{controllerPlan.commands.ssh}

Controller Env

{controllerPlan.env}

Readiness Checks

{controllerPlan.checks.map((check) => (

{check}

))}
) : (
Enter the remote node details to generate a controller bootstrap command and matching environment block.
)}

Clone Sandbox

Create a fresh sandbox, back up the source, then restore into the target.

backup + restore
{steps.map((step, index) => ( ))}
{activeStep === "source" && (

Choose Source Sandbox

This sandbox will be archived from the selected source directory.

{sandboxes.map((sandbox) => ( ))}
{sandboxes.length === 0 && (
No sandboxes are available to clone yet.
)}
)} {activeStep === "target" && (

Configure Target Sandbox

Choose the sandbox blueprint and target name.

{blueprints.map((blueprint) => ( ))}
{activeBlueprint?.supportsTailscale && ( )}
)} {activeStep === "options" && (

Clone Options

Most clones should back up and restore /sandbox.

)} {activeStep === "review" && (

Review Clone Plan

The wizard will run these steps in order.

{[ ["Source", sourceSandbox?.name || "-"], ["Target", targetName || "-"], ["Blueprint", activeBlueprint?.label || selectedBlueprint], ["Backup Path", backupPath], ["Restore Path", restorePath], ["Restore Mode", replaceTarget ? "replace" : "merge"], ].map(([label, value]) => (

{label}

{value}

))}
)} {activeStep === "run" && (

Run Clone

Progress appears here as each operation completes.

{runLog.length === 0 ? (

Ready to clone.

) : (
{runLog.map((line, index) => (

{line}

))}
)}
{message &&
{message}
}
)}
{activeStep === "review" || activeStep === "run" ? ( ) : ( )}
) }