From 7cb929369e631eda82d8bebd7eff3a8cf5a6d87f Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 25 Apr 2026 02:07:26 +0000 Subject: [PATCH] polish sandbox workflows --- app/api/sandbox/[sandboxId]/backup/route.ts | 35 ++ .../sandbox/[sandboxId]/files/list/route.ts | 26 ++ app/api/sandbox/[sandboxId]/restore/route.ts | 32 ++ app/components/ConfigurationPanel.tsx | 23 +- app/components/HelpPanel.tsx | 99 +++++ app/components/SandboxArchivePanel.tsx | 165 ++++++++ app/components/SandboxFilesPanel.tsx | 192 ++++++++- app/components/SandboxList.tsx | 74 ++-- app/components/Sidebar.tsx | 78 ++-- app/components/WizardPanel.tsx | 375 ++++++++++++++++++ app/globals.css | 58 ++- app/lib/sandboxFiles.ts | 119 ++++++ app/page.tsx | 39 +- 13 files changed, 1232 insertions(+), 83 deletions(-) create mode 100644 app/api/sandbox/[sandboxId]/backup/route.ts create mode 100644 app/api/sandbox/[sandboxId]/files/list/route.ts create mode 100644 app/api/sandbox/[sandboxId]/restore/route.ts create mode 100644 app/components/HelpPanel.tsx create mode 100644 app/components/SandboxArchivePanel.tsx create mode 100644 app/components/WizardPanel.tsx diff --git a/app/api/sandbox/[sandboxId]/backup/route.ts b/app/api/sandbox/[sandboxId]/backup/route.ts new file mode 100644 index 0000000..2b7f510 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/backup/route.ts @@ -0,0 +1,35 @@ +import { NextResponse } from "next/server" +import { backupSandboxArchive } from "@/app/lib/sandboxFiles" + +function contentDisposition(fileName: string) { + const fallback = fileName.replace(/[^\w.-]/g, "_") || "sandbox-backup.tar.gz" + return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}` +} + +export async function GET( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const requestUrl = new URL(request.url) + const sourcePath = requestUrl.searchParams.get("path") || "/sandbox" + const backup = await backupSandboxArchive(sandboxId, sourcePath) + + return new NextResponse(new Uint8Array(backup.bytes), { + status: 200, + headers: { + "cache-control": "no-store", + "content-disposition": contentDisposition(backup.fileName), + "content-length": String(backup.bytes.byteLength), + "content-type": "application/gzip", + "x-sandbox-name": backup.sandboxName, + "x-sandbox-path": backup.sourcePath, + "x-sandbox-backup-created-at": backup.createdAt, + }, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to create sandbox backup" + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist|directory/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/files/list/route.ts b/app/api/sandbox/[sandboxId]/files/list/route.ts new file mode 100644 index 0000000..8bf46d7 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/files/list/route.ts @@ -0,0 +1,26 @@ +import { NextResponse } from "next/server" +import { listSandboxFiles } from "@/app/lib/sandboxFiles" + +export async function GET( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const requestUrl = new URL(request.url) + const path = requestUrl.searchParams.get("path") || "/sandbox" + const listing = await listSandboxFiles(sandboxId, path) + + return NextResponse.json({ + ok: true, + listing, + }, { + headers: { + "cache-control": "no-store", + }, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to list sandbox files" + return NextResponse.json({ ok: false, error: message }, { status: /required|path|directory|readable/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/restore/route.ts b/app/api/sandbox/[sandboxId]/restore/route.ts new file mode 100644 index 0000000..9f60711 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/restore/route.ts @@ -0,0 +1,32 @@ +import { NextResponse } from "next/server" +import { restoreSandboxArchive } from "@/app/lib/sandboxFiles" + +export async function POST( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const form = await request.formData() + const file = form.get("archive") + const rawTargetPath = form.get("targetPath") + const rawReplace = form.get("replace") + if (!(file instanceof File)) throw new Error("archive is required") + + const targetPath = typeof rawTargetPath === "string" && rawTargetPath.trim() + ? rawTargetPath.trim() + : "/sandbox" + const replace = rawReplace === "true" || rawReplace === "1" + const payload = Buffer.from(await file.arrayBuffer()) + const restored = await restoreSandboxArchive(sandboxId, targetPath, file.name, payload, replace) + + return NextResponse.json({ + ok: true, + restored, + note: `Restored ${file.name} into ${restored.targetPath} (${restored.mode}).`, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to restore sandbox backup" + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|unsafe|archive/.test(message) ? 400 : 500 }) + } +} diff --git a/app/components/ConfigurationPanel.tsx b/app/components/ConfigurationPanel.tsx index fc73bf1..731f380 100644 --- a/app/components/ConfigurationPanel.tsx +++ b/app/components/ConfigurationPanel.tsx @@ -87,6 +87,10 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre const [selectedBlueprint, setSelectedBlueprint] = useState('nemoclaw-blueprint') const [sandboxName, setSandboxName] = useState('') const [enableTailscale, setEnableTailscale] = useState(false) + const [restoreFromBackup, setRestoreFromBackup] = useState(false) + const [restoreArchive, setRestoreArchive] = useState(null) + const [restorePath, setRestorePath] = useState('/sandbox') + const [restoreReplace, setRestoreReplace] = useState(true) useEffect(() => { if (mode === 'create') { @@ -129,12 +133,29 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre setSaving(true); setMessage("") if (mode === 'create') { if (!sandboxName.trim()) throw new Error('sandbox name is required') + if (restoreFromBackup && !restoreArchive) throw new Error('backup archive is required when restore from backup is enabled') const res = await fetch('/api/sandbox/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: sandboxName.trim(), enableTailscale, policy: assembledPolicy, preset: selectedPreset || null }) }) const data = await res.json() if (!res.ok) throw new Error([data.error, data.verification?.summary, data.verification?.error, data.stdout, data.stderr].filter(Boolean).join('\n\n')) const createdSandboxId = data.verification?.details?.id || data.verification?.details?.name || data.sandboxName + let restoreNote = '' + if (restoreFromBackup && restoreArchive && createdSandboxId) { + setMessage(`Sandbox '${data.sandboxName}' created. Restoring backup archive...`) + const form = new FormData() + form.set('archive', restoreArchive) + form.set('targetPath', restorePath.trim() || '/sandbox') + form.set('replace', restoreReplace ? 'true' : 'false') + const restoreRes = await fetch(`/api/sandbox/${encodeURIComponent(createdSandboxId)}/restore`, { + method: 'POST', + body: form, + }) + const restoreData = await restoreRes.json() + if (!restoreRes.ok) throw new Error([`Sandbox '${data.sandboxName}' was created, but backup restore failed.`, restoreData.error].filter(Boolean).join('\n\n')) + restoreNote = restoreData.note || `Restored ${restoreArchive.name} into ${restorePath.trim() || '/sandbox'}.` + } setMessage([ `Sandbox '${data.sandboxName}' created.`, + restoreNote, data.verification?.summary, data.note, ].filter(Boolean).join('\n\n')) @@ -167,7 +188,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre )} {loading ?
Loading policy…
:
- {mode === 'create' &&
Create Sandbox

Choose a template and enter a sandbox name.

{blueprints.map((bp) => )}
setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
{activeBlueprint?.supportsTailscale && }{enableTailscale &&
Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.
}
} + {mode === 'create' &&
Create Sandbox

Choose a template and enter a sandbox name.

{blueprints.map((bp) => )}
setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
{activeBlueprint?.supportsTailscale && }{enableTailscale &&
Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.
}
{restoreFromBackup &&
setRestoreArchive(e.target.files?.[0] || null)} className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background-tertiary)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" />
setRestorePath(e.target.value)} placeholder="/sandbox" className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
}
}
Security Presets

Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.

{activePreset &&
{activePreset.label}

{activePreset.summary}

}
Filesystem Policy
Static
setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /> setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" />
Network Policies
Dynamic
diff --git a/app/components/HelpPanel.tsx b/app/components/HelpPanel.tsx new file mode 100644 index 0000000..aeefe41 --- /dev/null +++ b/app/components/HelpPanel.tsx @@ -0,0 +1,99 @@ +"use client" + +const helpSections = [ + { + title: "Daily Flow", + items: [ + "Select a sandbox to reveal operations, file transfer, inference routes, policy, and archive tools.", + "Use Operator Terminal after selecting a sandbox; the terminal opens in a separate tab for that sandbox session.", + "Use Refresh Inventory when a create, restore, restart, or destroy operation is still settling.", + ], + }, + { + title: "Create And Clone", + items: [ + "Create Sandbox builds a new sandbox from a blueprint or custom OpenShell sandbox template.", + "Restore from Backup can hydrate a fresh sandbox immediately after it reaches Ready.", + "Wizards includes a guided Clone Sandbox workflow that creates a target sandbox and restores a source backup into it.", + "For cloning, keep Replace target contents enabled and restore into /sandbox.", + ], + }, + { + title: "Files", + items: [ + "File Transfer uploads local files into /sandbox or /tmp and downloads regular files back out.", + "The file browser lists one directory at a time; select a directory to enter it or use Up to move back.", + "Large file transfers are limited by SANDBOX_FILE_TRANSFER_MAX_BYTES, currently defaulting to 128 MiB.", + ], + }, + { + title: "Backup / Restore", + items: [ + "Backup downloads a compressed .tar.gz archive from a sandbox directory, usually /sandbox.", + "Restore extracts a .tar.gz archive into the selected sandbox path.", + "Replace target contents deletes existing files in the target directory before extraction; merge leaves existing files in place.", + ], + }, + { + title: "Policy And Network", + items: [ + "Sandbox Policy is where pending network permission requests appear for approval or rejection.", + "Dynamic network policy changes can apply live; static filesystem policy changes may require recreating the sandbox.", + "Inference Routes configure model/provider routing for the selected sandbox.", + ], + }, + { + title: "Safety", + items: [ + "Destroy Sandbox is permanent. Back up anything important first.", + "Restore rejects unsafe archive paths, but only restore archives you trust.", + "If the UI looks stale after code changes, hard refresh the browser; the dev server is on 192.168.50.81:3000.", + ], + }, +] + +export default function HelpPanel() { + return ( +
+
+

Operator Guide

+

Help

+

+ Quick reference for running sandboxes, moving files, preserving work, and cloning a prepared environment. +

+
+ +
+ {helpSections.map((section) => ( +
+

{section.title}

+
    + {section.items.map((item) => ( +
  • + + {item} +
  • + ))} +
+
+ ))} +
+ +
+

Common Paths

+
+ {[ + ["/sandbox", "Primary writable workspace for persisted sandbox contents."], + ["/tmp", "Scratch space for short-lived files and transfer staging."], + ["Backup .tar.gz", "Portable archive for cold storage, cloning, and redeploying."], + ].map(([label, body]) => ( +
+

{label}

+

{body}

+
+ ))} +
+
+
+ ) +} diff --git a/app/components/SandboxArchivePanel.tsx b/app/components/SandboxArchivePanel.tsx new file mode 100644 index 0000000..e4268b4 --- /dev/null +++ b/app/components/SandboxArchivePanel.tsx @@ -0,0 +1,165 @@ +"use client" + +import { useState } from "react" +import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" + +interface SandboxArchivePanelProps { + sandbox: SandboxInventoryItem + onRestoreComplete?: () => Promise | void +} + +export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: SandboxArchivePanelProps) { + const [backupPath, setBackupPath] = useState("/sandbox") + const [restorePath, setRestorePath] = useState("/sandbox") + const [restoreReplace, setRestoreReplace] = useState(false) + const [selectedArchive, setSelectedArchive] = useState(null) + const [busy, setBusy] = useState<"backup" | "restore" | null>(null) + const [message, setMessage] = useState("") + + async function backupSandbox() { + if (!backupPath.trim() || busy) return + try { + setBusy("backup") + setMessage("") + const pathToBackup = backupPath.trim() + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/backup?${new URLSearchParams({ path: pathToBackup })}`) + if (!response.ok) { + const data = await response.json().catch(() => ({})) + throw new Error(data.error || "Failed to create sandbox backup") + } + + const blob = await response.blob() + const contentDisposition = response.headers.get("content-disposition") || "" + const fileName = decodeURIComponent(contentDisposition.match(/filename\*=UTF-8''([^;]+)/)?.[1] || "") + || contentDisposition.match(/filename="([^"]+)"/)?.[1] + || `${sandbox.name}-backup.tar.gz` + const url = window.URL.createObjectURL(blob) + const anchor = document.createElement("a") + anchor.href = url + anchor.download = fileName + document.body.appendChild(anchor) + anchor.click() + anchor.remove() + window.URL.revokeObjectURL(url) + setMessage(`Created backup for ${pathToBackup}: ${fileName}.`) + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to create sandbox backup") + } finally { + setBusy(null) + } + } + + async function restoreSandbox() { + if (!selectedArchive || !restorePath.trim() || busy) return + try { + setBusy("restore") + setMessage("") + const form = new FormData() + form.set("archive", selectedArchive) + form.set("targetPath", restorePath.trim()) + form.set("replace", restoreReplace ? "true" : "false") + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/restore`, { + method: "POST", + body: form, + }) + const data = await response.json() + if (!response.ok) throw new Error(data.error || "Failed to restore sandbox backup") + setMessage(data.note || `Restored ${selectedArchive.name} into ${restorePath.trim()}.`) + await onRestoreComplete?.() + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to restore sandbox backup") + } finally { + setBusy(null) + } + } + + return ( +
+
+
+
Backup / Restore
+

+ Export sandbox contents as a compressed archive, or restore an archive into this sandbox. +

+
+ + tar.gz + +
+ +
+
+
+
Backup
+

Archive a directory for cold storage or cloning.

+
+ + +
+ +
+
+
Restore
+

Merge into the target directory, or replace it first.

+
+ setSelectedArchive(event.target.files?.[0] || null)} + className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background-tertiary)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" + /> + + + +
+
+ + {message && ( +
+ {message} +
+ )} +
+ ) +} diff --git a/app/components/SandboxFilesPanel.tsx b/app/components/SandboxFilesPanel.tsx index 71aafcd..33d6d92 100644 --- a/app/components/SandboxFilesPanel.tsx +++ b/app/components/SandboxFilesPanel.tsx @@ -1,8 +1,42 @@ "use client" -import { useMemo, useState } from "react" +import { useEffect, useMemo, useState } from "react" import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" +type SandboxFileEntry = { + name: string + path: string + type: "file" | "directory" | "symlink" | "other" + size: number | null + modifiedAt: string | null +} + +type SandboxFileListing = { + path: string + entries: SandboxFileEntry[] + truncated: boolean +} + +function formatBytes(bytes: number | null) { + if (bytes === null) return "-" + if (bytes < 1024) return `${bytes} B` + const units = ["KiB", "MiB", "GiB"] + let value = bytes / 1024 + let unitIndex = 0 + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024 + unitIndex += 1 + } + return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unitIndex]}` +} + +function parentPath(currentPath: string) { + const trimmed = currentPath.replace(/\/+$/, "") + if (trimmed === "/sandbox" || trimmed === "/tmp") return trimmed + const parent = trimmed.split("/").slice(0, -1).join("/") || "/sandbox" + return parent === "" ? "/sandbox" : parent +} + export default function SandboxFilesPanel({ sandbox, embedded = false, @@ -16,6 +50,9 @@ export default function SandboxFilesPanel({ const [uploadPath, setUploadPath] = useState("/sandbox/") const [downloadPath, setDownloadPath] = useState("/sandbox/") const [busy, setBusy] = useState<"upload" | "download" | null>(null) + const [listPath, setListPath] = useState("/sandbox") + const [listing, setListing] = useState(null) + const [listingBusy, setListingBusy] = useState(false) const [message, setMessage] = useState("") const suggestedUploadPath = useMemo(() => { @@ -23,6 +60,44 @@ export default function SandboxFilesPanel({ return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath }, [selectedFile, uploadPath]) + const sortedEntries = useMemo(() => { + return [...(listing?.entries || [])].sort((left, right) => { + if (left.type === "directory" && right.type !== "directory") return -1 + if (left.type !== "directory" && right.type === "directory") return 1 + return left.name.localeCompare(right.name) + }) + }, [listing]) + + async function loadFileList(nextPath = listPath) { + if (listingBusy) return + try { + setListingBusy(true) + setMessage("") + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/list?${new URLSearchParams({ path: nextPath.trim() || "/sandbox" })}`, { + cache: "no-store", + }) + const data = await response.json() + if (!response.ok) throw new Error(data.error || "Failed to list sandbox files") + setListing(data.listing) + setListPath(data.listing.path) + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to list sandbox files") + } finally { + setListingBusy(false) + } + } + + useEffect(() => { + setListPath("/sandbox") + setDownloadPath("/sandbox/") + setListing(null) + }, [sandbox.id]) + + useEffect(() => { + loadFileList("/sandbox") + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sandbox.id]) + async function uploadFile() { if (!selectedFile || busy) return try { @@ -39,6 +114,7 @@ export default function SandboxFilesPanel({ if (!response.ok) throw new Error(data.error || "Failed to upload file") setMessage(data.note || `Uploaded to ${data.uploaded?.path || suggestedUploadPath}.`) setDownloadPath(data.uploaded?.path || suggestedUploadPath) + await loadFileList(listPath) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to upload file") } finally { @@ -46,12 +122,13 @@ export default function SandboxFilesPanel({ } } - async function downloadFile() { - if (!downloadPath.trim() || busy) return + async function downloadFile(pathOverride?: string) { + const pathToDownload = (pathOverride || downloadPath).trim() + if (!pathToDownload || busy) return try { setBusy("download") setMessage("") - const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/download?${new URLSearchParams({ path: downloadPath.trim() })}`) + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/download?${new URLSearchParams({ path: pathToDownload })}`) if (!response.ok) { const data = await response.json().catch(() => ({})) throw new Error(data.error || "Failed to download file") @@ -61,7 +138,7 @@ export default function SandboxFilesPanel({ const contentDisposition = response.headers.get("content-disposition") || "" const fileName = decodeURIComponent(contentDisposition.match(/filename\*=UTF-8''([^;]+)/)?.[1] || "") || contentDisposition.match(/filename="([^"]+)"/)?.[1] - || downloadPath.split("/").filter(Boolean).pop() + || pathToDownload.split("/").filter(Boolean).pop() || "download.bin" const url = window.URL.createObjectURL(blob) const anchor = document.createElement("a") @@ -71,7 +148,7 @@ export default function SandboxFilesPanel({ anchor.click() anchor.remove() window.URL.revokeObjectURL(url) - setMessage(`Downloaded ${downloadPath.trim()}.`) + setMessage(`Downloaded ${pathToDownload}.`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to download file") } finally { @@ -79,6 +156,15 @@ export default function SandboxFilesPanel({ } } + const openEntry = (entry: SandboxFileEntry) => { + if (entry.type === "directory") { + setListPath(entry.path) + loadFileList(entry.path) + return + } + setDownloadPath(entry.path) + } + return (
{showHeader && ( @@ -94,7 +180,7 @@ export default function SandboxFilesPanel({
)} -
+
Upload
@@ -120,7 +206,7 @@ export default function SandboxFilesPanel({ @@ -129,8 +215,92 @@ export default function SandboxFilesPanel({
Download
-

Enter a regular file path under /sandbox or /tmp.

+

Browse sandbox files or enter a regular file path under /sandbox or /tmp.

+
+ setListPath(event.target.value)} + placeholder="/sandbox" + className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" + /> + + +
+
+
+ Name + Size + Modified + Action +
+
+ {listingBusy ? ( +
+ Reading sandbox directory... +
+ ) : sortedEntries.length === 0 ? ( +
+ {listing ? "No files found in this directory." : "File list has not loaded yet."} +
+ ) : ( + sortedEntries.map((entry) => ( +
+ + {entry.type === "directory" ? "dir" : formatBytes(entry.size)} + + {entry.modifiedAt ? new Date(entry.modifiedAt).toLocaleDateString() : "-"} + + +
+ )) + )} +
+
+ {listing?.truncated && ( +

+ Showing the first 200 entries. Narrow the path to see more. +

+ )}
diff --git a/app/components/SandboxList.tsx b/app/components/SandboxList.tsx index 2460460..65e1f63 100644 --- a/app/components/SandboxList.tsx +++ b/app/components/SandboxList.tsx @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import type { ReactNode } from 'react' import ConfigurationPanel from './ConfigurationPanel' +import SandboxArchivePanel from './SandboxArchivePanel' import SandboxFilesPanel from './SandboxFilesPanel' import SandboxInferencePanel from './SandboxInferencePanel' import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory' @@ -26,7 +27,7 @@ interface SandboxListProps { onInventoryRefresh: () => Promise } -type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' +type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' | 'archive' type NetworkRuleRequest = { chunkId: string status: string @@ -121,6 +122,7 @@ export default function SandboxList({ files: false, inference: false, policy: false, + archive: false, }) const [telemetry, setTelemetry] = useState({ cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString() @@ -232,29 +234,34 @@ export default function SandboxList({
) : ( <> -
-

- {isDestroyMode ? 'SELECT SANDBOX TO DESTROY' : 'ACTIVE SANDBOXES'} -

- - REFRESH: 10s +
+
+

+ Inventory +

+

+ {isDestroyMode ? 'SELECT SANDBOX TO DESTROY' : 'ACTIVE SANDBOXES'} +

+
+ + REFRESH 10s
-
+
{sandboxes.map((sandbox) => (
- -
+
setTargetName(event.target.value)} + placeholder="source-clone" + className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" + /> + + {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" ? ( + + ) : ( + + )} +
+
+
+ ) +} diff --git a/app/globals.css b/app/globals.css index 31f351b..a768715 100644 --- a/app/globals.css +++ b/app/globals.css @@ -32,6 +32,10 @@ /* Data visualization */ --metric-bg: #161616; --metric-border: #2a2a2a; + --surface-raised: rgba(30, 30, 30, 0.86); + --surface-hover: rgba(118, 185, 0, 0.08); + --shadow-soft: 0 18px 60px rgba(0, 0, 0, 0.34); + --shadow-glow: 0 0 0 1px rgba(118, 185, 0, 0.22), 0 18px 60px rgba(118, 185, 0, 0.12); } html[data-theme="light"] { @@ -46,17 +50,34 @@ html[data-theme="light"] { --border-medium: #a3a3a3; --metric-bg: #fafafa; --metric-border: #e5e5e5; + --surface-raised: rgba(255, 255, 255, 0.92); + --surface-hover: rgba(93, 150, 0, 0.08); + --shadow-soft: 0 18px 46px rgba(23, 23, 23, 0.08); + --shadow-glow: 0 0 0 1px rgba(93, 150, 0, 0.22), 0 18px 46px rgba(93, 150, 0, 0.12); } body { margin: 0; color: var(--foreground); - background: var(--background); + background: + radial-gradient(circle at 70% 0%, rgba(118, 185, 0, 0.13), transparent 28rem), + linear-gradient(180deg, var(--background-secondary), var(--background) 18rem); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } +* { + scrollbar-color: var(--border-medium) transparent; +} + +button, +a, +select, +input { + outline-color: var(--nvidia-green); +} + @layer utilities { .text-balance { text-wrap: balance; @@ -102,9 +123,11 @@ body { /* Panel styling - technical data panels */ .panel { - background: var(--background-panel); + background: var(--surface-raised); border: 1px solid var(--border-subtle); border-radius: 4px; + box-shadow: var(--shadow-soft); + backdrop-filter: blur(14px); } /* Metric display - data-dense */ @@ -113,4 +136,35 @@ body { border: 1px solid var(--metric-border); border-radius: 3px; } + + .action-button { + border: 1px solid var(--border-subtle); + border-radius: 4px; + background: var(--background-tertiary); + color: var(--foreground); + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 0.75rem; + letter-spacing: 0.05em; + text-transform: uppercase; + transition: border-color 150ms ease, background-color 150ms ease, color 150ms ease, transform 150ms ease; + } + + .action-button:hover:not(:disabled) { + border-color: var(--nvidia-green); + background: var(--surface-hover); + transform: translateY(-1px); + } + + .action-button:disabled { + cursor: not-allowed; + opacity: 0.5; + } + + .status-chip { + border-radius: 999px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 0.625rem; + letter-spacing: 0.05em; + text-transform: uppercase; + } } diff --git a/app/lib/sandboxFiles.ts b/app/lib/sandboxFiles.ts index e963a4d..1862755 100644 --- a/app/lib/sandboxFiles.ts +++ b/app/lib/sandboxFiles.ts @@ -16,6 +16,7 @@ const HOST_PATH = [ const MAX_FILE_BYTES = Number.parseInt(process.env.SANDBOX_FILE_TRANSFER_MAX_BYTES || String(128 * 1024 * 1024), 10) const ALLOWED_ROOTS = ["/sandbox", "/tmp"] +const MAX_LIST_ENTRIES = Number.parseInt(process.env.SANDBOX_FILE_LIST_MAX_ENTRIES || "200", 10) function shellQuote(value: string) { return `'${value.replace(/'/g, `'\\''`)}'` @@ -26,6 +27,10 @@ function sanitizeFileName(value: string) { return base.replace(/[^\w.@:+-]/g, "_") || "upload.bin" } +function sanitizeArchiveStem(value: string) { + return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "sandbox" +} + export function normalizeSandboxPath(input: string, fallbackFileName?: string) { const raw = input.trim() if (!raw) throw new Error("sandbox path is required") @@ -123,3 +128,117 @@ export async function downloadSandboxFile(sandboxId: string, sourcePath: string) bytes: result.stdout, } } + +export type SandboxFileListEntry = { + name: string + path: string + type: "file" | "directory" | "symlink" | "other" + size: number | null + modifiedAt: string | null +} + +function normalizeFindType(type: string): SandboxFileListEntry["type"] { + if (type === "f") return "file" + if (type === "d") return "directory" + if (type === "l") return "symlink" + return "other" +} + +export async function listSandboxFiles(sandboxId: string, directoryPath: string) { + const sandboxName = await resolveSandboxName(sandboxId) + const targetPath = normalizeSandboxPath(directoryPath || "/sandbox") + const script = [ + `test -d ${shellQuote(targetPath)}`, + `find ${shellQuote(targetPath)} -mindepth 1 -maxdepth 1 -printf '%y\\t%s\\t%T@\\t%p\\n' | sort -k4 | head -n ${MAX_LIST_ENTRIES}`, + ].join(" && ") + const result = await runSandboxExec(sandboxName, script, undefined, 30000) + if (result.code !== 0) throw new Error(result.stderr || "sandbox directory does not exist or is not readable") + + const entries = result.stdout + .toString("utf8") + .split("\n") + .map((line) => line.trimEnd()) + .filter(Boolean) + .map((line): SandboxFileListEntry | null => { + const [type, sizeValue, modifiedValue, ...pathParts] = line.split("\t") + const entryPath = pathParts.join("\t") + if (!entryPath) return null + const modifiedSeconds = Number.parseFloat(modifiedValue) + return { + name: path.posix.basename(entryPath), + path: entryPath, + type: normalizeFindType(type), + size: Number.isFinite(Number.parseInt(sizeValue, 10)) ? Number.parseInt(sizeValue, 10) : null, + modifiedAt: Number.isFinite(modifiedSeconds) ? new Date(modifiedSeconds * 1000).toISOString() : null, + } + }) + .filter((entry): entry is SandboxFileListEntry => Boolean(entry)) + + return { + sandboxName, + path: targetPath, + entries, + truncated: entries.length >= MAX_LIST_ENTRIES, + } +} + +export async function backupSandboxArchive(sandboxId: string, sourcePath: string) { + const sandboxName = await resolveSandboxName(sandboxId) + const targetPath = normalizeSandboxPath(sourcePath || "/sandbox") + const timestamp = new Date().toISOString() + const archiveName = `${sanitizeArchiveStem(sandboxName)}-${timestamp.replace(/[:.]/g, "-")}.tar.gz` + const script = [ + `test -d ${shellQuote(targetPath)}`, + `tar -C ${shellQuote(targetPath)} -czf - .`, + ].join(" && ") + const result = await runSandboxExec(sandboxName, script, undefined, 120000) + if (result.code !== 0) throw new Error(result.stderr || "failed to create sandbox backup archive") + if (result.stdout.byteLength > MAX_FILE_BYTES) { + throw new Error(`backup archive is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`) + } + + return { + sandboxName, + sourcePath: targetPath, + fileName: archiveName, + bytes: result.stdout, + createdAt: timestamp, + } +} + +export async function restoreSandboxArchive( + sandboxId: string, + targetPathInput: string, + archiveName: string, + payload: Buffer, + replace: boolean +) { + if (payload.byteLength > MAX_FILE_BYTES) { + throw new Error(`archive is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`) + } + + const sandboxName = await resolveSandboxName(sandboxId) + const targetPath = normalizeSandboxPath(targetPathInput || "/sandbox") + const safeArchiveName = sanitizeFileName(archiveName || "sandbox-backup.tar.gz") + const script = [ + `tmp_archive="$(mktemp /tmp/openshell-restore.XXXXXX.tar.gz)"`, + `cat > "$tmp_archive"`, + `tar -tzf "$tmp_archive" >/tmp/openshell-restore-list.$$`, + `while IFS= read -r entry; do case "$entry" in ""|/*|../*|*/../*|*"/..") rm -f "$tmp_archive" /tmp/openshell-restore-list.$$; exit 42;; esac; done < /tmp/openshell-restore-list.$$`, + `mkdir -p ${shellQuote(targetPath)}`, + replace ? `find ${shellQuote(targetPath)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {} +` : `:`, + `if grep -q '^payload/' /tmp/openshell-restore-list.$$; then tar -xzf "$tmp_archive" -C ${shellQuote(targetPath)} --strip-components=1 --wildcards 'payload/*'; else tar -xzf "$tmp_archive" -C ${shellQuote(targetPath)}; fi`, + `rm -f "$tmp_archive" /tmp/openshell-restore-list.$$`, + ].join(" && ") + const result = await runSandboxExec(sandboxName, script, payload, 120000) + if (result.code === 42) throw new Error("archive contains unsafe paths") + if (result.code !== 0) throw new Error(result.stderr || "failed to restore sandbox archive") + + return { + sandboxName, + archiveName: safeArchiveName, + targetPath, + bytes: payload.byteLength, + mode: replace ? "replace" : "merge", + } +} diff --git a/app/page.tsx b/app/page.tsx index 604df05..f266996 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -4,6 +4,8 @@ import Sidebar from './components/Sidebar' import SandboxList from './components/SandboxList' import ConfigurationPanel from './components/ConfigurationPanel' import InferenceEndpointPanel from './components/InferenceEndpointPanel' +import HelpPanel from './components/HelpPanel' +import WizardPanel from './components/WizardPanel' import { useSandboxInventory } from './hooks/useSandboxInventory' import { createHydrationSafeDashboardSessionState, @@ -18,12 +20,12 @@ export default function Dashboard() { const [dashboardSession, setDashboardSession] = useState(() => createHydrationSafeDashboardSessionState()) const [isCreateMode, setIsCreateMode] = useState(false) const [isDestroyMode, setIsDestroyMode] = useState(false) - const [activeView, setActiveView] = useState<'settings' | 'sandboxes'>('sandboxes') + const [activeView, setActiveView] = useState<'settings' | 'sandboxes' | 'help' | 'wizards'>('sandboxes') const [deletingSandboxId, setDeletingSandboxId] = useState(null) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) const [lifecycleMessage, setLifecycleMessage] = useState(null) const [deleteInProgress, setDeleteInProgress] = useState(false) - const inventoryEnabled = activeView === 'sandboxes' || isCreateMode || isDestroyMode + const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || isCreateMode || isDestroyMode const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ enabled: inventoryEnabled, }) @@ -202,6 +204,18 @@ export default function Dashboard() { setIsDestroyMode(false) clearSelection() }} + onWizardsClick={() => { + setActiveView('wizards') + setIsCreateMode(false) + setIsDestroyMode(false) + clearSelection() + }} + onHelpClick={() => { + setActiveView('help') + setIsCreateMode(false) + setIsDestroyMode(false) + clearSelection() + }} onExitMode={() => { setIsCreateMode(false) setIsDestroyMode(false) @@ -213,9 +227,9 @@ export default function Dashboard() { }} /> -
+
-
+
{activeView === 'settings' ? (
@@ -239,6 +253,10 @@ export default function Dashboard() {
+ ) : activeView === 'help' ? ( + + ) : activeView === 'wizards' ? ( + ) : isCreateMode ? (
@@ -304,9 +322,12 @@ export default function Dashboard() {
) : ( <> -
-
-

+
+
+

+ {sandboxes.filter((sandbox) => sandbox.status === 'running').length} online / {sandboxes.length} total +

+

OPENSHELL CONTROL

@@ -315,7 +336,7 @@ export default function Dashboard() {

@@ -367,7 +388,7 @@ export default function Dashboard() { {showDeleteConfirm && (
-
+