"use client" import { useCallback, useEffect, useState } from 'react' import type { ReactNode } from 'react' import ConfigurationPanel from './ConfigurationPanel' import SandboxArchivePanel from './SandboxArchivePanel' import SandboxFilesPanel from './SandboxFilesPanel' import SandboxInferencePanel from './SandboxInferencePanel' import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory' interface TelemetryData { cpu: number memory: number disk: number gpuMemoryUsed?: number gpuMemoryTotal?: number gpuTemperature?: number timestamp: string } interface SandboxListProps { sandboxes: SandboxInventoryItem[] nemoclaw: NemoClawSummary | null selectedSandboxId: string | null selectedSandbox: SandboxInventoryItem | null onSandboxSelect: (id: string | null) => void isDestroyMode: boolean onInventoryRefresh: () => Promise } type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' | 'archive' | 'mcp' type McpServerAccess = { id: string name: string command: string args: string[] enabled: boolean accessMode: 'disabled' | 'allow_all' | 'allow_only' allowedSandboxIds: string[] } type NetworkRuleRequest = { chunkId: string status: string rule: string binary: string confidence: string rationale: string endpoints: string[] binaries: string[] } type PermissionFeed = { latest?: { status?: string; chunkId?: string; error?: string } | null pending?: NetworkRuleRequest[] recent?: NetworkRuleRequest[] pendingCount?: number rejectedCount?: number } function renderDashboardTruthMessage(data: any) { if (data.reachable) return 'OpenClaw dashboard opened in a new tab.' return 'OpenClaw dashboard is not reachable from this host right now.' } function openDashboardUrl(url: string, openInNewTab: boolean) { if (openInNewTab) { window.open(url, '_blank', 'noopener,noreferrer') } else { window.location.href = url } } function DrawerSection({ title, summary, open, onToggle, children, }: { title: string summary: string open: boolean onToggle: () => void children: ReactNode }) { return (
{open && (
{children}
)}
) } export default function SandboxList({ sandboxes, nemoclaw: _nemoclaw, selectedSandboxId, selectedSandbox, onSandboxSelect, isDestroyMode, onInventoryRefresh, }: SandboxListProps) { const [dashboardMessage, setDashboardMessage] = useState('') const [restartInProgress, setRestartInProgress] = useState(false) const [permissionMessage, setPermissionMessage] = useState('') const [permissionFeeds, setPermissionFeeds] = useState>({}) const [grantingSandboxId, setGrantingSandboxId] = useState(null) const [mcpServers, setMcpServers] = useState([]) const [mcpMessage, setMcpMessage] = useState('') const [mcpUpdatingServerId, setMcpUpdatingServerId] = useState(null) const [mcpSyncing, setMcpSyncing] = useState(false) const [openDrawers, setOpenDrawers] = useState>({ operations: true, files: false, inference: false, policy: false, archive: false, mcp: false, }) const [telemetry, setTelemetry] = useState({ cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString() }) useEffect(() => { if (selectedSandboxId) { fetchTelemetry() const interval = setInterval(fetchTelemetry, 5000) return () => clearInterval(interval) } }, [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(() => { if (sandboxes.length === 0) { setPermissionFeeds({}) return } setPermissionFeeds((current) => Object.fromEntries( Object.entries(current).filter(([sandboxId]) => sandboxes.some((sandbox) => sandbox.id === sandboxId)), )) }, [sandboxes]) useEffect(() => { if (!selectedSandbox || !openDrawers.policy || permissionFeeds[selectedSandbox.id]) return loadPermissionFeed(selectedSandbox) }, [loadPermissionFeed, openDrawers.policy, permissionFeeds, selectedSandbox]) useEffect(() => { let active = true const loadMcpAccess = async () => { try { const response = await fetch('/api/mcp', { cache: 'no-store' }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Failed to load MCP access') if (active) setMcpServers(Array.isArray(data.servers) ? data.servers : []) } catch (error) { if (active) { setMcpServers([]) setMcpMessage(error instanceof Error ? error.message : 'Failed to load MCP access') } } } loadMcpAccess() const interval = window.setInterval(loadMcpAccess, 12000) return () => { active = false window.clearInterval(interval) } }, []) const fetchTelemetry = async () => { try { const response = await fetch('/api/telemetry/combined') const data = await response.json() setTelemetry(data) } catch (error) { console.error('Error fetching telemetry:', error) } } const restartSandboxRuntime = async () => { if (!selectedSandbox || restartInProgress) return try { setRestartInProgress(true) setDashboardMessage(`Restarting OpenClaw runtime for ${selectedSandbox.name}...`) const response = await fetch(`/api/sandbox/${encodeURIComponent(selectedSandbox.id)}/restart`, { method: 'POST', }) const data = await response.json() if (!response.ok) throw new Error(data.error || data.note || 'Failed to restart OpenClaw runtime') setDashboardMessage(data.note || `OpenClaw runtime restarted for ${selectedSandbox.name}.`) await onInventoryRefresh() } catch (error) { setDashboardMessage(error instanceof Error ? error.message : 'Failed to restart OpenClaw runtime.') } finally { setRestartInProgress(false) } } const toggleDrawer = (key: DrawerKey) => { const opening = !openDrawers[key] setOpenDrawers((current) => ({ ...current, [key]: !current[key] })) if (key === 'policy' && opening && selectedSandbox) { loadPermissionFeed(selectedSandbox) } } const sandboxCanAccessMcpServer = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { if (!server.enabled || server.accessMode === 'disabled') return false if (server.accessMode === 'allow_all') return true return server.allowedSandboxIds.includes(sandbox.id) || server.allowedSandboxIds.includes(sandbox.name) } const allowedMcpServersForSandbox = (sandbox: SandboxInventoryItem) => ( mcpServers.filter((server) => sandboxCanAccessMcpServer(sandbox, server)) ) const updateMcpServerAccess = async ( server: McpServerAccess, body: Partial>, success: string, ) => { try { setMcpUpdatingServerId(server.id) setMcpMessage('') const response = await fetch('/api/mcp', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'update-access', serverId: server.id, ...body }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Failed to update MCP access') setMcpServers(Array.isArray(data.servers) ? data.servers : []) setMcpMessage(success) } catch (error) { setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP access') } finally { setMcpUpdatingServerId(null) } } const syncMcpManifest = async (sandbox: SandboxInventoryItem, action: 'sync' | 'revoke' = 'sync') => { try { setMcpSyncing(true) setMcpMessage(action === 'revoke' ? `Revoking MCP broker config for ${sandbox.name}...` : `Issuing MCP broker config for ${sandbox.name}...`) const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sandboxName: sandbox.name, action }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Failed to update MCP broker config') const networkNote = data.network?.approved?.length ? ` 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) { setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP broker config') } finally { setMcpSyncing(false) } } const enableMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { const current = new Set(server.allowedSandboxIds) current.add(sandbox.id) return updateMcpServerAccess(server, { enabled: true, accessMode: server.accessMode === 'allow_all' ? 'allow_all' : 'allow_only', allowedSandboxIds: Array.from(current), }, `${server.name} enabled for ${sandbox.name}.`).then(() => syncMcpManifest(sandbox)) } const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { const hasOtherMcpAccess = mcpServers.some((candidate) => candidate.id !== server.id && sandboxCanAccessMcpServer(sandbox, candidate)) const current = new Set(server.allowedSandboxIds) current.delete(sandbox.id) current.delete(sandbox.name) if (server.accessMode === 'allow_all') { for (const item of sandboxes) { if (item.id !== sandbox.id) current.add(item.id) } } return updateMcpServerAccess(server, { accessMode: 'allow_only', allowedSandboxIds: Array.from(current), }, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox, hasOtherMcpAccess ? 'sync' : 'revoke')) } const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { if (!chunkId) return try { setGrantingSandboxId(sandbox.id) setPermissionMessage(`${action === 'approve' ? 'Approving' : 'Rejecting'} network request for ${sandbox.name}...`) const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/permissions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action, chunkId }), }) const data = await response.json() if (!response.ok) throw new Error(data.error || 'Failed to resolve permission request') if (data.result?.feed) { setPermissionFeeds((current) => ({ ...current, [sandbox.id]: data.result.feed })) } setPermissionMessage(data.note || `Network request ${action === 'approve' ? 'approved' : 'rejected'} for ${sandbox.name}.`) } catch (error) { setPermissionMessage(error instanceof Error ? error.message : 'Failed to resolve permission request') } finally { setGrantingSandboxId(null) } } return (
{sandboxes.length === 0 ? (

No Sandboxes Detected

No live OpenShell sandboxes reported yet

) : ( <> {permissionMessage && (
{permissionMessage}
)} {!isDestroyMode && selectedSandbox && ( <> toggleDrawer('operations')} >
LIVE
{dashboardMessage && (
{dashboardMessage &&
{dashboardMessage}
}
)}

CPU

{telemetry.cpu.toFixed(1)}%

MEM

{telemetry.memory.toFixed(1)}%

DISK

{telemetry.disk.toFixed(1)}%

UPDATED

{new Date(telemetry.timestamp).toLocaleTimeString()}

toggleDrawer('files')} > toggleDrawer('inference')} > toggleDrawer('mcp')} >

Sandbox Manifest

Writes /sandbox/openshell_control_mcp.md with broker URL and sandbox token only.

{mcpMessage && (
{mcpMessage}
)} {mcpServers.length === 0 ? (
No MCP servers are installed yet.
) : (
{mcpServers.map((server) => { const hasAccess = sandboxCanAccessMcpServer(selectedSandbox, server) const updating = mcpUpdatingServerId === server.id return (

{server.name}

{server.command} {server.args.join(' ')}

{hasAccess ? 'allowed' : 'blocked'}
) })}
)}
toggleDrawer('policy')} >

Network Permission Feed

Loaded on demand for the selected sandbox to avoid background permission polling.

{(() => { const feed = permissionFeeds[selectedSandbox.id] 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 && (

Recent Network Rules

{recentRules.map((request) => { const approved = /approved/i.test(request.status) const rejected = /rejected/i.test(request.status) return (
{request.endpoints.join(', ') || request.rule} {request.status || 'unknown'}

{request.rationale || 'Sandbox network rule.'}

{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}

{(approved || rejected) && ( )}
) })}
) if (pending.length === 0) { return ( <>
No pending network permission requests for this sandbox.
{renderRecentRules()} ) } return (
{pending.map((request) => (
{request.endpoints.join(', ') || request.rule} {request.confidence ? ( {request.confidence} ) : null}

{request.rationale || 'Sandbox requested a network policy rule.'}

{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}

))} {renderRecentRules()}
) })()}
toggleDrawer('archive')} > { await onInventoryRefresh() }} /> )} )}
) }