diff --git a/app/api/sandbox/delete/route.ts b/app/api/sandbox/delete/route.ts index a7f1f8b..95b9f62 100644 --- a/app/api/sandbox/delete/route.ts +++ b/app/api/sandbox/delete/route.ts @@ -6,6 +6,57 @@ import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands" const execFileAsync = promisify(execFile) +const PERSISTENT_STATE_TARGETS: Record = { + 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) { return Date.now() - start } @@ -29,13 +80,19 @@ function parseDeleteTarget(body: any) { 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 { const sandbox = await resolveSandboxRef(ref) return { requested: ref, sandboxName: validateSandboxName(sandbox.name), sandboxId: sandbox.id, + agent, resolved: true, } } catch (error) { @@ -43,6 +100,7 @@ async function resolveDeleteTarget(ref: string) { requested: ref, sandboxName: validateSandboxName(ref), sandboxId: null, + agent: "openclaw", resolved: false, 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) { 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") try { 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 deleteOutput = [result.error, result.stdout, result.stderr].filter(Boolean).join("\n") const openShellAlreadyGone = !result.ok && isSandboxNotFound(deleteOutput) @@ -137,6 +238,7 @@ export async function POST(request: Request) { sandboxId: target.sandboxId, resolved: target.resolved, resolveError: target.resolveError, + stateWipe, error: result.error, stdout: result.stdout, stderr: result.stderr, @@ -156,6 +258,7 @@ export async function POST(request: Request) { stdout: result.stdout, stderr: result.stderr, openShellAlreadyGone, + stateWipe, openShell: result, deletion, note: deleted ? "Sandbox delete completed." : "Sandbox delete command completed, but inventory still reports the sandbox.", diff --git a/app/page.tsx b/app/page.tsx index 7be4f76..a79f88c 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -147,7 +147,7 @@ export default function Dashboard() { const response = await fetch('/api/sandbox/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ sandboxName }), + body: JSON.stringify({ sandboxName, agent: sandbox?.agent || 'openclaw' }), }) 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') diff --git a/tests/sandbox-lifecycle-check.mjs b/tests/sandbox-lifecycle-check.mjs index d2df896..8ec8bfc 100644 --- a/tests/sandbox-lifecycle-check.mjs +++ b/tests/sandbox-lifecycle-check.mjs @@ -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(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, /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, /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')