diff --git a/app/api/activity/route.ts b/app/api/activity/route.ts new file mode 100644 index 0000000..4973b82 --- /dev/null +++ b/app/api/activity/route.ts @@ -0,0 +1,9 @@ +import { NextResponse } from "next/server" +import { listActivity } from "@/app/lib/activityLog" + +export async function GET(request: Request) { + const requestUrl = new URL(request.url) + const limit = Number.parseInt(requestUrl.searchParams.get("limit") || "100", 10) + const entries = await listActivity(Number.isFinite(limit) ? limit : 100) + return NextResponse.json({ ok: true, entries }) +} diff --git a/app/api/backups/[backupId]/download/route.ts b/app/api/backups/[backupId]/download/route.ts new file mode 100644 index 0000000..b50279f --- /dev/null +++ b/app/api/backups/[backupId]/download/route.ts @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server" +import { getCatalogBackup } from "@/app/lib/backupCatalog" + +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<{ backupId: string }> }, +) { + try { + const { backupId } = await params + const backup = await getCatalogBackup(backupId) + return new NextResponse(new Uint8Array(backup.bytes), { + status: 200, + headers: { + "cache-control": "no-store", + "content-disposition": contentDisposition(backup.metadata.fileName), + "content-length": String(backup.bytes.byteLength), + "content-type": "application/gzip", + }, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to download backup" + return NextResponse.json({ ok: false, error: message }, { status: 404 }) + } +} diff --git a/app/api/backups/[backupId]/restore/route.ts b/app/api/backups/[backupId]/restore/route.ts new file mode 100644 index 0000000..5eacbf7 --- /dev/null +++ b/app/api/backups/[backupId]/restore/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server" +import { restoreCatalogBackup } from "@/app/lib/backupCatalog" +import { recordActivity } from "@/app/lib/activityLog" + +export async function POST( + request: Request, + { params }: { params: Promise<{ backupId: string }> }, +) { + try { + const { backupId } = await params + const body = await request.json() + const sandboxId = typeof body?.sandboxId === "string" ? body.sandboxId.trim() : "" + const targetPath = typeof body?.targetPath === "string" && body.targetPath.trim() ? body.targetPath.trim() : "/sandbox" + const replace = body?.replace === true + if (!sandboxId) throw new Error("sandboxId is required") + + const restored = await restoreCatalogBackup(backupId, sandboxId, targetPath, replace) + await recordActivity({ + type: "backup.catalog.restore", + status: "success", + sandboxId, + sandboxName: restored.sandboxName, + message: `Restored catalog backup into ${restored.targetPath}.`, + metadata: { backupId, targetPath: restored.targetPath, mode: restored.mode, bytes: restored.bytes }, + }) + + return NextResponse.json({ ok: true, restored, note: `Restored catalog backup into ${restored.targetPath} (${restored.mode}).` }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to restore catalog backup" + await recordActivity({ + type: "backup.catalog.restore", + status: "error", + message, + }).catch(() => undefined) + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|unsafe|archive/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/backups/[backupId]/route.ts b/app/api/backups/[backupId]/route.ts new file mode 100644 index 0000000..1e65953 --- /dev/null +++ b/app/api/backups/[backupId]/route.ts @@ -0,0 +1,23 @@ +import { NextResponse } from "next/server" +import { deleteCatalogBackup } from "@/app/lib/backupCatalog" +import { recordActivity } from "@/app/lib/activityLog" + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ backupId: string }> }, +) { + try { + const { backupId } = await params + await deleteCatalogBackup(backupId) + await recordActivity({ + type: "backup.catalog.delete", + status: "success", + message: `Deleted catalog backup ${backupId}.`, + metadata: { backupId }, + }) + return NextResponse.json({ ok: true }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to delete backup" + return NextResponse.json({ ok: false, error: message }, { status: 500 }) + } +} diff --git a/app/api/backups/route.ts b/app/api/backups/route.ts new file mode 100644 index 0000000..f207f18 --- /dev/null +++ b/app/api/backups/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server" +import { createCatalogBackup, listBackupCatalog } from "@/app/lib/backupCatalog" +import { recordActivity } from "@/app/lib/activityLog" + +export async function GET() { + const backups = await listBackupCatalog() + return NextResponse.json({ ok: true, backups }) +} + +export async function POST(request: Request) { + try { + const body = await request.json() + const sandboxId = typeof body?.sandboxId === "string" ? body.sandboxId.trim() : "" + const sourcePath = typeof body?.sourcePath === "string" && body.sourcePath.trim() ? body.sourcePath.trim() : "/sandbox" + if (!sandboxId) throw new Error("sandboxId is required") + + const backup = await createCatalogBackup(sandboxId, sourcePath) + await recordActivity({ + type: "backup.catalog.create", + status: "success", + sandboxId, + sandboxName: backup.sandboxName, + message: `Saved backup ${backup.fileName} to catalog.`, + metadata: { backupId: backup.id, sourcePath: backup.sourcePath, size: backup.size }, + }) + + return NextResponse.json({ ok: true, backup }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to save backup" + await recordActivity({ + type: "backup.catalog.create", + status: "error", + message, + }).catch(() => undefined) + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist|directory/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/backup/route.ts b/app/api/sandbox/[sandboxId]/backup/route.ts index 2b7f510..bd31e84 100644 --- a/app/api/sandbox/[sandboxId]/backup/route.ts +++ b/app/api/sandbox/[sandboxId]/backup/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server" import { backupSandboxArchive } from "@/app/lib/sandboxFiles" +import { recordActivity } from "@/app/lib/activityLog" function contentDisposition(fileName: string) { const fallback = fileName.replace(/[^\w.-]/g, "_") || "sandbox-backup.tar.gz" @@ -15,6 +16,14 @@ export async function GET( const requestUrl = new URL(request.url) const sourcePath = requestUrl.searchParams.get("path") || "/sandbox" const backup = await backupSandboxArchive(sandboxId, sourcePath) + await recordActivity({ + type: "backup.download", + status: "success", + sandboxId, + sandboxName: backup.sandboxName, + message: `Created downloadable backup ${backup.fileName}.`, + metadata: { sourcePath: backup.sourcePath, size: backup.bytes.byteLength }, + }).catch(() => undefined) return new NextResponse(new Uint8Array(backup.bytes), { status: 200, @@ -30,6 +39,11 @@ export async function GET( }) } catch (error) { const message = error instanceof Error ? error.message : "Failed to create sandbox backup" + await recordActivity({ + type: "backup.download", + status: "error", + message, + }).catch(() => undefined) return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist|directory/.test(message) ? 400 : 500 }) } } diff --git a/app/api/sandbox/[sandboxId]/health/route.ts b/app/api/sandbox/[sandboxId]/health/route.ts new file mode 100644 index 0000000..6299764 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/health/route.ts @@ -0,0 +1,95 @@ +import { NextResponse } from "next/server" +import { execOpenShell, normalizeSandboxPhase, resolveSandboxRef } from "@/app/lib/openshellHost" +import { listBackupCatalog } from "@/app/lib/backupCatalog" + +function parseField(output: string, label: string) { + const normalizedLabel = label.toLowerCase() + const line = output + .split(/\r?\n/) + .map((entry) => entry.trim()) + .find((entry) => entry.toLowerCase().startsWith(`${normalizedLabel}:`)) + + return line ? line.slice(label.length + 1).trim() : null +} + +export async function GET( + _request: Request, + { params }: { params: Promise<{ sandboxId: string }> }, +) { + const startedAt = Date.now() + try { + const { sandboxId } = await params + const resolved = await resolveSandboxRef(sandboxId) + const phase = normalizeSandboxPhase(parseField(resolved.details, "Phase")) + const catalog = await listBackupCatalog() + const relatedBackups = catalog.filter((backup) => backup.sandboxId === sandboxId || backup.sandboxName === resolved.name) + + let sshConfig = "" + let sshConfigError = "" + try { + const result = await execOpenShell(["sandbox", "ssh-config", resolved.name]) + sshConfig = result.stdout.trim() + } catch (error) { + sshConfigError = error instanceof Error ? error.message : "ssh-config unavailable" + } + + const checks = [ + { + key: "resolve", + label: "OpenShell resolution", + ok: true, + detail: `${resolved.name} resolved by ${resolved.resolvedBy}.`, + }, + { + key: "phase", + label: "Sandbox phase", + ok: /running|ready/i.test(phase), + detail: phase, + }, + { + key: "ssh", + label: "SSH config", + ok: sshConfig.length > 0, + detail: sshConfig ? "Host alias is available." : sshConfigError || "No SSH config returned.", + }, + { + key: "backup", + label: "Catalog backup", + ok: relatedBackups.length > 0, + detail: relatedBackups.length > 0 + ? `${relatedBackups.length} saved backup${relatedBackups.length === 1 ? "" : "s"} in catalog.` + : "No saved catalog backups yet.", + }, + ] + + return NextResponse.json({ + ok: true, + sandbox: { + requested: resolved.requested, + id: resolved.id, + name: resolved.name, + phase, + }, + checks, + backupCount: relatedBackups.length, + durationMs: Date.now() - startedAt, + checkedAt: new Date().toISOString(), + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to check sandbox health" + return NextResponse.json({ + ok: false, + error: message, + checks: [ + { + key: "resolve", + label: "OpenShell resolution", + ok: false, + detail: message, + }, + ], + durationMs: Date.now() - startedAt, + checkedAt: new Date().toISOString(), + }, { status: 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/restore/route.ts b/app/api/sandbox/[sandboxId]/restore/route.ts index 9f60711..831df2d 100644 --- a/app/api/sandbox/[sandboxId]/restore/route.ts +++ b/app/api/sandbox/[sandboxId]/restore/route.ts @@ -1,5 +1,6 @@ import { NextResponse } from "next/server" import { restoreSandboxArchive } from "@/app/lib/sandboxFiles" +import { recordActivity } from "@/app/lib/activityLog" export async function POST( request: Request, @@ -19,6 +20,14 @@ export async function POST( const replace = rawReplace === "true" || rawReplace === "1" const payload = Buffer.from(await file.arrayBuffer()) const restored = await restoreSandboxArchive(sandboxId, targetPath, file.name, payload, replace) + await recordActivity({ + type: "backup.upload.restore", + status: "success", + sandboxId, + sandboxName: restored.sandboxName, + message: `Restored uploaded archive ${file.name} into ${restored.targetPath}.`, + metadata: { targetPath: restored.targetPath, mode: restored.mode, bytes: restored.bytes }, + }).catch(() => undefined) return NextResponse.json({ ok: true, @@ -27,6 +36,11 @@ export async function POST( }) } catch (error) { const message = error instanceof Error ? error.message : "Failed to restore sandbox backup" + await recordActivity({ + type: "backup.upload.restore", + status: "error", + message, + }).catch(() => undefined) return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|unsafe|archive/.test(message) ? 400 : 500 }) } } diff --git a/app/api/support-bundle/route.ts b/app/api/support-bundle/route.ts new file mode 100644 index 0000000..cb25df4 --- /dev/null +++ b/app/api/support-bundle/route.ts @@ -0,0 +1,68 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { NextResponse } from "next/server" +import { listActivity } from "@/app/lib/activityLog" +import { listBackupCatalog } from "@/app/lib/backupCatalog" + +const execFileAsync = promisify(execFile) + +export const dynamic = "force-dynamic" + +async function run(command: string, args: string[]) { + try { + const { stdout, stderr } = await execFileAsync(command, args, { + timeout: 10000, + env: { ...process.env, NO_COLOR: "1", CLICOLOR: "0", CLICOLOR_FORCE: "0" }, + }) + return { ok: true, stdout: stdout.trim(), stderr: stderr.trim() } + } catch (error) { + return { + ok: false, + stdout: "", + stderr: error instanceof Error ? error.message : "command failed", + } + } +} + +export async function GET() { + const [gitHead, gitStatus, sandboxList, activity, backups] = await Promise.all([ + run("git", ["rev-parse", "--short", "HEAD"]), + run("git", ["status", "--short", "--branch"]), + run(process.env.OPENSHELL_BIN || `${process.env.HOME || ""}/.local/bin/openshell`, ["sandbox", "list"]), + listActivity(75), + listBackupCatalog(), + ]) + + const bundle = { + generatedAt: new Date().toISOString(), + dashboard: { + cwd: process.cwd(), + gitHead: gitHead.stdout || null, + gitStatus: gitStatus.stdout || gitStatus.stderr, + nodeEnv: process.env.NODE_ENV || null, + }, + openshell: { + sandboxList: sandboxList.ok ? sandboxList.stdout : null, + error: sandboxList.ok ? null : sandboxList.stderr, + }, + backups: backups.map((backup) => ({ + id: backup.id, + fileName: backup.fileName, + sandboxName: backup.sandboxName, + sourcePath: backup.sourcePath, + size: backup.size, + createdAt: backup.createdAt, + })), + activity, + } + + const fileName = `openshell-support-${new Date().toISOString().replace(/[:.]/g, "-")}.json` + return new NextResponse(JSON.stringify(bundle, null, 2), { + status: 200, + headers: { + "cache-control": "no-store", + "content-disposition": `attachment; filename="${fileName}"`, + "content-type": "application/json", + }, + }) +} diff --git a/app/components/ActivityPanel.tsx b/app/components/ActivityPanel.tsx new file mode 100644 index 0000000..4b81b8f --- /dev/null +++ b/app/components/ActivityPanel.tsx @@ -0,0 +1,81 @@ +"use client" + +import { useEffect, useState } from "react" + +type ActivityEntry = { + id: string + timestamp: string + type: string + message: string + sandboxName?: string + status?: "success" | "error" | "info" | "warning" +} + +function toneClass(status?: ActivityEntry["status"]) { + if (status === "success") return "bg-[var(--status-running-bg)] text-[var(--status-running)]" + if (status === "error") return "bg-red-500/15 text-red-300" + if (status === "warning") return "bg-amber-400/15 text-amber-300" + return "bg-[var(--background-tertiary)] text-[var(--foreground-dim)]" +} + +export default function ActivityPanel() { + const [entries, setEntries] = useState([]) + const [loading, setLoading] = useState(false) + + async function loadActivity() { + try { + setLoading(true) + const response = await fetch("/api/activity?limit=40", { cache: "no-store" }) + const data = await response.json() + if (Array.isArray(data?.entries)) setEntries(data.entries) + } finally { + setLoading(false) + } + } + + useEffect(() => { + loadActivity() + }, []) + + return ( +
+
+
+

Activity Log

+

Recent backup, restore, catalog, and support actions recorded by the controller.

+
+
+ + + Support Bundle + +
+
+ +
+ {entries.map((entry) => ( +
+
+
+

{entry.message}

+

+ {entry.sandboxName || entry.type} / {new Date(entry.timestamp).toLocaleString()} +

+
+ + {entry.status || "info"} + +
+
+ ))} + {entries.length === 0 && ( +
+ No activity recorded yet. +
+ )} +
+
+ ) +} diff --git a/app/components/HelpPanel.tsx b/app/components/HelpPanel.tsx index aeefe41..b1515d4 100644 --- a/app/components/HelpPanel.tsx +++ b/app/components/HelpPanel.tsx @@ -1,5 +1,10 @@ "use client" +import { useEffect, useMemo, useState } from "react" +import ActivityPanel from "./ActivityPanel" +import SandboxHealthPanel from "./SandboxHealthPanel" +import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" + const helpSections = [ { title: "Daily Flow", @@ -30,6 +35,7 @@ const helpSections = [ title: "Backup / Restore", items: [ "Backup downloads a compressed .tar.gz archive from a sandbox directory, usually /sandbox.", + "Save to Catalog stores a backup on the controller host for later cloning or redeploying.", "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.", ], @@ -52,9 +58,81 @@ const helpSections = [ }, ] -export default function HelpPanel() { +function HealthAccordion({ sandboxes }: { sandboxes: SandboxInventoryItem[] }) { + const [open, setOpen] = useState(true) + const [selectedSandboxId, setSelectedSandboxId] = useState("") + const selectedSandbox = useMemo( + () => sandboxes.find((sandbox) => sandbox.id === selectedSandboxId) || sandboxes[0] || null, + [sandboxes, selectedSandboxId], + ) + + useEffect(() => { + if (!selectedSandboxId && sandboxes[0]) { + setSelectedSandboxId(sandboxes[0].id) + } + }, [sandboxes, selectedSandboxId]) + + return ( +
+ + + {open && ( +
+ {sandboxes.length > 1 && ( + + )} + + {selectedSandbox ? ( + + ) : ( +
+ No sandboxes are available for health checks yet. +
+ )} +
+ )} +
+ ) +} + +export default function HelpPanel({ sandboxes }: { sandboxes: SandboxInventoryItem[] }) { return (
+ +

Operator Guide

Help

@@ -94,6 +172,8 @@ export default function HelpPanel() { ))}
+ + ) } diff --git a/app/components/SandboxArchivePanel.tsx b/app/components/SandboxArchivePanel.tsx index e4268b4..4c25691 100644 --- a/app/components/SandboxArchivePanel.tsx +++ b/app/components/SandboxArchivePanel.tsx @@ -1,6 +1,6 @@ "use client" -import { useState } from "react" +import { useEffect, useState } from "react" import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" interface SandboxArchivePanelProps { @@ -8,14 +8,41 @@ interface SandboxArchivePanelProps { 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 [busy, setBusy] = useState<"backup" | "restore" | null>(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 { @@ -49,6 +76,27 @@ export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: Sand } } + 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 { @@ -73,6 +121,44 @@ export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: Sand } } + 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 (
@@ -102,14 +188,24 @@ export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: Sand 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)]" /> - +
+ + +
@@ -155,6 +251,59 @@ export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: Sand
+
+
+
+
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} diff --git a/app/components/SandboxHealthPanel.tsx b/app/components/SandboxHealthPanel.tsx new file mode 100644 index 0000000..9f8f2e1 --- /dev/null +++ b/app/components/SandboxHealthPanel.tsx @@ -0,0 +1,98 @@ +"use client" + +import { useCallback, useEffect, useState } from "react" +import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" + +type HealthCheck = { + key: string + label: string + ok: boolean + detail: string +} + +type HealthResponse = { + ok: boolean + error?: string + sandbox?: { + id: string | null + name: string + phase: string + } + checks: HealthCheck[] + backupCount?: number + durationMs: number + checkedAt: string +} + +export default function SandboxHealthPanel({ sandbox }: { sandbox: SandboxInventoryItem }) { + const [health, setHealth] = useState(null) + const [loading, setLoading] = useState(false) + + const loadHealth = useCallback(async () => { + try { + setLoading(true) + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/health`, { cache: "no-store" }) + const data = await response.json() + setHealth(data) + } catch (error) { + setHealth({ + ok: false, + error: error instanceof Error ? error.message : "Health check failed", + checks: [], + durationMs: 0, + checkedAt: new Date().toISOString(), + }) + } finally { + setLoading(false) + } + }, [sandbox.id]) + + useEffect(() => { + loadHealth() + }, [loadHealth]) + + const checks = health?.checks || [] + + return ( +
+
+
+
Sandbox Health
+

+ Quick checks for OpenShell resolution, runtime phase, SSH config, and saved backups. +

+
+ +
+ +
+ {(checks.length ? checks : [{ key: "loading", label: "Health", ok: false, detail: loading ? "Checking..." : "No health data yet." }]).map((check) => ( +
+
+
{check.label}
+ + {check.ok ? "ok" : "check"} + +
+

{check.detail}

+
+ ))} +
+ + {health && ( +
+ Checked {new Date(health.checkedAt).toLocaleString()} in {health.durationMs} ms + {health.sandbox ? ` / ${health.sandbox.name} / ${health.sandbox.phase}` : ""} + {health.error ? ` / ${health.error}` : ""} +
+ )} +
+ ) +} diff --git a/app/lib/activityLog.ts b/app/lib/activityLog.ts new file mode 100644 index 0000000..8588d39 --- /dev/null +++ b/app/lib/activityLog.ts @@ -0,0 +1,78 @@ +import { mkdir, readFile, stat, writeFile } from "node:fs/promises" +import path from "node:path" + +const ACTIVITY_LOG_PATH = process.env.OPENSHELL_ACTIVITY_LOG_PATH + || path.join(process.cwd(), ".runtime", "activity-log.jsonl") +const MAX_ACTIVITY_ENTRIES = Number.parseInt(process.env.OPENSHELL_ACTIVITY_LOG_MAX_ENTRIES || "200", 10) +const MAX_ACTIVITY_BYTES = Number.parseInt(process.env.OPENSHELL_ACTIVITY_LOG_MAX_BYTES || String(1024 * 1024), 10) + +export type ActivityEntry = { + id: string + timestamp: string + type: string + message: string + sandboxId?: string + sandboxName?: string + status?: "success" | "error" | "info" | "warning" + metadata?: Record +} + +function compactMetadata(metadata?: Record) { + if (!metadata) return undefined + return Object.fromEntries( + Object.entries(metadata).filter(([, value]) => value !== undefined && value !== null && value !== ""), + ) +} + +async function ensureLogDirectory() { + await mkdir(path.dirname(ACTIVITY_LOG_PATH), { recursive: true }) +} + +async function readLogText() { + try { + const currentStat = await stat(ACTIVITY_LOG_PATH) + if (currentStat.size > MAX_ACTIVITY_BYTES) { + const text = await readFile(ACTIVITY_LOG_PATH, "utf8") + const tail = text.split(/\r?\n/).filter(Boolean).slice(-MAX_ACTIVITY_ENTRIES).join("\n") + await writeFile(ACTIVITY_LOG_PATH, `${tail}\n`) + return tail + } + return await readFile(ACTIVITY_LOG_PATH, "utf8") + } catch { + return "" + } +} + +export async function recordActivity(entry: Omit) { + const payload: ActivityEntry = { + id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, + timestamp: new Date().toISOString(), + ...entry, + metadata: compactMetadata(entry.metadata), + } + + await ensureLogDirectory() + const text = await readLogText() + const lines = text.split(/\r?\n/).filter(Boolean) + lines.push(JSON.stringify(payload)) + await writeFile(ACTIVITY_LOG_PATH, `${lines.slice(-MAX_ACTIVITY_ENTRIES).join("\n")}\n`) + return payload +} + +export async function listActivity(limit = 100) { + const safeLimit = Math.max(1, Math.min(limit, MAX_ACTIVITY_ENTRIES)) + const text = await readLogText() + return text + .split(/\r?\n/) + .filter(Boolean) + .slice(-safeLimit) + .map((line) => { + try { + return JSON.parse(line) as ActivityEntry + } catch { + return null + } + }) + .filter((entry): entry is ActivityEntry => Boolean(entry)) + .reverse() +} diff --git a/app/lib/backupCatalog.ts b/app/lib/backupCatalog.ts new file mode 100644 index 0000000..dd068cc --- /dev/null +++ b/app/lib/backupCatalog.ts @@ -0,0 +1,98 @@ +import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises" +import path from "node:path" +import { backupSandboxArchive, restoreSandboxArchive } from "./sandboxFiles" + +const BACKUP_DIR = process.env.SANDBOX_BACKUP_DIR || path.join(process.cwd(), ".runtime", "backups") +const MAX_BACKUP_COUNT = Number.parseInt(process.env.SANDBOX_BACKUP_CATALOG_MAX || "100", 10) + +export type BackupCatalogEntry = { + id: string + fileName: string + sandboxId: string + sandboxName: string + sourcePath: string + size: number + createdAt: string +} + +function sanitizeSegment(value: string) { + return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "backup" +} + +function archivePath(id: string) { + return path.join(BACKUP_DIR, `${id}.tar.gz`) +} + +function metadataPath(id: string) { + return path.join(BACKUP_DIR, `${id}.json`) +} + +async function ensureBackupDirectory() { + await mkdir(BACKUP_DIR, { recursive: true }) +} + +export async function listBackupCatalog() { + await ensureBackupDirectory() + const names = await readdir(BACKUP_DIR).catch(() => []) + const entries = await Promise.all( + names + .filter((name) => name.endsWith(".json")) + .map(async (name) => { + try { + const metadata = JSON.parse(await readFile(path.join(BACKUP_DIR, name), "utf8")) as BackupCatalogEntry + await stat(archivePath(metadata.id)) + return metadata + } catch { + return null + } + }), + ) + + return entries + .filter((entry): entry is BackupCatalogEntry => Boolean(entry)) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) +} + +export async function createCatalogBackup(sandboxId: string, sourcePath: string) { + await ensureBackupDirectory() + const archive = await backupSandboxArchive(sandboxId, sourcePath) + const id = `${sanitizeSegment(archive.sandboxName)}-${Date.now().toString(36)}` + const entry: BackupCatalogEntry = { + id, + fileName: archive.fileName, + sandboxId, + sandboxName: archive.sandboxName, + sourcePath: archive.sourcePath, + size: archive.bytes.byteLength, + createdAt: archive.createdAt, + } + + await writeFile(archivePath(id), archive.bytes) + await writeFile(metadataPath(id), `${JSON.stringify(entry, null, 2)}\n`) + + const entries = await listBackupCatalog() + await Promise.all(entries.slice(MAX_BACKUP_COUNT).map((stale) => deleteCatalogBackup(stale.id).catch(() => undefined))) + + return entry +} + +export async function getCatalogBackup(id: string) { + const safeId = sanitizeSegment(id) + const metadata = JSON.parse(await readFile(metadataPath(safeId), "utf8")) as BackupCatalogEntry + const bytes = await readFile(archivePath(safeId)) + return { metadata, bytes } +} + +export async function restoreCatalogBackup(id: string, targetSandboxId: string, targetPath: string, replace: boolean) { + const backup = await getCatalogBackup(id) + return restoreSandboxArchive(targetSandboxId, targetPath, backup.metadata.fileName, backup.bytes, replace) +} + +export async function deleteCatalogBackup(id: string) { + const safeId = sanitizeSegment(id) + await Promise.all([ + rm(archivePath(safeId), { force: true }), + rm(metadataPath(safeId), { force: true }), + ]) + return { id: safeId } +} diff --git a/app/page.tsx b/app/page.tsx index f266996..830ece3 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -25,7 +25,7 @@ export default function Dashboard() { const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) const [lifecycleMessage, setLifecycleMessage] = useState(null) const [deleteInProgress, setDeleteInProgress] = useState(false) - const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || isCreateMode || isDestroyMode + const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || isCreateMode || isDestroyMode const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ enabled: inventoryEnabled, }) @@ -254,7 +254,7 @@ export default function Dashboard() {
) : activeView === 'help' ? ( - + ) : activeView === 'wizards' ? ( ) : isCreateMode ? (