From 5c357af7ce4cdf4eb677f681f3bc21691628df93 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 24 Apr 2026 15:49:58 +0000 Subject: [PATCH] Fix sandbox lifecycle workflows --- app/api/sandbox/create/route.ts | 17 ++++- app/api/sandbox/delete/route.ts | 96 +++++++++++++++++++++++++++ app/components/ConfigurationPanel.tsx | 6 +- app/components/SandboxList.tsx | 2 +- app/hooks/useSandboxInventory.ts | 36 +++++++--- app/page.tsx | 80 ++++++++++++++++++---- tests/sandbox-lifecycle-check.mjs | 43 ++++++++++++ 7 files changed, 249 insertions(+), 31 deletions(-) create mode 100644 app/api/sandbox/delete/route.ts create mode 100644 tests/sandbox-lifecycle-check.mjs diff --git a/app/api/sandbox/create/route.ts b/app/api/sandbox/create/route.ts index 58a9694..431d084 100644 --- a/app/api/sandbox/create/route.ts +++ b/app/api/sandbox/create/route.ts @@ -299,9 +299,16 @@ export async function POST(request: Request) { }, { status: 500 }) } - const verification = await verifySandboxCreation(sandboxName) - const created = verification.verified - console.log(`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} elapsedMs=${elapsedMs(requestStartedAt)}`) + const readiness = await waitForSandboxReady(sandboxName, 90000, 2000) + const verification = readiness.verification ?? { + verified: false, + summary: "Sandbox readiness polling produced no verification result.", + error: "Sandbox readiness polling produced no verification result.", + } + const created = readiness.verified + console.log( + `[sandbox/create] request:complete sandbox=${sandboxName} created=${created} readinessAttempts=${readiness.attempts} elapsedMs=${elapsedMs(requestStartedAt)}`, + ) return NextResponse.json({ ok: created, @@ -314,6 +321,10 @@ export async function POST(request: Request) { enableTailscale, setupPath: NEMOCLAW_SETUP, hostPath: HOST_PATH, + readiness: { + attempts: readiness.attempts, + elapsedMs: readiness.elapsedMs, + }, stdout: result.stdout, stderr: result.stderr, note: created diff --git a/app/api/sandbox/delete/route.ts b/app/api/sandbox/delete/route.ts new file mode 100644 index 0000000..7eff773 --- /dev/null +++ b/app/api/sandbox/delete/route.ts @@ -0,0 +1,96 @@ +import { NextResponse } from "next/server" +import { execFile } from "node:child_process" +import { promisify } from "node:util" + +const execFileAsync = promisify(execFile) +const HOME = process.env.HOME || "" +const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell` +const HOST_PATH = [ + `${HOME}/.local/bin`, + `${HOME}/.nvm/versions/node/v22.22.2/bin`, + `${HOME}/.nvm/versions/node/v22.22.1/bin`, + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + "/bin", + "/usr/sbin", + "/sbin", + process.env.PATH || "", +].filter(Boolean).join(":") + +function elapsedMs(start: number) { + return Date.now() - start +} + +function validateSandboxName(name: string) { + if (!name || typeof name !== "string") throw new Error("sandbox name is required") + if (name.length > 63) throw new Error("sandbox name too long (max 63 chars)") + if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) { + throw new Error("sandbox name must be lowercase alphanumeric with optional internal hyphens") + } + return name +} + +async function deleteSandbox(sandboxName: string) { + const startedAt = Date.now() + console.log(`[sandbox/delete] command:start sandbox=${sandboxName}`) + try { + const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, ["sandbox", "delete", sandboxName], { + env: { + ...process.env, + PATH: HOST_PATH, + NO_COLOR: "1", + CLICOLOR: "0", + CLICOLOR_FORCE: "0", + }, + maxBuffer: 20 * 1024 * 1024, + }) + console.log(`[sandbox/delete] command: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 ?? "Sandbox delete failed") + console.log(`[sandbox/delete] command:error sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`) + return { + ok: false as const, + stdout: String(error?.stdout || "").trim(), + stderr: String(error?.stderr || "").trim(), + error: message, + } + } +} + +export async function POST(request: Request) { + const startedAt = Date.now() + console.log("[sandbox/delete] request:start") + try { + const body = await request.json() + const sandboxName = validateSandboxName( + typeof body?.sandboxName === "string" ? body.sandboxName.trim() : typeof body?.sandboxId === "string" ? body.sandboxId.trim() : "", + ) + const result = await deleteSandbox(sandboxName) + if (!result.ok) { + return NextResponse.json({ + ok: false, + deleted: false, + sandboxName, + error: result.error, + stdout: result.stdout, + stderr: result.stderr, + }, { status: 500 }) + } + + console.log(`[sandbox/delete] request:complete sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)}`) + return NextResponse.json({ + ok: true, + deleted: true, + sandboxName, + stdout: result.stdout, + stderr: result.stderr, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Sandbox delete failed" + const status = /required|must be|too long/.test(message) ? 400 : 500 + console.log(`[sandbox/delete] request:error elapsedMs=${elapsedMs(startedAt)} message=${message}`) + return NextResponse.json({ ok: false, deleted: false, error: message }, { status }) + } +} diff --git a/app/components/ConfigurationPanel.tsx b/app/components/ConfigurationPanel.tsx index 9788115..18b6c89 100644 --- a/app/components/ConfigurationPanel.tsx +++ b/app/components/ConfigurationPanel.tsx @@ -27,7 +27,6 @@ interface ConfigurationPanelProps { sandboxId: string mode?: 'existing' | 'create' onCreateSuccess?: (sandboxId: string) => void | Promise - onInventoryRefresh?: () => Promise } function FieldHelp({ text }: { text: string }) { @@ -75,7 +74,7 @@ function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_ return out } -export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess, onInventoryRefresh }: ConfigurationPanelProps) { +export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess }: ConfigurationPanelProps) { const [policy, setPolicy] = useState(defaultPolicy) const [blocks, setBlocks] = useState([]) const [loading, setLoading] = useState(mode === 'existing') @@ -132,9 +131,6 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre 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')) const createdSandboxId = data.verification?.details?.id || data.verification?.details?.name || data.sandboxName - if (onInventoryRefresh) { - await onInventoryRefresh() - } setMessage([ `Sandbox '${data.sandboxName}' created.`, data.verification?.summary, diff --git a/app/components/SandboxList.tsx b/app/components/SandboxList.tsx index be79026..9da691a 100644 --- a/app/components/SandboxList.tsx +++ b/app/components/SandboxList.tsx @@ -240,7 +240,7 @@ export default function SandboxList({ - + )} diff --git a/app/hooks/useSandboxInventory.ts b/app/hooks/useSandboxInventory.ts index cd2b877..751ca2b 100644 --- a/app/hooks/useSandboxInventory.ts +++ b/app/hooks/useSandboxInventory.ts @@ -27,6 +27,10 @@ interface InventoryResponse { nemoclaw?: NemoClawSummary | null } +type RefreshOptions = { + force?: boolean +} + function normalizeStatus(status: unknown): SandboxInventoryItem['status'] { const value = typeof status === 'string' ? status.toLowerCase() : 'unknown' if (value === 'running' || value === 'pending' || value === 'stopped' || value === 'error') return value @@ -79,12 +83,16 @@ export function useSandboxInventory(options?: { enabled?: boolean; refreshInterv const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const inFlightRef = useRef | null>(null) + const requestIdRef = useRef(0) - const refresh = useCallback(async () => { - if (inFlightRef.current) { + const refresh = useCallback(async (refreshOptions?: RefreshOptions) => { + if (!refreshOptions?.force && inFlightRef.current) { return inFlightRef.current } + const requestId = requestIdRef.current + 1 + requestIdRef.current = requestId + const run = (async () => { try { const response = await fetch('/api/telemetry/real', { cache: 'no-store' }) @@ -92,19 +100,27 @@ export function useSandboxInventory(options?: { enabled?: boolean; refreshInterv if (!response.ok) throw new Error(data.error || 'Failed to fetch sandbox inventory') const nextSandboxes = normalizeFromResponse(data) - setSandboxes(nextSandboxes) - setNemoclaw(data?.nemoclaw ?? null) - setError(null) + if (requestId === requestIdRef.current) { + setSandboxes(nextSandboxes) + setNemoclaw(data?.nemoclaw ?? null) + setError(null) + } return nextSandboxes } catch (err) { const message = err instanceof Error ? err.message : 'Failed to fetch sandbox inventory' - setSandboxes([]) - setNemoclaw(null) - setError(message) + if (requestId === requestIdRef.current) { + setSandboxes([]) + setNemoclaw(null) + setError(message) + } throw err } finally { - setLoading(false) - inFlightRef.current = null + if (requestId === requestIdRef.current) { + setLoading(false) + } + if (requestId === requestIdRef.current) { + inFlightRef.current = null + } } })() diff --git a/app/page.tsx b/app/page.tsx index ff2969b..a901617 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -19,6 +19,8 @@ export default function Dashboard() { const [activeView, setActiveView] = useState<'settings' | 'sandboxes'>('sandboxes') const [deletingSandboxId, setDeletingSandboxId] = useState(null) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) + const [lifecycleMessage, setLifecycleMessage] = useState(null) + const [deleteInProgress, setDeleteInProgress] = useState(false) const inventoryEnabled = activeView === 'sandboxes' || isCreateMode || isDestroyMode const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ enabled: inventoryEnabled, @@ -40,6 +42,10 @@ export default function Dashboard() { () => sandboxes.find((sandbox) => sandbox.id === dashboardSession.selectedSandboxId) ?? null, [sandboxes, dashboardSession.selectedSandboxId] ) + const deletingSandbox = useMemo( + () => sandboxes.find((sandbox) => sandbox.id === deletingSandboxId) ?? null, + [sandboxes, deletingSandboxId] + ) const toggleTheme = () => { setTheme(theme === 'light' ? 'dark' : 'light') @@ -58,20 +64,56 @@ export default function Dashboard() { setDashboardSession((current) => updateDashboardSessionSelection(current, null)) } + const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms)) + + const refreshUntilSandboxVisible = async (sandboxRef: string) => { + for (let attempt = 0; attempt < 8; attempt += 1) { + const latest = await refresh({ force: true }) + const sandbox = latest.find((item) => item.id === sandboxRef || item.name === sandboxRef) + if (sandbox) return sandbox + await sleep(1500) + } + return null + } + const handleCreateSuccess = async (createdSandboxId: string) => { setIsCreateMode(false) setIsDestroyMode(false) setActiveView('sandboxes') - const latest = await refresh() - const created = latest.find((sandbox) => sandbox.id === createdSandboxId || sandbox.name === createdSandboxId) - setDashboardSession((current) => updateDashboardSessionSelection(current, created?.id ?? createdSandboxId)) + setLifecycleMessage(`Refreshing inventory for ${createdSandboxId}...`) + const created = await refreshUntilSandboxVisible(createdSandboxId) + setLifecycleMessage(created ? `Sandbox ${created.name} is ready.` : `Sandbox ${createdSandboxId} was created, but inventory has not reported it yet.`) + setDashboardSession((current) => updateDashboardSessionSelection(current, created?.id ?? null)) } - const confirmDelete = () => { - console.log('Destroying sandbox:', deletingSandboxId) - setShowDeleteConfirm(false) - setDeletingSandboxId(null) - setIsDestroyMode(false) + const confirmDelete = async () => { + if (!deletingSandboxId || deleteInProgress) return + const sandbox = sandboxes.find((item) => item.id === deletingSandboxId) + const sandboxName = sandbox?.name ?? deletingSandboxId + + try { + setDeleteInProgress(true) + setLifecycleMessage(`Destroying sandbox ${sandboxName}...`) + const response = await fetch('/api/sandbox/delete', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ sandboxName }), + }) + 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') + + const latest = await refresh({ force: true }) + const stillPresent = latest.find((item) => item.id === deletingSandboxId || item.name === sandboxName) + setDashboardSession((current) => updateDashboardSessionSelection(current, current.selectedSandboxId === deletingSandboxId ? null : current.selectedSandboxId)) + setLifecycleMessage(stillPresent ? `Delete started for ${sandboxName}. Inventory still reports it while cleanup finishes.` : `Sandbox ${sandboxName} destroyed.`) + setShowDeleteConfirm(false) + setDeletingSandboxId(null) + setIsDestroyMode(false) + } catch (err) { + setLifecycleMessage(err instanceof Error ? err.message : 'Failed to destroy sandbox') + } finally { + setDeleteInProgress(false) + } } const cancelDelete = () => { @@ -103,11 +145,13 @@ export default function Dashboard() { setIsCreateMode(true) setIsDestroyMode(false) clearSelection() + setLifecycleMessage(null) }} onDestroyClick={() => { setActiveView('sandboxes') setIsDestroyMode(true) setIsCreateMode(false) + setLifecycleMessage(null) }} onSettingsClick={() => { setActiveView('settings') @@ -157,7 +201,7 @@ export default function Dashboard() { Choose a blueprint, name the sandbox, and create it.

- + ) : isDestroyMode ? (
@@ -198,6 +242,12 @@ export default function Dashboard() {
+ {lifecycleMessage && ( +
+ {lifecycleMessage} +
+ )} + {inventoryEnabled && loading ? (
@@ -249,14 +299,20 @@ export default function Dashboard() {

- Destroying this sandbox will permanently delete it and it will not be recoverable. Are you sure? + Destroying {deletingSandbox?.name ?? 'this sandbox'} will permanently delete it and it will not be recoverable. Are you sure?

+ {lifecycleMessage && ( +
+ {lifecycleMessage} +
+ )}