Add dashboard backup catalog and health tools
This commit is contained in:
@@ -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 })
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextResponse } from "next/server"
|
import { NextResponse } from "next/server"
|
||||||
import { backupSandboxArchive } from "@/app/lib/sandboxFiles"
|
import { backupSandboxArchive } from "@/app/lib/sandboxFiles"
|
||||||
|
import { recordActivity } from "@/app/lib/activityLog"
|
||||||
|
|
||||||
function contentDisposition(fileName: string) {
|
function contentDisposition(fileName: string) {
|
||||||
const fallback = fileName.replace(/[^\w.-]/g, "_") || "sandbox-backup.tar.gz"
|
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 requestUrl = new URL(request.url)
|
||||||
const sourcePath = requestUrl.searchParams.get("path") || "/sandbox"
|
const sourcePath = requestUrl.searchParams.get("path") || "/sandbox"
|
||||||
const backup = await backupSandboxArchive(sandboxId, sourcePath)
|
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), {
|
return new NextResponse(new Uint8Array(backup.bytes), {
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -30,6 +39,11 @@ export async function GET(
|
|||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : "Failed to create sandbox backup"
|
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 })
|
return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist|directory/.test(message) ? 400 : 500 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextResponse } from "next/server"
|
import { NextResponse } from "next/server"
|
||||||
import { restoreSandboxArchive } from "@/app/lib/sandboxFiles"
|
import { restoreSandboxArchive } from "@/app/lib/sandboxFiles"
|
||||||
|
import { recordActivity } from "@/app/lib/activityLog"
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: Request,
|
request: Request,
|
||||||
@@ -19,6 +20,14 @@ export async function POST(
|
|||||||
const replace = rawReplace === "true" || rawReplace === "1"
|
const replace = rawReplace === "true" || rawReplace === "1"
|
||||||
const payload = Buffer.from(await file.arrayBuffer())
|
const payload = Buffer.from(await file.arrayBuffer())
|
||||||
const restored = await restoreSandboxArchive(sandboxId, targetPath, file.name, payload, replace)
|
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({
|
return NextResponse.json({
|
||||||
ok: true,
|
ok: true,
|
||||||
@@ -27,6 +36,11 @@ export async function POST(
|
|||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : "Failed to restore sandbox backup"
|
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 })
|
return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|unsafe|archive/.test(message) ? 400 : 500 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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<ActivityEntry[]>([])
|
||||||
|
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 (
|
||||||
|
<section className="panel p-5">
|
||||||
|
<div className="flex items-start justify-between gap-4 max-md:flex-col">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Activity Log</h2>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Recent backup, restore, catalog, and support actions recorded by the controller.</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button type="button" onClick={loadActivity} disabled={loading} className="action-button px-3 py-2">
|
||||||
|
{loading ? "Refreshing..." : "Refresh"}
|
||||||
|
</button>
|
||||||
|
<a href="/api/support-bundle" className="action-button px-3 py-2">
|
||||||
|
Support Bundle
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-2">
|
||||||
|
{entries.map((entry) => (
|
||||||
|
<div key={entry.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||||
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-xs font-mono text-[var(--foreground)]">{entry.message}</p>
|
||||||
|
<p className="mt-1 text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">
|
||||||
|
{entry.sandboxName || entry.type} / {new Date(entry.timestamp).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className={`status-chip shrink-0 px-2 py-1 ${toneClass(entry.status)}`}>
|
||||||
|
{entry.status || "info"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{entries.length === 0 && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 text-sm text-[var(--foreground-dim)]">
|
||||||
|
No activity recorded yet.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from "react"
|
||||||
|
import ActivityPanel from "./ActivityPanel"
|
||||||
|
import SandboxHealthPanel from "./SandboxHealthPanel"
|
||||||
|
import type { SandboxInventoryItem } from "../hooks/useSandboxInventory"
|
||||||
|
|
||||||
const helpSections = [
|
const helpSections = [
|
||||||
{
|
{
|
||||||
title: "Daily Flow",
|
title: "Daily Flow",
|
||||||
@@ -30,6 +35,7 @@ const helpSections = [
|
|||||||
title: "Backup / Restore",
|
title: "Backup / Restore",
|
||||||
items: [
|
items: [
|
||||||
"Backup downloads a compressed .tar.gz archive from a sandbox directory, usually /sandbox.",
|
"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.",
|
"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.",
|
"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 (
|
||||||
|
<section className="panel overflow-hidden">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen((current) => !current)}
|
||||||
|
aria-expanded={open}
|
||||||
|
className="flex w-full items-center justify-between gap-4 p-5 text-left"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]">Operator Checks</p>
|
||||||
|
<h2 className="mt-1 text-sm font-semibold uppercase tracking-wider text-[var(--foreground)]">Sandbox Health</h2>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">OpenShell reachability, runtime state, SSH config, and backup coverage.</p>
|
||||||
|
</div>
|
||||||
|
<svg
|
||||||
|
className={`h-4 w-4 shrink-0 text-[var(--foreground-dim)] transition-transform ${open ? "rotate-90" : ""}`}
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div className="space-y-4 border-t border-[var(--border-subtle)] p-5">
|
||||||
|
{sandboxes.length > 1 && (
|
||||||
|
<label className="block max-w-lg space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox</span>
|
||||||
|
<select
|
||||||
|
value={selectedSandbox?.id || ""}
|
||||||
|
onChange={(event) => setSelectedSandboxId(event.target.value)}
|
||||||
|
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:border-[var(--nvidia-green)] focus:outline-none"
|
||||||
|
>
|
||||||
|
{sandboxes.map((sandbox) => (
|
||||||
|
<option key={sandbox.id} value={sandbox.id}>
|
||||||
|
{sandbox.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedSandbox ? (
|
||||||
|
<SandboxHealthPanel sandbox={selectedSandbox} />
|
||||||
|
) : (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 text-sm text-[var(--foreground-dim)]">
|
||||||
|
No sandboxes are available for health checks yet.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function HelpPanel({ sandboxes }: { sandboxes: SandboxInventoryItem[] }) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
<HealthAccordion sandboxes={sandboxes} />
|
||||||
|
|
||||||
<section className="panel p-8">
|
<section className="panel p-8">
|
||||||
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]">Operator Guide</p>
|
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]">Operator Guide</p>
|
||||||
<h1 className="mt-2 text-xl font-semibold uppercase tracking-wider text-[var(--foreground)]">Help</h1>
|
<h1 className="mt-2 text-xl font-semibold uppercase tracking-wider text-[var(--foreground)]">Help</h1>
|
||||||
@@ -94,6 +172,8 @@ export default function HelpPanel() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<ActivityPanel />
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
|
||||||
import { useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import type { SandboxInventoryItem } from "../hooks/useSandboxInventory"
|
import type { SandboxInventoryItem } from "../hooks/useSandboxInventory"
|
||||||
|
|
||||||
interface SandboxArchivePanelProps {
|
interface SandboxArchivePanelProps {
|
||||||
@@ -8,14 +8,41 @@ interface SandboxArchivePanelProps {
|
|||||||
onRestoreComplete?: () => Promise<void> | void
|
onRestoreComplete?: () => Promise<void> | 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) {
|
export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: SandboxArchivePanelProps) {
|
||||||
const [backupPath, setBackupPath] = useState("/sandbox")
|
const [backupPath, setBackupPath] = useState("/sandbox")
|
||||||
const [restorePath, setRestorePath] = useState("/sandbox")
|
const [restorePath, setRestorePath] = useState("/sandbox")
|
||||||
const [restoreReplace, setRestoreReplace] = useState(false)
|
const [restoreReplace, setRestoreReplace] = useState(false)
|
||||||
const [selectedArchive, setSelectedArchive] = useState<File | null>(null)
|
const [selectedArchive, setSelectedArchive] = useState<File | null>(null)
|
||||||
const [busy, setBusy] = useState<"backup" | "restore" | null>(null)
|
const [catalogBackups, setCatalogBackups] = useState<BackupCatalogEntry[]>([])
|
||||||
|
const [busy, setBusy] = useState<"backup" | "catalog" | "restore" | `restore-${string}` | `delete-${string}` | null>(null)
|
||||||
const [message, setMessage] = useState("")
|
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() {
|
async function backupSandbox() {
|
||||||
if (!backupPath.trim() || busy) return
|
if (!backupPath.trim() || busy) return
|
||||||
try {
|
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() {
|
async function restoreSandbox() {
|
||||||
if (!selectedArchive || !restorePath.trim() || busy) return
|
if (!selectedArchive || !restorePath.trim() || busy) return
|
||||||
try {
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
|
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
|
||||||
@@ -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)]"
|
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)]"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<button
|
<div className="flex flex-wrap gap-2">
|
||||||
type="button"
|
<button
|
||||||
onClick={backupSandbox}
|
type="button"
|
||||||
disabled={!backupPath.trim() || busy !== null}
|
onClick={backupSandbox}
|
||||||
className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
disabled={!backupPath.trim() || busy !== null}
|
||||||
>
|
className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
{busy === "backup" ? "Creating Backup..." : "Download Backup"}
|
>
|
||||||
</button>
|
{busy === "backup" ? "Creating Backup..." : "Download Backup"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={saveCatalogBackup}
|
||||||
|
disabled={!backupPath.trim() || busy !== null}
|
||||||
|
className="action-button px-4 py-2"
|
||||||
|
>
|
||||||
|
{busy === "catalog" ? "Saving..." : "Save To Catalog"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-3">
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-3">
|
||||||
@@ -155,6 +251,59 @@ export default function SandboxArchivePanel({ sandbox, onRestoreComplete }: Sand
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-3">
|
||||||
|
<div className="flex items-start justify-between gap-4 max-md:flex-col">
|
||||||
|
<div>
|
||||||
|
<h6 className="text-[11px] font-semibold uppercase tracking-wider text-[var(--foreground)]">Backup Catalog</h6>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Host-side cold storage for cloning and redeploying sandboxes later.</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" onClick={() => loadCatalog().catch((error) => setMessage(error.message))} className="action-button px-3 py-2">
|
||||||
|
Refresh Catalog
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
{catalogBackups.map((backup) => (
|
||||||
|
<div key={backup.id} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3">
|
||||||
|
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-xs font-mono text-[var(--foreground)]">{backup.fileName}</p>
|
||||||
|
<p className="mt-1 text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">
|
||||||
|
{backup.sandboxName} / {backup.sourcePath} / {formatBytes(backup.size)} / {new Date(backup.createdAt).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 flex-wrap gap-2">
|
||||||
|
<a href={`/api/backups/${encodeURIComponent(backup.id)}/download`} className="action-button px-3 py-2">
|
||||||
|
Download
|
||||||
|
</a>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => restoreCatalogBackup(backup.id)}
|
||||||
|
disabled={busy !== null || !restorePath.trim()}
|
||||||
|
className="rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy === `restore-${backup.id}` ? "Restoring..." : "Restore Here"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => deleteCatalogBackup(backup.id)}
|
||||||
|
disabled={busy !== null}
|
||||||
|
className="action-button px-3 py-2"
|
||||||
|
>
|
||||||
|
{busy === `delete-${backup.id}` ? "Deleting..." : "Delete"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{catalogBackups.length === 0 && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-sm text-[var(--foreground-dim)]">
|
||||||
|
No catalog backups saved yet.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{message && (
|
{message && (
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">
|
||||||
{message}
|
{message}
|
||||||
|
|||||||
@@ -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<HealthResponse | null>(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 (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start justify-between gap-4 max-lg:flex-col">
|
||||||
|
<div>
|
||||||
|
<h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Sandbox Health</h5>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">
|
||||||
|
Quick checks for OpenShell resolution, runtime phase, SSH config, and saved backups.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={loadHealth}
|
||||||
|
disabled={loading}
|
||||||
|
className="action-button px-3 py-2"
|
||||||
|
>
|
||||||
|
{loading ? "Checking..." : "Refresh Health"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||||
|
{(checks.length ? checks : [{ key: "loading", label: "Health", ok: false, detail: loading ? "Checking..." : "No health data yet." }]).map((check) => (
|
||||||
|
<div key={check.key} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<h6 className="text-[11px] font-semibold uppercase tracking-wider text-[var(--foreground)]">{check.label}</h6>
|
||||||
|
<span className={`status-chip px-2 py-1 ${check.ok ? "bg-[var(--status-running-bg)] text-[var(--status-running)]" : "bg-amber-400/15 text-amber-300"}`}>
|
||||||
|
{check.ok ? "ok" : "check"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 text-xs leading-5 text-[var(--foreground-dim)]">{check.detail}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{health && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||||
|
Checked {new Date(health.checkedAt).toLocaleString()} in {health.durationMs} ms
|
||||||
|
{health.sandbox ? ` / ${health.sandbox.name} / ${health.sandbox.phase}` : ""}
|
||||||
|
{health.error ? ` / ${health.error}` : ""}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
function compactMetadata(metadata?: Record<string, unknown>) {
|
||||||
|
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<ActivityEntry, "id" | "timestamp">) {
|
||||||
|
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()
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
+2
-2
@@ -25,7 +25,7 @@ export default function Dashboard() {
|
|||||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||||
const [lifecycleMessage, setLifecycleMessage] = useState<string | null>(null)
|
const [lifecycleMessage, setLifecycleMessage] = useState<string | null>(null)
|
||||||
const [deleteInProgress, setDeleteInProgress] = useState(false)
|
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({
|
const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({
|
||||||
enabled: inventoryEnabled,
|
enabled: inventoryEnabled,
|
||||||
})
|
})
|
||||||
@@ -254,7 +254,7 @@ export default function Dashboard() {
|
|||||||
<InferenceEndpointPanel />
|
<InferenceEndpointPanel />
|
||||||
</div>
|
</div>
|
||||||
) : activeView === 'help' ? (
|
) : activeView === 'help' ? (
|
||||||
<HelpPanel />
|
<HelpPanel sandboxes={sandboxes} />
|
||||||
) : activeView === 'wizards' ? (
|
) : activeView === 'wizards' ? (
|
||||||
<WizardPanel sandboxes={sandboxes} onInventoryRefresh={refresh} />
|
<WizardPanel sandboxes={sandboxes} onInventoryRefresh={refresh} />
|
||||||
) : isCreateMode ? (
|
) : isCreateMode ? (
|
||||||
|
|||||||
Reference in New Issue
Block a user