"use client" import { useEffect, useState } from "react" import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" interface SandboxArchivePanelProps { sandbox: SandboxInventoryItem onRestoreComplete?: () => Promise | void } type BackupCatalogEntry = { id: string fileName: string sandboxName: string sourcePath: string size: number createdAt: string } function formatBytes(value: number) { if (value < 1024) return `${value} B` if (value < 1024 * 1024) return `${Math.ceil(value / 1024)} KiB` return `${(value / 1024 / 1024).toFixed(1)} MiB` } 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 [catalogBackups, setCatalogBackups] = useState([]) const [busy, setBusy] = useState<"backup" | "catalog" | "restore" | `restore-${string}` | `delete-${string}` | null>(null) const [message, setMessage] = useState("") async function loadCatalog() { const response = await fetch("/api/backups", { cache: "no-store" }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to load backup catalog") setCatalogBackups(Array.isArray(data.backups) ? data.backups : []) } useEffect(() => { loadCatalog().catch(() => undefined) }, [sandbox.id]) 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 saveCatalogBackup() { if (!backupPath.trim() || busy) return try { setBusy("catalog") setMessage("") const response = await fetch("/api/backups", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sandboxId: sandbox.id, sourcePath: backupPath.trim() }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to save backup to catalog") setMessage(`Saved ${data.backup.fileName} to the local backup catalog.`) await loadCatalog() } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to save backup to catalog") } 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) } } async function restoreCatalogBackup(backupId: string) { if (!restorePath.trim() || busy) return try { setBusy(`restore-${backupId}`) setMessage("") const response = await fetch(`/api/backups/${encodeURIComponent(backupId)}/restore`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sandboxId: sandbox.id, targetPath: restorePath.trim(), replace: restoreReplace }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to restore catalog backup") setMessage(data.note || `Restored catalog backup into ${restorePath.trim()}.`) await onRestoreComplete?.() } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to restore catalog backup") } finally { setBusy(null) } } async function deleteCatalogBackup(backupId: string) { if (busy) return try { setBusy(`delete-${backupId}`) setMessage("") const response = await fetch(`/api/backups/${encodeURIComponent(backupId)}`, { method: "DELETE" }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to delete catalog backup") setMessage("Deleted catalog backup.") await loadCatalog() } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to delete catalog 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)]" />
Backup Catalog

Host-side cold storage for cloning and redeploying sandboxes later.

{catalogBackups.map((backup) => (

{backup.fileName}

{backup.sandboxName} / {backup.sourcePath} / {formatBytes(backup.size)} / {new Date(backup.createdAt).toLocaleString()}

Download
))} {catalogBackups.length === 0 && (
No catalog backups saved yet.
)}
{message && (
{message}
)}
) }