"use client" 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, showHeader = true, }: { sandbox: SandboxInventoryItem embedded?: boolean showHeader?: boolean }) { const [selectedFile, setSelectedFile] = useState(null) const [selectedDirectoryFiles, setSelectedDirectoryFiles] = useState([]) const [uploadMode, setUploadMode] = useState<"file" | "directory">("file") 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(() => { if (!selectedFile) return uploadPath return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath }, [selectedFile, uploadPath]) const uploadCount = uploadMode === "directory" ? selectedDirectoryFiles.length : selectedFile ? 1 : 0 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 (uploadCount === 0 || busy) return try { setBusy("upload") setMessage("") const form = new FormData() form.set("path", uploadPath) if (uploadMode === "directory") { form.set("relativePaths", JSON.stringify(selectedDirectoryFiles.map((file) => file.webkitRelativePath || file.name))) for (const file of selectedDirectoryFiles) { form.append("files", file, file.name) } } else if (selectedFile) { form.set("file", selectedFile) } const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/upload`, { method: "POST", body: form, }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to upload file") setMessage(data.note || "Upload complete.") if (uploadMode === "directory") { setDownloadPath(uploadPath) } else { setDownloadPath(data.uploaded?.path || suggestedUploadPath) } await loadFileList(listPath) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to upload file") } finally { setBusy(null) } } 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: pathToDownload })}`) if (!response.ok) { const data = await response.json().catch(() => ({})) throw new Error(data.error || "Failed to download file") } 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] || pathToDownload.split("/").filter(Boolean).pop() || "download.bin" 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(`Downloaded ${pathToDownload}.`) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to download file") } finally { setBusy(null) } } const openEntry = (entry: SandboxFileEntry) => { if (entry.type === "directory") { setListPath(entry.path) loadFileList(entry.path) return } setDownloadPath(entry.path) } return (
{showHeader && (

{sandbox.name} - FILE TRANSFER

Move files through scoped sandbox paths.

)}
Upload

Destination must be under /sandbox or /tmp.

{ setUploadMode("file") setSelectedFile(event.target.files?.[0] || null) setSelectedDirectoryFiles([]) }} 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)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" /> )} onChange={(event) => { setUploadMode("directory") setSelectedDirectoryFiles(Array.from(event.target.files || [])) setSelectedFile(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)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" />
setUploadPath(event.target.value)} placeholder="/sandbox/file.txt" 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)]" /> {selectedFile && (

Target: {suggestedUploadPath}

)} {uploadMode === "directory" && selectedDirectoryFiles.length > 0 && (

Directory upload: {selectedDirectoryFiles.length} file{selectedDirectoryFiles.length === 1 ? "" : "s"} into {uploadPath}

)}
Download

Browse sandbox files or enter a file or directory 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.

)}
setDownloadPath(event.target.value)} placeholder="/sandbox/file.txt" 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)]" />
{message && (
{message}
)}
) }