Fix sandbox lifecycle workflows
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ interface ConfigurationPanelProps {
|
||||
sandboxId: string
|
||||
mode?: 'existing' | 'create'
|
||||
onCreateSuccess?: (sandboxId: string) => void | Promise<void>
|
||||
onInventoryRefresh?: () => Promise<unknown>
|
||||
}
|
||||
|
||||
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<OpenShellPolicy>(defaultPolicy)
|
||||
const [blocks, setBlocks] = useState<NetworkPolicyBlock[]>([])
|
||||
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,
|
||||
|
||||
@@ -240,7 +240,7 @@ export default function SandboxList({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" onInventoryRefresh={onInventoryRefresh} />
|
||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -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<string | null>(null)
|
||||
const inFlightRef = useRef<Promise<SandboxInventoryItem[]> | 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
|
||||
}
|
||||
}
|
||||
})()
|
||||
|
||||
|
||||
+68
-12
@@ -19,6 +19,8 @@ export default function Dashboard() {
|
||||
const [activeView, setActiveView] = useState<'settings' | 'sandboxes'>('sandboxes')
|
||||
const [deletingSandboxId, setDeletingSandboxId] = useState<string | null>(null)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const [lifecycleMessage, setLifecycleMessage] = useState<string | null>(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.
|
||||
</p>
|
||||
</div>
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" onCreateSuccess={handleCreateSuccess} onInventoryRefresh={refresh} />
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" onCreateSuccess={handleCreateSuccess} />
|
||||
</div>
|
||||
) : isDestroyMode ? (
|
||||
<div className="panel p-8 border-2 border-[var(--status-stopped)]">
|
||||
@@ -198,6 +242,12 @@ export default function Dashboard() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{lifecycleMessage && (
|
||||
<div className="panel mb-6 p-4 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap" data-testid="sandbox-lifecycle-message">
|
||||
{lifecycleMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{inventoryEnabled && loading ? (
|
||||
<div className="flex items-center justify-center h-64" data-testid="inventory-loading-state">
|
||||
<div className="text-xs text-[var(--foreground-dim)] font-mono uppercase tracking-wider">
|
||||
@@ -249,14 +299,20 @@ export default function Dashboard() {
|
||||
</h2>
|
||||
</div>
|
||||
<p className="text-sm text-[var(--foreground)] mb-6">
|
||||
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?
|
||||
</p>
|
||||
{lifecycleMessage && (
|
||||
<div className="mb-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">
|
||||
{lifecycleMessage}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-4">
|
||||
<button
|
||||
onClick={confirmDelete}
|
||||
className="flex-1 px-4 py-2 rounded-sm bg-[var(--status-stopped)] text-white text-xs font-mono uppercase tracking-wider hover:bg-[#b91c1c] transition-colors"
|
||||
disabled={deleteInProgress}
|
||||
className="flex-1 px-4 py-2 rounded-sm bg-[var(--status-stopped)] text-white text-xs font-mono uppercase tracking-wider hover:bg-[#b91c1c] transition-colors disabled:opacity-50"
|
||||
>
|
||||
YES — DESTROY
|
||||
{deleteInProgress ? 'DESTROYING...' : 'YES — DESTROY'}
|
||||
</button>
|
||||
<button
|
||||
onClick={cancelDelete}
|
||||
|
||||
Reference in New Issue
Block a user