fix: wipe NemoClaw sandbox state before delete (#26)
Co-authored-by: Mark Mckeen <markmckeen@Marks-Mac-mini.local>
This commit is contained in:
co-authored by
Mark Mckeen
parent
722a7b08a1
commit
1b5752793c
@@ -6,6 +6,57 @@ import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
|
|||||||
|
|
||||||
const execFileAsync = promisify(execFile)
|
const execFileAsync = promisify(execFile)
|
||||||
|
|
||||||
|
const PERSISTENT_STATE_TARGETS: Record<string, { dir: string; targets: string[] }> = {
|
||||||
|
openclaw: {
|
||||||
|
dir: "/sandbox/.openclaw",
|
||||||
|
targets: [
|
||||||
|
"agents",
|
||||||
|
"extensions",
|
||||||
|
"workspace",
|
||||||
|
"skills",
|
||||||
|
"hooks",
|
||||||
|
"identity",
|
||||||
|
"devices",
|
||||||
|
"canvas",
|
||||||
|
"cron",
|
||||||
|
"memory",
|
||||||
|
"telegram",
|
||||||
|
"wechat",
|
||||||
|
"whatsapp",
|
||||||
|
"credentials",
|
||||||
|
"openclaw.json",
|
||||||
|
"workspace-*",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
hermes: {
|
||||||
|
dir: "/sandbox/.hermes",
|
||||||
|
targets: [
|
||||||
|
"memories",
|
||||||
|
"sessions",
|
||||||
|
"skills",
|
||||||
|
"plugins",
|
||||||
|
"cron",
|
||||||
|
"logs",
|
||||||
|
"skins",
|
||||||
|
"plans",
|
||||||
|
"workspace",
|
||||||
|
"profiles",
|
||||||
|
"cache",
|
||||||
|
"pairing",
|
||||||
|
"platforms",
|
||||||
|
"weixin",
|
||||||
|
"SOUL.md",
|
||||||
|
".hermes_history",
|
||||||
|
"runtime/state.db",
|
||||||
|
"workspace-*",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
"langchain-deepagents-code": {
|
||||||
|
dir: "/sandbox/.deepagents",
|
||||||
|
targets: [".state", "skills", "agent/skills", "config.toml", "hooks.json", "workspace-*"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
function elapsedMs(start: number) {
|
function elapsedMs(start: number) {
|
||||||
return Date.now() - start
|
return Date.now() - start
|
||||||
}
|
}
|
||||||
@@ -29,13 +80,19 @@ function parseDeleteTarget(body: any) {
|
|||||||
return raw
|
return raw
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolveDeleteTarget(ref: string) {
|
function parseDeleteAgent(body: any) {
|
||||||
|
const raw = typeof body?.agent === "string" ? body.agent.trim() : "openclaw"
|
||||||
|
return PERSISTENT_STATE_TARGETS[raw] ? raw : "openclaw"
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveDeleteTarget(ref: string, agent: string) {
|
||||||
try {
|
try {
|
||||||
const sandbox = await resolveSandboxRef(ref)
|
const sandbox = await resolveSandboxRef(ref)
|
||||||
return {
|
return {
|
||||||
requested: ref,
|
requested: ref,
|
||||||
sandboxName: validateSandboxName(sandbox.name),
|
sandboxName: validateSandboxName(sandbox.name),
|
||||||
sandboxId: sandbox.id,
|
sandboxId: sandbox.id,
|
||||||
|
agent,
|
||||||
resolved: true,
|
resolved: true,
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -43,6 +100,7 @@ async function resolveDeleteTarget(ref: string) {
|
|||||||
requested: ref,
|
requested: ref,
|
||||||
sandboxName: validateSandboxName(ref),
|
sandboxName: validateSandboxName(ref),
|
||||||
sandboxId: null,
|
sandboxId: null,
|
||||||
|
agent: "openclaw",
|
||||||
resolved: false,
|
resolved: false,
|
||||||
resolveError: error instanceof Error ? error.message : String(error ?? "Sandbox lookup failed"),
|
resolveError: error instanceof Error ? error.message : String(error ?? "Sandbox lookup failed"),
|
||||||
}
|
}
|
||||||
@@ -74,6 +132,48 @@ async function deleteSandbox(sandboxName: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function shellQuote(value: string) {
|
||||||
|
return `'${value.replace(/'/g, `'"'"'`)}'`
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSafeManifestRelativePath(value: string) {
|
||||||
|
return Boolean(value) && !value.startsWith("/") && !value.split("/").includes("..")
|
||||||
|
}
|
||||||
|
|
||||||
|
async function wipePersistentSandboxState(sandboxName: string, agent: string | null | undefined) {
|
||||||
|
const agentName = agent || "openclaw"
|
||||||
|
const contract = PERSISTENT_STATE_TARGETS[agentName] || PERSISTENT_STATE_TARGETS.openclaw
|
||||||
|
const targets = contract.targets.filter(isSafeManifestRelativePath)
|
||||||
|
if (targets.length === 0) return { ok: true as const, skipped: true as const, reason: "no safe state targets" }
|
||||||
|
|
||||||
|
const startedAt = Date.now()
|
||||||
|
const script = `cd ${shellQuote(contract.dir)} 2>/dev/null || exit 0; rm -rf -- ${targets
|
||||||
|
.map((target) => (target === "workspace-*" ? target : shellQuote(target)))
|
||||||
|
.join(" ")}`
|
||||||
|
console.log(`[sandbox/delete] state-wipe:start sandbox=${sandboxName} agent=${agentName}`)
|
||||||
|
try {
|
||||||
|
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
|
||||||
|
env: hostCommandEnv({
|
||||||
|
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
|
||||||
|
}),
|
||||||
|
timeout: 30000,
|
||||||
|
maxBuffer: 1024 * 1024,
|
||||||
|
})
|
||||||
|
console.log(`[sandbox/delete] state-wipe: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 ?? "Persistent state wipe failed")
|
||||||
|
console.warn(`[sandbox/delete] state-wipe:warning sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||||
|
return {
|
||||||
|
ok: false as const,
|
||||||
|
stdout: String(error?.stdout || "").trim(),
|
||||||
|
stderr: String(error?.stderr || "").trim(),
|
||||||
|
error: message,
|
||||||
|
warning: "Could not wipe persistent sandbox state before delete; re-onboarding with the same name may resurface old files.",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function isSandboxNotFound(output: string) {
|
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)
|
||||||
}
|
}
|
||||||
@@ -123,7 +223,8 @@ export async function POST(request: Request) {
|
|||||||
console.log("[sandbox/delete] request:start")
|
console.log("[sandbox/delete] request:start")
|
||||||
try {
|
try {
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const target = await resolveDeleteTarget(parseDeleteTarget(body))
|
const target = await resolveDeleteTarget(parseDeleteTarget(body), parseDeleteAgent(body))
|
||||||
|
const stateWipe = await wipePersistentSandboxState(target.sandboxName, target.agent)
|
||||||
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)
|
||||||
@@ -137,6 +238,7 @@ export async function POST(request: Request) {
|
|||||||
sandboxId: target.sandboxId,
|
sandboxId: target.sandboxId,
|
||||||
resolved: target.resolved,
|
resolved: target.resolved,
|
||||||
resolveError: target.resolveError,
|
resolveError: target.resolveError,
|
||||||
|
stateWipe,
|
||||||
error: result.error,
|
error: result.error,
|
||||||
stdout: result.stdout,
|
stdout: result.stdout,
|
||||||
stderr: result.stderr,
|
stderr: result.stderr,
|
||||||
@@ -156,6 +258,7 @@ export async function POST(request: Request) {
|
|||||||
stdout: result.stdout,
|
stdout: result.stdout,
|
||||||
stderr: result.stderr,
|
stderr: result.stderr,
|
||||||
openShellAlreadyGone,
|
openShellAlreadyGone,
|
||||||
|
stateWipe,
|
||||||
openShell: result,
|
openShell: result,
|
||||||
deletion,
|
deletion,
|
||||||
note: deleted ? "Sandbox delete completed." : "Sandbox delete command completed, but inventory still reports the sandbox.",
|
note: deleted ? "Sandbox delete completed." : "Sandbox delete command completed, but inventory still reports the sandbox.",
|
||||||
|
|||||||
+1
-1
@@ -147,7 +147,7 @@ export default function Dashboard() {
|
|||||||
const response = await fetch('/api/sandbox/delete', {
|
const response = await fetch('/api/sandbox/delete', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ sandboxName }),
|
body: JSON.stringify({ sandboxName, agent: sandbox?.agent || 'openclaw' }),
|
||||||
})
|
})
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
if (!response.ok) throw new Error([data.error, data.stdout, data.stderr].filter(Boolean).join('\n\n') || 'Failed to destroy sandbox')
|
if (!response.ok) throw new Error([data.error, data.stdout, data.stderr].filter(Boolean).join('\n\n') || 'Failed to destroy sandbox')
|
||||||
|
|||||||
@@ -154,6 +154,10 @@ assert.match(hookSource, /requestIdRef = useRef\(0\)/, 'inventory refresh must g
|
|||||||
assert.match(deleteRouteSource, /OPENSHELL_BIN/, 'delete route must use the shared OpenShell CLI resolver')
|
assert.match(deleteRouteSource, /OPENSHELL_BIN/, 'delete route must use the shared OpenShell CLI resolver')
|
||||||
assert.match(hostCommandsSource, /export const OPENSHELL_BIN[\s\S]*"openshell"/, 'shared command resolver must fall back to the OpenShell CLI')
|
assert.match(hostCommandsSource, /export const OPENSHELL_BIN[\s\S]*"openshell"/, 'shared command resolver must fall back to the OpenShell CLI')
|
||||||
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, /wipePersistentSandboxState/, 'delete route must best-effort wipe NemoClaw persistent state before OpenShell deletion')
|
||||||
|
assert.match(deleteRouteSource, /\["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script\]/, 'persistent state wipe must run inside the target sandbox before deletion')
|
||||||
|
assert.match(deleteRouteSource, /workspace-\*/, 'persistent state wipe must include NemoClaw multi-agent workspace globs')
|
||||||
|
assert.match(pageSource, /JSON\.stringify\(\{ sandboxName, agent: sandbox\?\.agent \|\| 'openclaw' \}\)/, 'destroy workflow must pass the selected NemoClaw agent to delete state cleanup')
|
||||||
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, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must use the NemoClaw gateway context')
|
assert.match(deleteRouteSource, /OPENSHELL_GATEWAY: process\.env\.OPENSHELL_GATEWAY \|\| "nemoclaw"/, 'delete route must use the NemoClaw gateway context')
|
||||||
|
|||||||
Reference in New Issue
Block a user