Add dashboard backup catalog and health tools

This commit is contained in:
Codex
2026-04-25 02:51:29 +00:00
parent ed7b7e38ea
commit 989d842d78
16 changed files with 923 additions and 13 deletions
+9
View File
@@ -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 })
}
}
+23
View File
@@ -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 })
}
}
+37
View File
@@ -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 { 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 })
}
}
@@ -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 { 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 })
}
}
+68
View File
@@ -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",
},
})
}