Roll back sandbox create destroy workflow to Monday

This commit is contained in:
mmckeen-nv
2026-04-30 10:08:44 -07:00
parent ae7a7c3a26
commit fda3cbb056
7 changed files with 181 additions and 536 deletions
+1 -93
View File
@@ -2,7 +2,6 @@ import { NextResponse } from "next/server"
import { execFile, spawn } from "node:child_process" import { execFile, spawn } from "node:child_process"
import { promisify } from "node:util" import { promisify } from "node:util"
import { inspectSandbox } from "@/app/lib/openshellHost" import { inspectSandbox } from "@/app/lib/openshellHost"
import { repairOpenClawWorkspacePermissions, stabilizeOpenClawGatewayConfig } from "@/app/lib/sandboxPrivilegedFiles"
import { import {
commandExists, commandExists,
HOST_PATH, HOST_PATH,
@@ -58,60 +57,6 @@ type NemoClawCreateCommand = {
mode: "cli-onboard" | "legacy-setup" mode: "cli-onboard" | "legacy-setup"
} }
type CreateInferenceMode = "auto" | "vllm" | "nim"
type CreateInferenceSettings = {
mode: CreateInferenceMode
model: string
hasApiKey: boolean
envSummary: string[]
}
function parseCreateInferenceSettings(body: any): CreateInferenceSettings {
const raw = body?.createInference && typeof body.createInference === "object" ? body.createInference : {}
const requestedMode = typeof raw.mode === "string" ? raw.mode : "auto"
const mode: CreateInferenceMode = requestedMode === "vllm" || requestedMode === "nim" ? requestedMode : "auto"
const model = typeof raw.model === "string" ? raw.model.trim() : ""
const apiKey = typeof raw.apiKey === "string" ? raw.apiKey.trim() : ""
return {
mode,
model,
hasApiKey: Boolean(apiKey),
envSummary: [],
}
}
function applyCreateInferenceEnv(env: NodeJS.ProcessEnv, settings: CreateInferenceSettings, body: any) {
if (settings.mode === "auto") return settings
env.NEMOCLAW_EXPERIMENTAL = "1"
settings.envSummary.push("NEMOCLAW_EXPERIMENTAL=1")
if (settings.mode === "vllm") {
env.NEMOCLAW_PROVIDER = "vllm"
settings.envSummary.push("NEMOCLAW_PROVIDER=vllm")
}
if (settings.mode === "nim") {
env.NEMOCLAW_PROVIDER = "nim-local"
settings.envSummary.push("NEMOCLAW_PROVIDER=nim-local")
const apiKey = typeof body?.createInference?.apiKey === "string" ? body.createInference.apiKey.trim() : ""
if (apiKey) {
env.NVIDIA_API_KEY = apiKey
env.NEMOCLAW_PROVIDER_KEY = apiKey
settings.envSummary.push("NVIDIA_API_KEY=<provided>", "NEMOCLAW_PROVIDER_KEY=<provided>")
}
}
if (settings.model) {
env.NEMOCLAW_MODEL = settings.model
settings.envSummary.push(`NEMOCLAW_MODEL=${settings.model}`)
}
return settings
}
function buildNemoClawCreateCommand(): NemoClawCreateCommand { function buildNemoClawCreateCommand(): NemoClawCreateCommand {
if (NEMOCLAW_BIN && commandExists(NEMOCLAW_BIN)) { if (NEMOCLAW_BIN && commandExists(NEMOCLAW_BIN)) {
const args = ["onboard", "--non-interactive", "--recreate-sandbox", "--yes-i-accept-third-party-software"] const args = ["onboard", "--non-interactive", "--recreate-sandbox", "--yes-i-accept-third-party-software"]
@@ -386,8 +331,7 @@ export async function POST(request: Request) {
const sandboxName = validateSandboxName(typeof body?.sandboxName === "string" ? body.sandboxName.trim() : "") const sandboxName = validateSandboxName(typeof body?.sandboxName === "string" ? body.sandboxName.trim() : "")
const policy = body?.policy && typeof body.policy === "object" ? body.policy : null const policy = body?.policy && typeof body.policy === "object" ? body.policy : null
const enableTailscale = Boolean(body?.enableTailscale) const enableTailscale = Boolean(body?.enableTailscale)
const createInference = parseCreateInferenceSettings(body) console.log(`[sandbox/create] request:parsed sandbox=${sandboxName} blueprint=${blueprint} enableTailscale=${enableTailscale} elapsedMs=${elapsedMs(requestStartedAt)}`)
console.log(`[sandbox/create] request:parsed sandbox=${sandboxName} blueprint=${blueprint} enableTailscale=${enableTailscale} inferenceMode=${createInference.mode} elapsedMs=${elapsedMs(requestStartedAt)}`)
if (!blueprint) { if (!blueprint) {
return NextResponse.json({ ok: false, error: "blueprint is required" }, { status: 400 }) return NextResponse.json({ ok: false, error: "blueprint is required" }, { status: 400 })
@@ -409,8 +353,6 @@ export async function POST(request: Request) {
env.NVIDIA_API_KEY = env.NVIDIA_API_KEY || "optional-local-mode" env.NVIDIA_API_KEY = env.NVIDIA_API_KEY || "optional-local-mode"
} }
applyCreateInferenceEnv(env, createInference, body)
const result = await runCommand( const result = await runCommand(
createCommand.file, createCommand.file,
createCommand.mode === "legacy-setup" ? [...createCommand.args, sandboxName] : createCommand.args, createCommand.mode === "legacy-setup" ? [...createCommand.args, sandboxName] : createCommand.args,
@@ -427,7 +369,6 @@ export async function POST(request: Request) {
blueprint, blueprint,
sandboxName, sandboxName,
enableTailscale, enableTailscale,
createInference,
}, { status: 500 }) }, { status: 500 })
} }
@@ -438,16 +379,6 @@ export async function POST(request: Request) {
error: "Sandbox readiness polling produced no verification result.", error: "Sandbox readiness polling produced no verification result.",
} }
const created = readiness.verified const created = readiness.verified
const gatewayConfigRepair = created ? await stabilizeOpenClawGatewayConfig(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/openclaw.json",
error: error instanceof Error ? error.message : "Failed to stabilize OpenClaw gateway config",
})) : null
const workspaceRepair = created ? await repairOpenClawWorkspacePermissions(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/workspace",
error: error instanceof Error ? error.message : "Failed to repair OpenClaw workspace permissions",
})) : null
const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null
console.log( console.log(
`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} readinessAttempts=${readiness.attempts} deviceApproval=${deviceApproval?.approved ?? false} elapsedMs=${elapsedMs(requestStartedAt)}`, `[sandbox/create] request:complete sandbox=${sandboxName} created=${created} readinessAttempts=${readiness.attempts} deviceApproval=${deviceApproval?.approved ?? false} elapsedMs=${elapsedMs(requestStartedAt)}`,
@@ -462,15 +393,12 @@ export async function POST(request: Request) {
verification, verification,
mode: "nemoclaw-blueprint", mode: "nemoclaw-blueprint",
enableTailscale, enableTailscale,
createInference,
createCommand, createCommand,
hostPath: HOST_PATH, hostPath: HOST_PATH,
readiness: { readiness: {
attempts: readiness.attempts, attempts: readiness.attempts,
elapsedMs: readiness.elapsedMs, elapsedMs: readiness.elapsedMs,
}, },
workspaceRepair,
gatewayConfigRepair,
deviceApproval, deviceApproval,
stdout: result.stdout, stdout: result.stdout,
stderr: result.stderr, stderr: result.stderr,
@@ -479,10 +407,6 @@ export async function POST(request: Request) {
enableTailscale enableTailscale
? "NemoClaw blueprint workflow completed with Tailscale-enabled prerequisites. Existing healthy OpenShell gateways are reused before any new gateway start is attempted." ? "NemoClaw blueprint workflow completed with Tailscale-enabled prerequisites. Existing healthy OpenShell gateways are reused before any new gateway start is attempted."
: "NemoClaw blueprint workflow completed in local/default mode. Existing healthy OpenShell gateways are reused before any new gateway start is attempted.", : "NemoClaw blueprint workflow completed in local/default mode. Existing healthy OpenShell gateways are reused before any new gateway start is attempted.",
workspaceRepair && "note" in workspaceRepair ? workspaceRepair.note : false,
workspaceRepair && "error" in workspaceRepair ? `OpenClaw workspace permission repair failed: ${workspaceRepair.error}` : false,
gatewayConfigRepair && "note" in gatewayConfigRepair ? gatewayConfigRepair.note : false,
gatewayConfigRepair && "error" in gatewayConfigRepair ? `OpenClaw gateway config repair failed: ${gatewayConfigRepair.error}` : false,
deviceApproval?.note, deviceApproval?.note,
) )
: "Blueprint command reported success, but the sandbox never reached a ready verification state afterward.", : "Blueprint command reported success, but the sandbox never reached a ready verification state afterward.",
@@ -517,16 +441,6 @@ export async function POST(request: Request) {
error: "Sandbox readiness polling produced no verification result.", error: "Sandbox readiness polling produced no verification result.",
} }
const created = readiness.verified const created = readiness.verified
const gatewayConfigRepair = created ? await stabilizeOpenClawGatewayConfig(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/openclaw.json",
error: error instanceof Error ? error.message : "Failed to stabilize OpenClaw gateway config",
})) : null
const workspaceRepair = created ? await repairOpenClawWorkspacePermissions(sandboxName).catch((error) => ({
sandboxName,
path: "/sandbox/.openclaw/workspace",
error: error instanceof Error ? error.message : "Failed to repair OpenClaw workspace permissions",
})) : null
const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null const deviceApproval = created ? await approveOpenClawDeviceRequests(sandboxName) : null
const policyPrepared = Boolean(policy) const policyPrepared = Boolean(policy)
console.log( console.log(
@@ -553,8 +467,6 @@ export async function POST(request: Request) {
attempts: readiness.attempts, attempts: readiness.attempts,
elapsedMs: readiness.elapsedMs, elapsedMs: readiness.elapsedMs,
}, },
workspaceRepair,
gatewayConfigRepair,
deviceApproval, deviceApproval,
policyPrepared, policyPrepared,
note: created note: created
@@ -564,10 +476,6 @@ export async function POST(request: Request) {
: (policyPrepared : (policyPrepared
? "Custom sandbox created. Policy draft is prepared, but applying it live should be a follow-up action." ? "Custom sandbox created. Policy draft is prepared, but applying it live should be a follow-up action."
: "Custom sandbox created."), : "Custom sandbox created."),
workspaceRepair && "note" in workspaceRepair ? workspaceRepair.note : false,
workspaceRepair && "error" in workspaceRepair ? `OpenClaw workspace permission repair failed: ${workspaceRepair.error}` : false,
gatewayConfigRepair && "note" in gatewayConfigRepair ? gatewayConfigRepair.note : false,
gatewayConfigRepair && "error" in gatewayConfigRepair ? `OpenClaw gateway config repair failed: ${gatewayConfigRepair.error}` : false,
deviceApproval?.note, deviceApproval?.note,
) )
: "Create command started, but the sandbox never reached a ready verification state afterward.", : "Create command started, but the sandbox never reached a ready verification state afterward.",
+43 -46
View File
@@ -1,10 +1,8 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { execFile } from "node:child_process" import { execFile } from "node:child_process"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
import { promisify } from "node:util" import { promisify } from "node:util"
import { resolveSandboxRef } from "@/app/lib/openshellHost" import { resolveSandboxRef } from "@/app/lib/openshellHost"
import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands" import { HOST_PATH, NEMOCLAW_BIN, NEMOCLAW_CWD, OPENSHELL_BIN } from "@/app/lib/hostCommands"
const execFileAsync = promisify(execFile) const execFileAsync = promisify(execFile)
@@ -56,9 +54,14 @@ async function deleteSandbox(sandboxName: string) {
console.log(`[sandbox/delete] command:start sandbox=${sandboxName}`) console.log(`[sandbox/delete] command:start sandbox=${sandboxName}`)
try { try {
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "delete", sandboxName], { const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "delete", sandboxName], {
env: hostCommandEnv({ env: {
...process.env,
PATH: HOST_PATH,
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw", OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
}), NO_COLOR: "1",
CLICOLOR: "0",
CLICOLOR_FORCE: "0",
},
timeout: 60000, timeout: 60000,
maxBuffer: 20 * 1024 * 1024, maxBuffer: 20 * 1024 * 1024,
}) })
@@ -80,50 +83,48 @@ function isSandboxNotFound(output: string) {
return /sandbox not found|status:\s*NotFound|not present in the live OpenShell gateway/i.test(output) return /sandbox not found|status:\s*NotFound|not present in the live OpenShell gateway/i.test(output)
} }
function isGatewayRecoverable(output: string) { function isNemoClawSandboxNotRegistered(output: string, sandboxName: string) {
return /Unknown gateway|Deploy it first|transport error|tcp connect error|Connection refused|invalid peer certificate|BadSignature/i.test(output) return new RegExp(`Unknown command:\\s*${sandboxName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i").test(output)
} }
const NEMOCLAW_REGISTRY_PATH = path.join(process.env.HOME || "/tmp", ".nemoclaw", "sandboxes.json")
async function cleanupNemoClawSandbox(sandboxName: string) { async function cleanupNemoClawSandbox(sandboxName: string) {
const startedAt = Date.now()
console.log(`[sandbox/delete] nemoclaw-cleanup:start sandbox=${sandboxName}`)
try { try {
const raw = await readFile(NEMOCLAW_REGISTRY_PATH, "utf8") const { stdout, stderr } = await execFileAsync(NEMOCLAW_BIN, [sandboxName, "destroy", "--yes"], {
const registry = JSON.parse(raw) cwd: NEMOCLAW_CWD,
const sandboxes = registry && typeof registry === "object" && registry.sandboxes && typeof registry.sandboxes === "object" env: {
? registry.sandboxes ...process.env,
: {} PATH: HOST_PATH,
const existed = Object.prototype.hasOwnProperty.call(sandboxes, sandboxName) OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
if (existed) delete sandboxes[sandboxName] NO_COLOR: "1",
const remaining = Object.keys(sandboxes) CLICOLOR: "0",
const defaultSandbox = registry.defaultSandbox === sandboxName CLICOLOR_FORCE: "0",
? remaining[0] || null },
: (registry.defaultSandbox && sandboxes[registry.defaultSandbox] ? registry.defaultSandbox : remaining[0] || null) timeout: 90000,
const next = { ...registry, sandboxes, defaultSandbox } maxBuffer: 20 * 1024 * 1024,
await mkdir(path.dirname(NEMOCLAW_REGISTRY_PATH), { recursive: true, mode: 0o700 }) })
await writeFile(NEMOCLAW_REGISTRY_PATH, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 }) console.log(`[sandbox/delete] nemoclaw-cleanup:done sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)}`)
return { ok: true as const, stdout: String(stdout).trim(), stderr: String(stderr).trim() }
} catch (error: any) {
const message = error instanceof Error ? error.message : String(error ?? "NemoClaw cleanup failed")
const stdout = String(error?.stdout || "").trim()
const stderr = String(error?.stderr || "").trim()
const output = [message, stdout, stderr].filter(Boolean).join("\n")
if (isNemoClawSandboxNotRegistered(output, sandboxName)) {
console.log(`[sandbox/delete] nemoclaw-cleanup:already-gone sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)}`)
return { return {
ok: true as const, ok: true as const,
stdout: "", stdout,
stderr: "", stderr,
note: existed note: "NemoClaw registry already had no matching sandbox.",
? "Pruned NemoClaw registry entry without destroying the shared OpenShell gateway."
: "NemoClaw registry already had no matching sandbox entry.",
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error ?? "NemoClaw registry cleanup failed")
if (/ENOENT/.test(message)) {
return {
ok: true as const,
stdout: "",
stderr: "",
note: "NemoClaw registry file does not exist; skipped registry cleanup.",
} }
} }
console.log(`[sandbox/delete] nemoclaw-cleanup:error sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
return { return {
ok: false as const, ok: false as const,
stdout: "", stdout,
stderr: "", stderr,
error: message, error: message,
} }
} }
@@ -178,6 +179,7 @@ export async function POST(request: Request) {
const result = await deleteSandbox(target.sandboxName) const result = await deleteSandbox(target.sandboxName)
const deleteOutput = [result.error, result.stdout, result.stderr].filter(Boolean).join("\n") const deleteOutput = [result.error, result.stdout, result.stderr].filter(Boolean).join("\n")
const openShellAlreadyGone = !result.ok && isSandboxNotFound(deleteOutput) const openShellAlreadyGone = !result.ok && isSandboxNotFound(deleteOutput)
const cleanup = await cleanupNemoClawSandbox(target.sandboxName)
if (!result.ok && !openShellAlreadyGone) { if (!result.ok && !openShellAlreadyGone) {
return NextResponse.json({ return NextResponse.json({
@@ -191,15 +193,10 @@ export async function POST(request: Request) {
error: result.error, error: result.error,
stdout: result.stdout, stdout: result.stdout,
stderr: result.stderr, stderr: result.stderr,
recoverableGateway: isGatewayRecoverable(deleteOutput), nemoclaw: cleanup,
note: isGatewayRecoverable(deleteOutput) }, { status: 500 })
? "OpenShell gateway is unavailable or its trust state is broken. Repair gateway trust, then retry delete."
: "OpenShell delete failed before NemoClaw cleanup ran.",
}, { status: isGatewayRecoverable(deleteOutput) ? 503 : 500 })
} }
const cleanup = await cleanupNemoClawSandbox(target.sandboxName)
if (!cleanup.ok) { if (!cleanup.ok) {
return NextResponse.json({ return NextResponse.json({
ok: false, ok: false,
+2 -80
View File
@@ -7,7 +7,6 @@ type EndpointProtocol = "" | "rest"
type EndpointTls = "" | "terminate" | "passthrough" type EndpointTls = "" | "terminate" | "passthrough"
type EndpointEnforcement = "" | "enforce" | "audit" type EndpointEnforcement = "" | "enforce" | "audit"
type EndpointAccess = "" | "read-only" | "read-write" | "full" type EndpointAccess = "" | "read-only" | "read-write" | "full"
type CreateInferenceMode = "auto" | "vllm" | "nim"
interface NetworkRule { method: string; path: string } interface NetworkRule { method: string; path: string }
interface NetworkEndpoint { host: string; port: string; protocol: EndpointProtocol; tls: EndpointTls; enforcement: EndpointEnforcement; access: EndpointAccess; rules: NetworkRule[] } interface NetworkEndpoint { host: string; port: string; protocol: EndpointProtocol; tls: EndpointTls; enforcement: EndpointEnforcement; access: EndpointAccess; rules: NetworkRule[] }
@@ -88,9 +87,6 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
const [selectedBlueprint, setSelectedBlueprint] = useState<string>('nemoclaw-blueprint') const [selectedBlueprint, setSelectedBlueprint] = useState<string>('nemoclaw-blueprint')
const [sandboxName, setSandboxName] = useState<string>('') const [sandboxName, setSandboxName] = useState<string>('')
const [enableTailscale, setEnableTailscale] = useState<boolean>(false) const [enableTailscale, setEnableTailscale] = useState<boolean>(false)
const [createInferenceMode, setCreateInferenceMode] = useState<CreateInferenceMode>("vllm")
const [createInferenceModel, setCreateInferenceModel] = useState<string>("")
const [createNvidiaApiKey, setCreateNvidiaApiKey] = useState<string>("")
const [restoreFromBackup, setRestoreFromBackup] = useState<boolean>(false) const [restoreFromBackup, setRestoreFromBackup] = useState<boolean>(false)
const [restoreArchive, setRestoreArchive] = useState<File | null>(null) const [restoreArchive, setRestoreArchive] = useState<File | null>(null)
const [restorePath, setRestorePath] = useState<string>('/sandbox') const [restorePath, setRestorePath] = useState<string>('/sandbox')
@@ -138,12 +134,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
if (mode === 'create') { if (mode === 'create') {
if (!sandboxName.trim()) throw new Error('sandbox name is required') if (!sandboxName.trim()) throw new Error('sandbox name is required')
if (restoreFromBackup && !restoreArchive) throw new Error('backup archive is required when restore from backup is enabled') if (restoreFromBackup && !restoreArchive) throw new Error('backup archive is required when restore from backup is enabled')
const createInference = { const res = await fetch('/api/sandbox/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: sandboxName.trim(), enableTailscale, policy: assembledPolicy, preset: selectedPreset || null }) })
mode: createInferenceMode,
model: createInferenceModel.trim(),
apiKey: createInferenceMode === 'nim' ? createNvidiaApiKey.trim() : '',
}
const res = await fetch('/api/sandbox/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: sandboxName.trim(), enableTailscale, createInference, policy: assembledPolicy, preset: selectedPreset || null }) })
const data = await res.json() const data = await res.json()
if (!res.ok) throw new Error([data.error, data.verification?.summary, data.verification?.error, data.stdout, data.stderr].filter(Boolean).join('\n\n')) if (!res.ok) throw new Error([data.error, data.verification?.summary, data.verification?.error, data.stdout, data.stderr].filter(Boolean).join('\n\n'))
const createdSandboxId = data.verification?.details?.id || data.verification?.details?.name || data.sandboxName const createdSandboxId = data.verification?.details?.id || data.verification?.details?.name || data.sandboxName
@@ -197,76 +188,7 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre
</div> </div>
)} )}
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8"> {loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8">
{mode === 'create' && ( {mode === 'create' && <section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a template and enter a sandbox name.</p></div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{blueprints.map((bp) => <button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}><div className="flex items-center justify-between gap-3"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span><Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge></div><p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p></button>)}</div><div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Lowercase letters, numbers, and hyphens only." /></label><input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" /></div>{activeBlueprint?.supportsTailscale && <label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale</label>}{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4"><label className="flex items-start gap-3"><input type="checkbox" checked={restoreFromBackup} onChange={(e) => setRestoreFromBackup(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" /><span><span className="block text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Restore from Backup</span><span className="mt-1 block text-xs text-[var(--foreground-dim)]">After the sandbox reaches Ready, restore a .tar.gz archive into it.</span></span></label>{restoreFromBackup && <div className="grid grid-cols-1 gap-4 md:grid-cols-2"><div className="space-y-2"><label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Backup Archive</label><input type="file" accept=".tar.gz,.tgz,application/gzip,application/x-gzip" onChange={(e) => setRestoreArchive(e.target.files?.[0] || null)} className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background-tertiary)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" /></div><div className="space-y-2"><label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Restore Target</label><input value={restorePath} onChange={(e) => setRestorePath(e.target.value)} placeholder="/sandbox" 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)]" /></div><label className="md:col-span-2 flex items-start gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3"><input type="checkbox" checked={restoreReplace} onChange={(e) => setRestoreReplace(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" /><span><span className="block text-xs font-mono uppercase tracking-wider text-[var(--foreground)]">Replace target contents</span><span className="mt-1 block text-[11px] text-[var(--foreground-dim)]">Recommended for cloning from a backup into a fresh sandbox.</span></span></label></div>}</div></section>}
<section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div>
<h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5>
<p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a template and enter a sandbox name.</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{blueprints.map((bp) => (
<button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}>
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span>
<Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge>
</div>
<p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p>
</button>
))}
</div>
<div>
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Lowercase letters, numbers, and hyphens only." /></label>
<input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
</div>
{activeBlueprint?.supportsTailscale && (
<label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono">
<input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale
</label>
)}
{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4">
<div>
<h6 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Inference at Create</h6>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Choose the provider NemoClaw should use while onboarding this sandbox.</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<label className={`flex items-start gap-3 rounded-sm border p-3 text-sm text-[var(--foreground)] ${createInferenceMode === 'auto' ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)]'}`}>
<input type="checkbox" checked={createInferenceMode === 'auto'} onChange={() => setCreateInferenceMode('auto')} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" />
<span><span className="block text-xs font-mono uppercase tracking-wider">Auto</span><span className="mt-1 block text-[11px] text-[var(--foreground-dim)]">Let NemoClaw choose.</span></span>
</label>
<label className={`flex items-start gap-3 rounded-sm border p-3 text-sm text-[var(--foreground)] ${createInferenceMode === 'vllm' ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)]'}`}>
<input type="checkbox" checked={createInferenceMode === 'vllm'} onChange={() => setCreateInferenceMode('vllm')} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" />
<span><span className="block text-xs font-mono uppercase tracking-wider">Use vLLM in experimental mode</span><span className="mt-1 block text-[11px] text-[var(--foreground-dim)]">Sets NEMOCLAW_EXPERIMENTAL and vLLM.</span></span>
</label>
<label className={`flex items-start gap-3 rounded-sm border p-3 text-sm text-[var(--foreground)] ${createInferenceMode === 'nim' ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)]'}`}>
<input type="checkbox" checked={createInferenceMode === 'nim'} onChange={() => setCreateInferenceMode('nim')} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" />
<span><span className="block text-xs font-mono uppercase tracking-wider">Use NVIDIA NIM</span><span className="mt-1 block text-[11px] text-[var(--foreground-dim)]">Uses the experimental local NIM provider.</span></span>
</label>
</div>
{createInferenceMode !== 'auto' && (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Model</label>
<input value={createInferenceModel} onChange={(e) => setCreateInferenceModel(e.target.value)} placeholder={createInferenceMode === 'vllm' ? 'auto-detect from vLLM' : 'model name'} 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)]" />
</div>
{createInferenceMode === 'nim' && (
<div className="space-y-2">
<label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">NVIDIA API Key</label>
<input type="password" value={createNvidiaApiKey} onChange={(e) => setCreateNvidiaApiKey(e.target.value)} placeholder="nvapi-..." 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)]" />
</div>
)}
</div>
)}
</div>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-4 space-y-4">
<label className="flex items-start gap-3">
<input type="checkbox" checked={restoreFromBackup} onChange={(e) => setRestoreFromBackup(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" />
<span><span className="block text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Restore from Backup</span><span className="mt-1 block text-xs text-[var(--foreground-dim)]">After the sandbox reaches Ready, restore a .tar.gz archive into it.</span></span>
</label>
{restoreFromBackup && <div className="grid grid-cols-1 gap-4 md:grid-cols-2"><div className="space-y-2"><label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Backup Archive</label><input type="file" accept=".tar.gz,.tgz,application/gzip,application/x-gzip" onChange={(e) => setRestoreArchive(e.target.files?.[0] || null)} className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background-tertiary)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" /></div><div className="space-y-2"><label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Restore Target</label><input value={restorePath} onChange={(e) => setRestorePath(e.target.value)} placeholder="/sandbox" 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)]" /></div><label className="md:col-span-2 flex items-start gap-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3"><input type="checkbox" checked={restoreReplace} onChange={(e) => setRestoreReplace(e.target.checked)} className="mt-0.5 h-4 w-4 accent-[var(--nvidia-green)]" /><span><span className="block text-xs font-mono uppercase tracking-wider text-[var(--foreground)]">Replace target contents</span><span className="mt-1 block text-[11px] text-[var(--foreground-dim)]">Recommended for cloning from a backup into a fresh sandbox.</span></span></label></div>}
</div>
</section>
)}
<section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(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)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section> <section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(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)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section>
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section> <section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section>
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section> <section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section>
+57 -135
View File
@@ -1,5 +1,5 @@
"use client" "use client"
import { useCallback, useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import ConfigurationPanel from './ConfigurationPanel' import ConfigurationPanel from './ConfigurationPanel'
import SandboxArchivePanel from './SandboxArchivePanel' import SandboxArchivePanel from './SandboxArchivePanel'
@@ -150,34 +150,33 @@ export default function SandboxList({
} }
}, [selectedSandboxId]) }, [selectedSandboxId])
const loadPermissionFeed = useCallback(async (sandbox: SandboxInventoryItem) => {
try {
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/permissions`, { cache: 'no-store' })
const data = await response.json()
const feed = response.ok ? data.feed : { rejectedCount: 1, latest: { status: 'Unavailable', error: data.error } }
setPermissionFeeds((current) => ({ ...current, [sandbox.id]: feed }))
} catch (error) {
setPermissionFeeds((current) => ({
...current,
[sandbox.id]: { rejectedCount: 1, latest: { status: 'Unavailable', error: error instanceof Error ? error.message : 'Permission feed unavailable' } },
}))
}
}, [])
useEffect(() => { useEffect(() => {
if (sandboxes.length === 0) { if (sandboxes.length === 0) {
setPermissionFeeds({}) setPermissionFeeds({})
return return
} }
setPermissionFeeds((current) => Object.fromEntries(
Object.entries(current).filter(([sandboxId]) => sandboxes.some((sandbox) => sandbox.id === sandboxId)),
))
}, [sandboxes])
useEffect(() => { let active = true
if (!selectedSandbox || !openDrawers.policy || permissionFeeds[selectedSandbox.id]) return const loadPermissionFeeds = async () => {
loadPermissionFeed(selectedSandbox) const entries = await Promise.all(sandboxes.map(async (sandbox) => {
}, [loadPermissionFeed, openDrawers.policy, permissionFeeds, selectedSandbox]) try {
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/permissions`, { cache: 'no-store' })
const data = await response.json()
return [sandbox.id, response.ok ? data.feed : { rejectedCount: 1, latest: { status: 'Unavailable', error: data.error } }] as const
} catch (error) {
return [sandbox.id, { rejectedCount: 1, latest: { status: 'Unavailable', error: error instanceof Error ? error.message : 'Permission feed unavailable' } }] as const
}
}))
if (active) setPermissionFeeds(Object.fromEntries(entries))
}
loadPermissionFeeds()
const interval = window.setInterval(loadPermissionFeeds, 12000)
return () => {
active = false
window.clearInterval(interval)
}
}, [sandboxes])
useEffect(() => { useEffect(() => {
let active = true let active = true
@@ -213,31 +212,27 @@ export default function SandboxList({
} }
} }
const restartSandboxRuntime = async () => { const restartSandbox = async () => {
if (!selectedSandbox || restartInProgress) return if (!selectedSandbox || restartInProgress) return
try { try {
setRestartInProgress(true) setRestartInProgress(true)
setDashboardMessage(`Restarting OpenClaw runtime for ${selectedSandbox.name}...`) setDashboardMessage(`Restarting sandbox ${selectedSandbox.name}...`)
const response = await fetch(`/api/sandbox/${encodeURIComponent(selectedSandbox.id)}/restart`, { const response = await fetch(`/api/sandbox/${encodeURIComponent(selectedSandbox.id)}/restart`, {
method: 'POST', method: 'POST',
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) throw new Error(data.error || data.note || 'Failed to restart OpenClaw runtime') if (!response.ok) throw new Error(data.error || data.note || 'Failed to restart sandbox')
setDashboardMessage(data.note || `OpenClaw runtime restarted for ${selectedSandbox.name}.`) setDashboardMessage(data.note || `Sandbox ${selectedSandbox.name} restarted.`)
await onInventoryRefresh() await onInventoryRefresh()
} catch (error) { } catch (error) {
setDashboardMessage(error instanceof Error ? error.message : 'Failed to restart OpenClaw runtime.') setDashboardMessage(error instanceof Error ? error.message : 'Failed to restart sandbox.')
} finally { } finally {
setRestartInProgress(false) setRestartInProgress(false)
} }
} }
const toggleDrawer = (key: DrawerKey) => { const toggleDrawer = (key: DrawerKey) => {
const opening = !openDrawers[key]
setOpenDrawers((current) => ({ ...current, [key]: !current[key] })) setOpenDrawers((current) => ({ ...current, [key]: !current[key] }))
if (key === 'policy' && opening && selectedSandbox) {
loadPermissionFeed(selectedSandbox)
}
} }
const sandboxCanAccessMcpServer = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { const sandboxCanAccessMcpServer = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
@@ -274,25 +269,20 @@ export default function SandboxList({
} }
} }
const syncMcpManifest = async (sandbox: SandboxInventoryItem, action: 'sync' | 'revoke' = 'sync') => { const syncMcpManifest = async (sandbox: SandboxInventoryItem) => {
try { try {
setMcpSyncing(true) setMcpSyncing(true)
setMcpMessage(action === 'revoke' ? `Revoking MCP broker config for ${sandbox.name}...` : `Issuing MCP broker config for ${sandbox.name}...`) setMcpMessage(`Issuing MCP broker config for ${sandbox.name}...`)
const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, { const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sandboxName: sandbox.name, action }), body: JSON.stringify({ sandboxName: sandbox.name }),
}) })
const data = await response.json() const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to update MCP broker config') if (!response.ok) throw new Error(data.error || 'Failed to issue MCP broker config')
const networkNote = data.network?.approved?.length setMcpMessage(data.note || 'MCP broker config issued.')
? ` Approved ${data.network.approved.length} broker network rule${data.network.approved.length === 1 ? '' : 's'}.`
: data.network?.rejected?.length
? ` Removed ${data.network.rejected.length} broker network rule${data.network.rejected.length === 1 ? '' : 's'}.`
: ''
setMcpMessage(`${data.note || 'MCP broker config updated.'}${networkNote}`)
} catch (error) { } catch (error) {
setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP broker config') setMcpMessage(error instanceof Error ? error.message : 'Failed to issue MCP broker config')
} finally { } finally {
setMcpSyncing(false) setMcpSyncing(false)
} }
@@ -305,7 +295,7 @@ export default function SandboxList({
enabled: true, enabled: true,
accessMode: server.accessMode === 'allow_all' ? 'allow_all' : 'allow_only', accessMode: server.accessMode === 'allow_all' ? 'allow_all' : 'allow_only',
allowedSandboxIds: Array.from(current), allowedSandboxIds: Array.from(current),
}, `${server.name} enabled for ${sandbox.name}.`) }, `${server.name} enabled for ${sandbox.name}.`).then(() => syncMcpManifest(sandbox))
} }
const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => {
@@ -320,7 +310,7 @@ export default function SandboxList({
return updateMcpServerAccess(server, { return updateMcpServerAccess(server, {
accessMode: 'allow_only', accessMode: 'allow_only',
allowedSandboxIds: Array.from(current), allowedSandboxIds: Array.from(current),
}, `${server.name} revoked from ${sandbox.name}.`) }, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox))
} }
const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => {
@@ -360,25 +350,21 @@ export default function SandboxList({
</div> </div>
) : ( ) : (
<> <>
<aside className="border border-[var(--border-subtle)] bg-[var(--background-secondary)]/95 shadow-[12px_0_40px_rgba(0,0,0,0.2)] backdrop-blur lg:fixed lg:left-64 lg:top-0 lg:z-10 lg:h-screen lg:w-80 lg:border-y-0 lg:border-l-0 max-lg:rounded max-lg:shadow-[var(--shadow-soft)]"> <div className="flex items-end justify-between gap-4 max-sm:flex-col max-sm:items-start">
<div className="flex items-start justify-between gap-4 border-b border-[var(--border-subtle)] p-4"> <div>
<div className="min-w-0">
<p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]"> <p className="text-[10px] font-mono uppercase tracking-wider text-[var(--nvidia-green)]">
Inventory Inventory
</p> </p>
<h3 className="mt-1 text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider"> <h3 className="mt-1 text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
{isDestroyMode ? 'Select To Destroy' : 'Sandboxes'} {isDestroyMode ? 'SELECT SANDBOX TO DESTROY' : 'ACTIVE SANDBOXES'}
</h3> </h3>
<p className="mt-1 text-[11px] text-[var(--foreground-dim)]">
{sandboxes.length} total / {sandboxes.filter((sandbox) => sandbox.ready).length} ready
</p>
</div> </div>
<span className="status-chip shrink-0 border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]"> <span className="status-chip border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-2.5 py-1 text-[var(--foreground-dim)]">
10s REFRESH 10s
</span> </span>
</div> </div>
<div className="max-h-[calc(100vh-5.5rem)] space-y-2 overflow-y-auto p-3 max-lg:max-h-[22rem]"> <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
{sandboxes.map((sandbox) => ( {sandboxes.map((sandbox) => (
<div <div
key={sandbox.id} key={sandbox.id}
@@ -387,16 +373,16 @@ export default function SandboxList({
? 'border-[var(--status-stopped)] bg-[var(--status-stopped-bg)] hover:shadow-[0_18px_60px_rgba(220,38,38,0.16)]' ? 'border-[var(--status-stopped)] bg-[var(--status-stopped-bg)] hover:shadow-[0_18px_60px_rgba(220,38,38,0.16)]'
: selectedSandboxId === sandbox.id : selectedSandboxId === sandbox.id
? 'border-[var(--nvidia-green)] bg-[var(--surface-hover)] shadow-[var(--shadow-glow)]' ? 'border-[var(--nvidia-green)] bg-[var(--surface-hover)] shadow-[var(--shadow-glow)]'
: 'border-[var(--border-subtle)] bg-[var(--surface-raised)] shadow-[var(--shadow-soft)] hover:border-[var(--nvidia-green)] hover:bg-[var(--surface-hover)]' : 'border-[var(--border-subtle)] bg-[var(--surface-raised)] shadow-[var(--shadow-soft)] hover:-translate-y-0.5 hover:border-[var(--nvidia-green)] hover:bg-[var(--surface-hover)]'
}`} }`}
> >
<button <button
type="button" type="button"
onClick={() => onSandboxSelect(sandbox.id)} onClick={() => onSandboxSelect(sandbox.id)}
className="w-full p-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--nvidia-green)]" className="w-full p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--nvidia-green)]"
aria-pressed={selectedSandboxId === sandbox.id} aria-pressed={selectedSandboxId === sandbox.id}
> >
<div className="mb-2 flex items-start justify-between gap-3"> <div className="mb-3 flex items-start justify-between gap-3">
<div className="flex items-center gap-2 min-w-0"> <div className="flex items-center gap-2 min-w-0">
{(() => { {(() => {
const feed = permissionFeeds[sandbox.id] const feed = permissionFeeds[sandbox.id]
@@ -453,19 +439,21 @@ export default function SandboxList({
</div> </div>
</div> </div>
<div className="space-y-1"> <div className="space-y-1.5">
{([ {([
['Attach Target', sandbox.ip, '180px'], ['Attach Target', sandbox.ip, '180px'],
['Namespace', sandbox.namespace, '120px'],
['Host Alias', sandbox.sshHostAlias || 'N/A', '140px'],
['Sandbox ID', sandbox.id, '140px'], ['Sandbox ID', sandbox.id, '140px'],
] as Array<[string, string, string]>).map(([label, value, width]) => ( ] as Array<[string, string, string]>).map(([label, value, width]) => (
<div key={label} className="grid grid-cols-[5.75rem_minmax(0,1fr)] items-center gap-2"> <div key={label} className="grid grid-cols-[6.5rem_minmax(0,1fr)] items-center gap-3">
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{label}</span> <span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">{label}</span>
<span className="text-xs font-mono truncate text-[var(--foreground)]" style={{ maxWidth: width }} title={value}>{value}</span> <span className="text-xs font-mono truncate text-[var(--foreground)]" style={{ maxWidth: width }} title={value}>{value}</span>
</div> </div>
))} ))}
</div> </div>
</button> </button>
<div className="border-t border-[var(--border-subtle)] p-2"> <div className="border-t border-[var(--border-subtle)] p-3">
<select <select
value="" value=""
disabled={grantingSandboxId === sandbox.id} disabled={grantingSandboxId === sandbox.id}
@@ -475,7 +463,7 @@ export default function SandboxList({
event.currentTarget.value = '' event.currentTarget.value = ''
resolvePermissionRequest(sandbox, 'approve', value) resolvePermissionRequest(sandbox, 'approve', value)
}} }}
className="field-control w-full px-2 py-2 font-mono text-[11px] uppercase tracking-wider" className="field-control w-full px-3 py-2 font-mono text-xs uppercase tracking-wider"
> >
<option value=""> <option value="">
{grantingSandboxId === sandbox.id {grantingSandboxId === sandbox.id
@@ -494,7 +482,6 @@ export default function SandboxList({
</div> </div>
))} ))}
</div> </div>
</aside>
{permissionMessage && ( {permissionMessage && (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]"> <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
@@ -537,11 +524,11 @@ export default function SandboxList({
Start OpenClaw Gateway Dashboard Start OpenClaw Gateway Dashboard
</button> </button>
<button <button
onClick={restartSandboxRuntime} onClick={restartSandbox}
disabled={restartInProgress} disabled={restartInProgress}
className="action-button px-3 py-2" className="action-button px-3 py-2"
> >
{restartInProgress ? 'Restarting Runtime...' : 'Restart OpenClaw Runtime'} {restartInProgress ? 'Restarting Sandbox...' : 'Restart Sandbox'}
</button> </button>
<button <button
onClick={async () => { onClick={async () => {
@@ -612,16 +599,16 @@ export default function SandboxList({
<div> <div>
<h4 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Sandbox Manifest</h4> <h4 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Sandbox Manifest</h4>
<p className="mt-1 text-xs text-[var(--foreground-dim)]"> <p className="mt-1 text-xs text-[var(--foreground-dim)]">
Writes <span className="font-mono text-[var(--foreground)]">/sandbox/openshell_control_mcp.md</span> and configures OpenClaw to use the broker MCP endpoint. Writes <span className="font-mono text-[var(--foreground)]">/sandbox/openshell_control_mcp.md</span> with broker URL and sandbox token only.
</p> </p>
</div> </div>
<button <button
type="button" type="button"
disabled={mcpSyncing} disabled={mcpSyncing}
onClick={() => syncMcpManifest(selectedSandbox, allowedMcpServersForSandbox(selectedSandbox).length > 0 ? 'sync' : 'revoke')} onClick={() => syncMcpManifest(selectedSandbox)}
className="action-button px-3 py-2 max-sm:w-full" className="action-button px-3 py-2 max-sm:w-full"
> >
{mcpSyncing ? 'Updating...' : 'Sync Broker Config'} {mcpSyncing ? 'Issuing...' : 'Issue Broker Config'}
</button> </button>
</div> </div>
{mcpMessage && ( {mcpMessage && (
@@ -690,80 +677,18 @@ export default function SandboxList({
onToggle={() => toggleDrawer('policy')} onToggle={() => toggleDrawer('policy')}
> >
<div className="space-y-4"> <div className="space-y-4">
<div className="flex items-center justify-between gap-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 max-sm:flex-col max-sm:items-start">
<div>
<h4 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Network Permission Feed</h4>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Loaded on demand for the selected sandbox to avoid background permission polling.</p>
</div>
<button
type="button"
disabled={grantingSandboxId === selectedSandbox.id}
onClick={() => loadPermissionFeed(selectedSandbox)}
className="action-button px-3 py-2 max-sm:w-full"
>
Refresh Requests
</button>
</div>
{(() => { {(() => {
const feed = permissionFeeds[selectedSandbox.id] const feed = permissionFeeds[selectedSandbox.id]
const pending = feed?.pending || [] const pending = feed?.pending || []
const recent = feed?.recent || []
const recentRules = recent.filter((request) => !pending.some((pendingRequest) => pendingRequest.chunkId === request.chunkId))
const renderRecentRules = () => recentRules.length > 0 && (
<div className="space-y-3">
<h4 className="text-[10px] font-semibold uppercase tracking-wider text-[var(--foreground-dim)]">Recent Network Rules</h4>
<div className="max-h-[26rem] space-y-3 overflow-y-auto pr-1">
{recentRules.map((request) => {
const approved = /approved/i.test(request.status)
const rejected = /rejected/i.test(request.status)
return (
<div key={`${request.status}-${request.chunkId}`} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-start justify-between gap-4 max-md:flex-col">
<div className="min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="break-all text-xs font-mono font-semibold text-[var(--foreground)]">
{request.endpoints.join(', ') || request.rule}
</span>
<span className={`status-chip px-2 py-1 ${approved ? 'bg-[var(--status-running-bg)] text-[var(--status-running)]' : rejected ? 'bg-[var(--status-stopped)] text-white' : 'bg-[var(--status-pending-bg)] text-[var(--status-pending)]'}`}>
{request.status || 'unknown'}
</span>
</div>
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox network rule.'}</p>
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
</p>
</div>
{(approved || rejected) && (
<button
type="button"
disabled={grantingSandboxId === selectedSandbox.id}
onClick={() => resolvePermissionRequest(selectedSandbox, approved ? 'reject' : 'approve', request.chunkId)}
className={`${rejected ? 'rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] text-black' : 'rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] text-[var(--foreground)]'} px-3 py-2 text-xs font-mono uppercase tracking-wider disabled:opacity-50 max-md:w-full`}
>
{approved ? 'Revoke' : 'Approve'}
</button>
)}
</div>
</div>
)
})}
</div>
</div>
)
if (pending.length === 0) { if (pending.length === 0) {
return ( return (
<>
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]"> <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
No pending network permission requests for this sandbox. No pending network permission requests for this sandbox.
</div> </div>
{renderRecentRules()}
</>
) )
} }
return ( return pending.map((request) => (
<div className="space-y-3">
{pending.map((request) => (
<div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4"> <div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4">
<div className="flex items-start justify-between gap-4 max-md:flex-col"> <div className="flex items-start justify-between gap-4 max-md:flex-col">
<div className="min-w-0 space-y-2"> <div className="min-w-0 space-y-2">
@@ -802,10 +727,7 @@ export default function SandboxList({
</div> </div>
</div> </div>
</div> </div>
))} ))
{renderRecentRules()}
</div>
)
})()} })()}
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} /> <ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} />
</div> </div>
+11 -44
View File
@@ -1,6 +1,6 @@
import { execFile, spawn } from "node:child_process" import { execFile, spawn } from "node:child_process"
import { promisify } from "node:util" import { promisify } from "node:util"
import { HOST_PATH, OPENCLAW_BIN, OPENSHELL_BIN, hostCommandEnv } from "./hostCommands" import { HOST_PATH, OPENCLAW_BIN, OPENSHELL_BIN } from "./hostCommands"
import { getDefaultOpenClawInstance, getOpenClawDashboardPortForSandbox, resolveOpenClawInstance } from "./openclawInstances" import { getDefaultOpenClawInstance, getOpenClawDashboardPortForSandbox, resolveOpenClawInstance } from "./openclawInstances"
const execFileAsync = promisify(execFile) const execFileAsync = promisify(execFile)
@@ -44,7 +44,13 @@ export type DashboardProbe = {
export async function execOpenShell(args: string[]) { export async function execOpenShell(args: string[]) {
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, { const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
env: hostCommandEnv(), env: {
...process.env,
PATH: HOST_PATH,
NO_COLOR: "1",
CLICOLOR: "0",
CLICOLOR_FORCE: "0",
},
}) })
return { stdout, stderr } return { stdout, stderr }
} }
@@ -263,37 +269,6 @@ function rewriteDashboardBootstrapOrigin(bootstrapUrl: string, dashboardUrl: str
return bootstrap.toString() return bootstrap.toString()
} }
function normalizeDashboardToken(value: string | null | undefined) {
const token = value?.trim() || ''
if (!token || /\s/.test(token)) return null
return token
}
function withDashboardToken(bootstrapUrl: string, token: string | null) {
if (!token || hasDashboardToken(bootstrapUrl)) return bootstrapUrl
try {
const parsed = new URL(bootstrapUrl)
const hashParams = new URLSearchParams(parsed.hash.startsWith('#') ? parsed.hash.slice(1) : parsed.hash)
hashParams.set('token', token)
parsed.hash = hashParams.toString()
return parsed.toString()
} catch {
const separator = bootstrapUrl.includes('#') ? '&' : '#'
return `${bootstrapUrl}${separator}token=${encodeURIComponent(token)}`
}
}
async function readSandboxOpenClawDashboardToken(sandboxName: string) {
const script = [
'const fs=require("fs")',
'const cfg=JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json","utf8"))',
'const token=cfg?.gateway?.auth?.token||cfg?.gateway?.token||""',
'if(token) process.stdout.write(String(token))',
].join(';')
const { stdout } = await execSandboxSsh(sandboxName, `node -e '${script}'`, 5000)
return normalizeDashboardToken(stdout)
}
export async function resolveOpenClawDashboardBootstrap(instanceId?: string | null) { export async function resolveOpenClawDashboardBootstrap(instanceId?: string | null) {
const instance = resolveOpenClawInstance(instanceId) const instance = resolveOpenClawInstance(instanceId)
const defaultInstance = getDefaultOpenClawInstance() const defaultInstance = getDefaultOpenClawInstance()
@@ -308,19 +283,11 @@ export async function resolveOpenClawDashboardBootstrap(instanceId?: string | nu
const bootstrapUrl = rawBootstrapUrl const bootstrapUrl = rawBootstrapUrl
? rewriteDashboardBootstrapOrigin(rawBootstrapUrl, instance.dashboardUrl) ? rewriteDashboardBootstrapOrigin(rawBootstrapUrl, instance.dashboardUrl)
: null : null
let tokenizedBootstrapUrl = bootstrapUrl const bootstrapTokenPresent = hasDashboardToken(bootstrapUrl)
let bootstrapTokenPresent = hasDashboardToken(tokenizedBootstrapUrl)
if (tokenizedBootstrapUrl && !bootstrapTokenPresent) { if (bootstrapUrl) {
await execSandboxSsh(sandboxInstance.sandboxId, 'openclaw dashboard', 15000).catch(() => null)
const token = await readSandboxOpenClawDashboardToken(sandboxInstance.sandboxId).catch(() => null)
tokenizedBootstrapUrl = withDashboardToken(tokenizedBootstrapUrl, token)
bootstrapTokenPresent = hasDashboardToken(tokenizedBootstrapUrl)
}
if (tokenizedBootstrapUrl) {
return { return {
bootstrapUrl: tokenizedBootstrapUrl, bootstrapUrl,
bootstrapTokenPresent, bootstrapTokenPresent,
bootstrapSource: 'openclaw-cli' as const, bootstrapSource: 'openclaw-cli' as const,
bootstrapAuthority: bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const), bootstrapAuthority: bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const),
+2 -60
View File
@@ -26,7 +26,6 @@ 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 [gatewayRepairing, setGatewayRepairing] = useState(false)
const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || activeView === 'mcp' || isCreateMode || isDestroyMode const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || activeView === 'mcp' || isCreateMode || isDestroyMode
const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({
enabled: inventoryEnabled, enabled: inventoryEnabled,
@@ -95,31 +94,6 @@ export default function Dashboard() {
const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms)) const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms))
const gatewayTrustError = Boolean(error && /BadSignature|invalid peer certificate|transport error|certificate signature|Unknown gateway|Deploy it first|Connection refused|tcp connect error/i.test(error))
const repairGatewayTrust = async () => {
if (gatewayRepairing) return
try {
setGatewayRepairing(true)
setLifecycleMessage(
"Repairing OpenShell gateway trust. This backs up local OpenShell config, restarts the selected gateway, reselects it, and verifies sandbox inventory. It does not destroy sandboxes."
)
const response = await fetch('/api/openshell/gateway/repair', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: 'inventory BadSignature recovery' }),
})
const data = await response.json()
if (!response.ok) throw new Error(data.error || 'Failed to repair OpenShell gateway trust')
setLifecycleMessage(`${data.warning || 'OpenShell gateway trust repaired.'}\nGateway: ${data.gateway}\nBackup: ${data.backupPath}`)
await refresh({ force: true })
} catch (err) {
setLifecycleMessage(err instanceof Error ? err.message : 'Failed to repair OpenShell gateway trust')
} finally {
setGatewayRepairing(false)
}
}
const refreshUntilSandboxVisible = async (sandboxRef: string) => { const refreshUntilSandboxVisible = async (sandboxRef: string) => {
for (let attempt = 0; attempt < 8; attempt += 1) { for (let attempt = 0; attempt < 8; attempt += 1) {
const latest = await refresh({ force: true }) const latest = await refresh({ force: true })
@@ -260,7 +234,7 @@ export default function Dashboard() {
}} }}
/> />
<main className={`${activeView === 'sandboxes' && !isCreateMode ? 'lg:ml-[36rem]' : 'lg:ml-64'} min-h-screen transition-all duration-300 max-lg:ml-0 max-lg:pb-28`}> <main className="ml-64 min-h-screen transition-all duration-300 max-lg:ml-0 max-lg:pb-28">
<div> <div>
<div className="mx-auto max-w-7xl p-8 max-sm:p-4"> <div className="mx-auto max-w-7xl p-8 max-sm:p-4">
{activeView === 'settings' ? ( {activeView === 'settings' ? (
@@ -342,22 +316,6 @@ export default function Dashboard() {
<div className="panel p-8 text-center" data-testid="inventory-error-state"> <div className="panel p-8 text-center" data-testid="inventory-error-state">
<h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3> <h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3>
<p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p> <p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p>
{gatewayTrustError && (
<div className="mx-auto mt-5 max-w-2xl rounded-sm border border-amber-500/40 bg-amber-500/10 p-4 text-left">
<h4 className="text-xs font-semibold uppercase tracking-wider text-amber-300">Gateway Trust Mismatch</h4>
<p className="mt-2 text-xs leading-5 text-amber-100/80">
OpenShell could not use the selected gateway. This usually means the gateway stopped, was undeployed, or regenerated mTLS material while this controller still has stale trust files.
</p>
<button
type="button"
disabled={gatewayRepairing}
onClick={repairGatewayTrust}
className="mt-4 rounded-sm bg-amber-300 px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
>
{gatewayRepairing ? 'Repairing Gateway...' : 'Repair Gateway Trust'}
</button>
</div>
)}
</div> </div>
) : ( ) : (
<SandboxList <SandboxList
@@ -373,7 +331,7 @@ export default function Dashboard() {
</div> </div>
) : ( ) : (
<> <>
<div className="panel mb-6 overflow-hidden"> <div className="panel mb-8 overflow-hidden">
<div className="panel-header flex items-center justify-between gap-4 p-5 max-md:flex-col max-md:items-start"> <div className="panel-header flex items-center justify-between gap-4 p-5 max-md:flex-col max-md:items-start">
<div className="min-w-0"> <div className="min-w-0">
<p className="font-mono text-[10px] uppercase tracking-wider text-[var(--nvidia-green)]"> <p className="font-mono text-[10px] uppercase tracking-wider text-[var(--nvidia-green)]">
@@ -436,22 +394,6 @@ export default function Dashboard() {
<div className="panel p-8 text-center" data-testid="inventory-error-state"> <div className="panel p-8 text-center" data-testid="inventory-error-state">
<h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3> <h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3>
<p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p> <p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p>
{gatewayTrustError && (
<div className="mx-auto mt-5 max-w-2xl rounded-sm border border-amber-500/40 bg-amber-500/10 p-4 text-left">
<h4 className="text-xs font-semibold uppercase tracking-wider text-amber-300">Gateway Trust Mismatch</h4>
<p className="mt-2 text-xs leading-5 text-amber-100/80">
OpenShell could not use the selected gateway. This usually means the gateway stopped, was undeployed, or regenerated mTLS material while this controller still has stale trust files.
</p>
<button
type="button"
disabled={gatewayRepairing}
onClick={repairGatewayTrust}
className="mt-4 rounded-sm bg-amber-300 px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
>
{gatewayRepairing ? 'Repairing Gateway...' : 'Repair Gateway Trust'}
</button>
</div>
)}
</div> </div>
) : sandboxes.length === 0 ? ( ) : sandboxes.length === 0 ? (
<div className="panel p-8 text-center" data-testid="inventory-empty-state"> <div className="panel p-8 text-center" data-testid="inventory-empty-state">
+10 -23
View File
@@ -62,17 +62,11 @@ assert.match(
assert.match(createRouteSource, /"onboard", "--non-interactive", "--recreate-sandbox"/, 'blueprint create must use the Monday-era normal NemoClaw onboard flow') assert.match(createRouteSource, /"onboard", "--non-interactive", "--recreate-sandbox"/, 'blueprint create must use the Monday-era normal NemoClaw onboard flow')
assert.doesNotMatch(createRouteSource, /"--from"|resolvePreferredNemoClawDockerfile|prepareDashboardOwnedNemoClawDockerfile/, 'blueprint create must not force the explicit Dockerfile path') assert.doesNotMatch(createRouteSource, /"--from"|resolvePreferredNemoClawDockerfile|prepareDashboardOwnedNemoClawDockerfile/, 'blueprint create must not force the explicit Dockerfile path')
assert.match(createRouteSource, /NEMOCLAW_SANDBOX_NAME: sandboxName/, 'blueprint create must pass the requested sandbox name to NemoClaw onboarding') assert.match(createRouteSource, /NEMOCLAW_SANDBOX_NAME: sandboxName/, 'blueprint create must pass the requested sandbox name to NemoClaw onboarding')
assert.match(createRouteSource, /NEMOCLAW_EXPERIMENTAL = "1"/, 'blueprint create must support NemoClaw experimental provider onboarding') assert.doesNotMatch(createRouteSource, /NEMOCLAW_EXPERIMENTAL|NEMOCLAW_PROVIDER|NEMOCLAW_PROVIDER_KEY/, 'blueprint create must stay on the Monday-era stock NemoClaw onboarding path')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "vllm"/, 'blueprint create must support the vLLM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER = "nim-local"/, 'blueprint create must support the NVIDIA NIM onboarding provider')
assert.match(createRouteSource, /NEMOCLAW_PROVIDER_KEY = apiKey/, 'blueprint create must pass NVIDIA API keys through provider env without changing NemoClaw')
assert.match(versionedInstallerSource, /OPENCLAW_VERSION="\$\{OPENCLAW_VERSION:-2026\.4\.24\}"/, 'versioned installer must pin the dashboard-compatible NemoClaw OpenClaw version') assert.match(versionedInstallerSource, /OPENCLAW_VERSION="\$\{OPENCLAW_VERSION:-2026\.4\.24\}"/, 'versioned installer must pin the dashboard-compatible NemoClaw OpenClaw version')
assert.match(versionedInstallerSource, /docker build[\s\S]*Dockerfile\.base[\s\S]*--build-arg "OPENCLAW_VERSION=\$OPENCLAW_VERSION"[\s\S]*"\$source_dir"/, 'versioned installer must rebuild the stock NemoClaw base image with the pinned OpenClaw version') assert.match(versionedInstallerSource, /docker build[\s\S]*Dockerfile\.base[\s\S]*--build-arg "OPENCLAW_VERSION=\$OPENCLAW_VERSION"[\s\S]*"\$source_dir"/, 'versioned installer must rebuild the stock NemoClaw base image with the pinned OpenClaw version')
assert.doesNotMatch(createRouteSource, /repairOpenClawRuntimePolicy|runtimePolicyRepair/, 'sandbox create must not mutate OpenShell filesystem policy for OpenClaw') assert.doesNotMatch(createRouteSource, /repairOpenClawRuntimePolicy|runtimePolicyRepair/, 'sandbox create must not mutate OpenShell filesystem policy for OpenClaw')
assert.match(createRouteSource, /stabilizeOpenClawGatewayConfig/, 'sandbox create must stabilize OpenClaw gateway config after readiness') assert.doesNotMatch(createRouteSource, /stabilizeOpenClawGatewayConfig|gatewayConfigRepair|repairOpenClawWorkspacePermissions|workspaceRepair/, 'sandbox create must not patch OpenClaw internals after the Monday rollback')
assert.match(createRouteSource, /gatewayConfigRepair/, 'sandbox create response must report OpenClaw gateway config stabilization status')
assert.match(createRouteSource, /repairOpenClawWorkspacePermissions/, 'sandbox create must repair OpenClaw workspace permissions after readiness')
assert.match(createRouteSource, /workspaceRepair/, 'sandbox create response must report OpenClaw workspace permission repair status')
assert.doesNotMatch(sandboxPrivilegedFilesSource, /openshell-openclaw-policy-|"policy", "set"|withoutReadOnlyOpenClaw/, 'OpenClaw repair must not mutate OpenShell filesystem policy') assert.doesNotMatch(sandboxPrivilegedFilesSource, /openshell-openclaw-policy-|"policy", "set"|withoutReadOnlyOpenClaw/, 'OpenClaw repair must not mutate OpenShell filesystem policy')
assert.match(sandboxPrivilegedFilesSource, /plugins\.entries\.bonjour/, 'gateway config stabilization must disable the crashing Bonjour plugin') assert.match(sandboxPrivilegedFilesSource, /plugins\.entries\.bonjour/, 'gateway config stabilization must disable the crashing Bonjour plugin')
assert.match(sandboxPrivilegedFilesSource, /sha256sum openclaw\.json > \.config-hash/, 'gateway config stabilization must refresh OpenClaw config hash') assert.match(sandboxPrivilegedFilesSource, /sha256sum openclaw\.json > \.config-hash/, 'gateway config stabilization must refresh OpenClaw config hash')
@@ -102,16 +96,15 @@ assert.match(hostCommandsSource, /export const OPENSHELL_BIN[\s\S]*"openshell"/,
assert.match(deleteRouteSource, /\["sandbox", "delete", sandboxName\]/, 'delete route must call openshell sandbox delete with the sandbox name') assert.match(deleteRouteSource, /\["sandbox", "delete", sandboxName\]/, 'delete route must call openshell sandbox delete with the sandbox name')
assert.match(deleteRouteSource, /validateSandboxName/, 'delete route must validate sandbox names before execution') assert.match(deleteRouteSource, /validateSandboxName/, 'delete route must validate sandbox names before execution')
assert.match(deleteRouteSource, /resolveSandboxRef/, 'delete route must resolve sandbox ids to names before deleting') assert.match(deleteRouteSource, /resolveSandboxRef/, 'delete route must resolve sandbox ids to names before deleting')
assert.match(deleteRouteSource, /hostCommandEnv\(\{[\s\S]*OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must use the NemoClaw gateway context with the shared host command environment') assert.match(deleteRouteSource, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must use the NemoClaw gateway context')
assert.match(hostCommandsSource, /export function hostCommandEnv/, 'host commands must provide a shared environment for OpenShell child processes') assert.match(hostCommandsSource, /export function hostCommandEnv/, 'host commands must provide a shared environment for OpenShell child processes')
assert.match(hostCommandsSource, /XDG_CONFIG_HOME/, 'shared host command environment must preserve the OpenShell config home') assert.match(hostCommandsSource, /XDG_CONFIG_HOME/, 'shared host command environment must preserve the OpenShell config home')
assert.match(deleteRouteSource, /waitForSandboxDeleted/, 'delete route must poll authoritative inventory until the sandbox is gone') assert.match(deleteRouteSource, /waitForSandboxDeleted/, 'delete route must poll authoritative inventory until the sandbox is gone')
assert.match(deleteRouteSource, /cleanupNemoClawSandbox/, 'delete route must clean up NemoClaw registry state after deleting from OpenShell') assert.match(deleteRouteSource, /cleanupNemoClawSandbox/, 'delete route must clean up NemoClaw registry state after deleting from OpenShell')
assert.doesNotMatch(deleteRouteSource, /\[sandboxName, "destroy", "--yes"\]|gateway", "destroy"|cleanupGatewayAfterLastSandbox/, 'delete route must not run NemoClaw destroy or destroy the shared gateway when deleting the last sandbox') assert.match(deleteRouteSource, /\[sandboxName, "destroy", "--yes"\]/, 'delete route must match the Monday-era NemoClaw destroy cleanup path')
assert.match(deleteRouteSource, /Pruned NemoClaw registry entry without destroying the shared OpenShell gateway/, 'delete route must prune registry state without tearing down the shared gateway') assert.doesNotMatch(deleteRouteSource, /Pruned NemoClaw registry entry without destroying the shared OpenShell gateway|cleanupGatewayAfterLastSandbox/, 'delete route must not include the later registry-prune rewrite')
assert.match(deleteRouteSource, /openShellAlreadyGone/, 'delete route must tolerate sandboxes that OpenShell already deleted while NemoClaw still has registry state') assert.match(deleteRouteSource, /openShellAlreadyGone/, 'delete route must tolerate sandboxes that OpenShell already deleted while NemoClaw still has registry state')
assert.match(deleteRouteSource, /isGatewayRecoverable/, 'delete route must detect recoverable OpenShell gateway failures') assert.doesNotMatch(deleteRouteSource, /isGatewayRecoverable|recoverableGateway/, 'delete route must not include the later gateway-repair branching')
assert.match(deleteRouteSource, /recoverableGateway/, 'delete failures must tell the UI when gateway repair can recover the operation')
assert.match(telemetryRouteSource, /const names = parseOpenShellSandboxNames\(sandboxListStdout\)/, 'telemetry must derive inventory from OpenShell before consulting NemoClaw') assert.match(telemetryRouteSource, /const names = parseOpenShellSandboxNames\(sandboxListStdout\)/, 'telemetry must derive inventory from OpenShell before consulting NemoClaw')
assert.match(telemetryRouteSource, /names\.length > 0[\s\S]*execNemoclaw\(\["list"\]\)[\s\S]*execNemoclaw\(\["status"\]\)/, 'telemetry must skip NemoClaw list/status when OpenShell reports zero live sandboxes') assert.match(telemetryRouteSource, /names\.length > 0[\s\S]*execNemoclaw\(\["list"\]\)[\s\S]*execNemoclaw\(\["status"\]\)/, 'telemetry must skip NemoClaw list/status when OpenShell reports zero live sandboxes')
assert.match(inferenceRouteSource, /\["provider", "create", "--name", name, "--type", type\]/, 'inference route must create OpenShell providers') assert.match(inferenceRouteSource, /\["provider", "create", "--name", name, "--type", type\]/, 'inference route must create OpenShell providers')
@@ -157,17 +150,13 @@ assert.match(sandboxInferenceApplyLibSource, /providerKey: "nvidia"[\s\S]*modelR
assert.doesNotMatch(sandboxRestartRouteSource, /delete", "pod"|kubectl delete/, 'restart route must not delete the backing sandbox pod') assert.doesNotMatch(sandboxRestartRouteSource, /delete", "pod"|kubectl delete/, 'restart route must not delete the backing sandbox pod')
assert.match(sandboxRestartRouteSource, /restartMode: "openclaw-runtime"/, 'restart route must restart only the in-sandbox OpenClaw runtime') assert.match(sandboxRestartRouteSource, /restartMode: "openclaw-runtime"/, 'restart route must restart only the in-sandbox OpenClaw runtime')
assert.match(sandboxRestartRouteSource, /waitForSandboxReady\(sandboxName, 15000, 1000\)/, 'restart route must verify OpenShell reports the sandbox ready before runtime restart') assert.match(sandboxRestartRouteSource, /waitForSandboxReady\(sandboxName, 15000, 1000\)/, 'restart route must verify OpenShell reports the sandbox ready before runtime restart')
assert.match(sandboxListSource, /Restart OpenClaw Runtime/, 'sandbox details must expose a scoped runtime restart button') assert.match(sandboxListSource, /Restart Sandbox/, 'sandbox details must expose the Monday-era sandbox restart button')
assert.match(sandboxListSource, /\/api\/sandbox\/\$\{encodeURIComponent\(selectedSandbox\.id\)\}\/restart/, 'restart button must call the sandbox restart endpoint') assert.match(sandboxListSource, /\/api\/sandbox\/\$\{encodeURIComponent\(selectedSandbox\.id\)\}\/restart/, 'restart button must call the sandbox restart endpoint')
assert.match(gatewayRepairRouteSource, /gateway", "start", "--name", gateway/, 'gateway repair route must restart the selected OpenShell gateway') assert.match(gatewayRepairRouteSource, /gateway", "start", "--name", gateway/, 'gateway repair route must restart the selected OpenShell gateway')
assert.match(gatewayRepairRouteSource, /backupOpenShellConfig/, 'gateway repair route must back up OpenShell config before repair') assert.match(gatewayRepairRouteSource, /backupOpenShellConfig/, 'gateway repair route must back up OpenShell config before repair')
assert.match(gatewayRepairRouteSource, /\["sandbox", "list"\]/, 'gateway repair route must verify sandbox inventory after repair') assert.match(gatewayRepairRouteSource, /\["sandbox", "list"\]/, 'gateway repair route must verify sandbox inventory after repair')
assert.match(pageSource, /BadSignature\|invalid peer certificate\|transport error\|certificate signature\|Unknown gateway\|Deploy it first\|Connection refused\|tcp connect error/, 'dashboard must detect gateway certificate and availability failures') assert.doesNotMatch(pageSource, /Repair Gateway Trust|api\/openshell\/gateway\/repair|It does not destroy sandboxes/, 'dashboard page must not include the later gateway trust repair UI after rollback')
assert.match(pageSource, /Repair Gateway Trust/, 'inventory error UI must expose a guarded gateway trust repair button') assert.match(sandboxListSource, /setInterval\(loadPermissionFeeds/, 'sandbox list must match the Monday-era permission feed polling behavior')
assert.match(pageSource, /api\/openshell\/gateway\/repair/, 'gateway trust repair button must call the repair endpoint')
assert.match(pageSource, /It does not destroy sandboxes/, 'gateway trust repair warning must clarify sandboxes are not destroyed')
assert.doesNotMatch(sandboxListSource, /setInterval\(loadPermissionFeeds/, 'sandbox list must not poll every sandbox permission feed')
assert.match(sandboxListSource, /loadPermissionFeed\(selectedSandbox\)/, 'policy drawer must load the selected sandbox permission feed on demand')
assert.match(sandboxListSource, /<SandboxInferencePanel sandbox=\{selectedSandbox\}/, 'sandbox list must render the per-sandbox inference profile panel for the selected sandbox') assert.match(sandboxListSource, /<SandboxInferencePanel sandbox=\{selectedSandbox\}/, 'sandbox list must render the per-sandbox inference profile panel for the selected sandbox')
assert.match(sidebarSource, />Inference</, 'sidebar settings item must expose inference settings') assert.match(sidebarSource, />Inference</, 'sidebar settings item must expose inference settings')
assert.match(pageSource, /<InferenceEndpointPanel \/>/, 'settings view must render inference endpoint panel') assert.match(pageSource, /<InferenceEndpointPanel \/>/, 'settings view must render inference endpoint panel')
@@ -183,8 +172,6 @@ assert.match(
) )
assert.doesNotMatch(pageSource, /console\.log\('Destroying sandbox:'/, 'destroy workflow must not be a UI-only placeholder') assert.doesNotMatch(pageSource, /console\.log\('Destroying sandbox:'/, 'destroy workflow must not be a UI-only placeholder')
assert.doesNotMatch(configPanelSource, /onInventoryRefresh/, 'create panel must leave post-create inventory orchestration to the parent') assert.doesNotMatch(configPanelSource, /onInventoryRefresh/, 'create panel must leave post-create inventory orchestration to the parent')
assert.match(configPanelSource, /Use vLLM in experimental mode/, 'create panel must expose vLLM experimental onboarding') assert.doesNotMatch(configPanelSource, /Use vLLM in experimental mode|Use NVIDIA NIM|createInference/, 'create panel must not include later create-time inference controls after rollback')
assert.match(configPanelSource, /Use NVIDIA NIM/, 'create panel must expose NVIDIA NIM onboarding')
assert.match(configPanelSource, /createInference/, 'create panel must send create-time inference settings')
console.log('sandbox-lifecycle-check: PASS create/destroy lifecycle assertions') console.log('sandbox-lifecycle-check: PASS create/destroy lifecycle assertions')