Stabilize dashboard runtime proxy
This commit is contained in:
@@ -1,14 +1,108 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getOpenClawDashboardUrl } from '../../../../lib/openshellHost'
|
||||
import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost'
|
||||
import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances'
|
||||
import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority'
|
||||
|
||||
function parseInventoryCount(requestUrl: URL) {
|
||||
const raw = requestUrl.searchParams.get('inventoryCount')
|
||||
if (raw == null) return null
|
||||
const count = Number.parseInt(raw, 10)
|
||||
return Number.isFinite(count) && count >= 0 ? count : null
|
||||
}
|
||||
|
||||
function buildLaunchUrl(proxiedUrl: string, bootstrapUrl: string | null) {
|
||||
if (!bootstrapUrl) return proxiedUrl
|
||||
|
||||
const bootstrap = new URL(bootstrapUrl)
|
||||
const browserHash = bootstrap.hash
|
||||
bootstrap.hash = ''
|
||||
|
||||
const params = new URLSearchParams({
|
||||
path: '/',
|
||||
bootstrapUrl: bootstrap.toString(),
|
||||
})
|
||||
|
||||
return `${proxiedUrl}?${params.toString()}${browserHash}`
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const sandboxId = requestUrl.searchParams.get('sandboxId')
|
||||
const requestedInstanceId = requestUrl.searchParams.get('instanceId')
|
||||
const inventoryCount = parseInventoryCount(requestUrl)
|
||||
const mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox(sandboxId)
|
||||
const instance = requestedInstanceId
|
||||
? resolveOpenClawInstance(requestedInstanceId)
|
||||
: resolveOpenClawInstanceForSandbox(sandboxId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
instanceId: requestedInstanceId,
|
||||
})
|
||||
const probe = await probeOpenClawDashboard(authority.openclaw.id)
|
||||
const instanceQualifiedProxyBase = `/api/openshell/instances/${encodeURIComponent(instance.id)}/dashboard/proxy`
|
||||
const zeroInventoryMappedDashboard = Boolean(
|
||||
inventoryCount === 0 &&
|
||||
sandboxId &&
|
||||
authority.bridgeActive &&
|
||||
probe.reachable
|
||||
)
|
||||
const truthState = zeroInventoryMappedDashboard
|
||||
? 'degraded'
|
||||
: probe.bootstrapAuthority === 'tokenized-cli'
|
||||
? 'tokenized'
|
||||
: authority.bridgeActive
|
||||
? 'bridged'
|
||||
: 'verified'
|
||||
|
||||
const proxiedUrl = authority.explicitInstanceOverride ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy'
|
||||
const launchUrl = buildLaunchUrl(proxiedUrl, probe.bootstrapUrl)
|
||||
|
||||
export async function GET() {
|
||||
const dashboardUrl = getOpenClawDashboardUrl()
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
dashboardUrl,
|
||||
proxiedUrl: '/api/openshell/dashboard/proxy',
|
||||
sandboxId,
|
||||
sandboxInstanceId: mappedSandboxInstanceId,
|
||||
instanceId: instance.id,
|
||||
inventoryCount,
|
||||
truthState,
|
||||
degraded: zeroInventoryMappedDashboard,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
authorityMode: authority.authorityMode,
|
||||
provenance: authority.provenance,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
bridgeReason: authority.bridgeReason,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
},
|
||||
defaultInstanceId: getDefaultOpenClawDashboardInstanceId(),
|
||||
dashboardUrl: getOpenClawDashboardUrl(authority.openclaw.id),
|
||||
bootstrapUrl: probe.bootstrapUrl,
|
||||
bootstrapTokenPresent: probe.bootstrapTokenPresent,
|
||||
bootstrapSource: probe.bootstrapSource,
|
||||
bootstrapAuthority: probe.bootstrapAuthority,
|
||||
proxiedUrl,
|
||||
launchUrl,
|
||||
instanceQualifiedProxiedUrl: instanceQualifiedProxyBase,
|
||||
openInNewTab: true,
|
||||
loopbackOnly: true,
|
||||
note: 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
|
||||
loopbackOnly: authority.openclaw.loopbackOnly,
|
||||
reachable: probe.reachable,
|
||||
upstreamStatus: probe.status,
|
||||
upstreamStatusText: probe.statusText,
|
||||
listenerPresent: probe.listenerPresent,
|
||||
listenerSummary: probe.listenerSummary,
|
||||
note: zeroInventoryMappedDashboard
|
||||
? 'Degraded truth: live OpenShell inventory is zero, but a bridged OpenClaw dashboard upstream is still reachable. Treat this dashboard as a fallback operator surface, not proof that the sandbox currently exists.'
|
||||
: probe.bootstrapAuthority === 'tokenized-cli'
|
||||
? 'Tokenized bootstrap available: the bridge resolved a dashboard URL from `openclaw dashboard --no-open`, so the proxy can carry the real OpenClaw session contract instead of treating raw loopback fetch as sufficient truth.'
|
||||
: authority.bridgeActive
|
||||
? authority.bridgeReason || 'Bridge-active: this dashboard action is using an explicit upstream OpenClaw bridge instead of assuming same-lane loopback ownership.'
|
||||
: authority.openclaw.loopbackOnly
|
||||
? 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
|
||||
: 'OpenClaw Dashboard is reachable directly for this instance.'
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,9 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const OPENCLAW_LOCAL_DASHBOARD = 'http://127.0.0.1:18789/'
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from './shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const targetPath = url.searchParams.get('path') || ''
|
||||
const target = new URL(targetPath, OPENCLAW_LOCAL_DASHBOARD)
|
||||
|
||||
const upstream = await fetch(target.toString(), {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
accept: 'text/html,application/json;q=0.9,*/*;q=0.8'
|
||||
},
|
||||
cache: 'no-store'
|
||||
})
|
||||
|
||||
const contentType = upstream.headers.get('content-type') || 'text/html; charset=utf-8'
|
||||
const body = await upstream.text()
|
||||
|
||||
return new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
headers: {
|
||||
'content-type': contentType,
|
||||
'cache-control': 'no-store'
|
||||
}
|
||||
})
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard'
|
||||
}, { status: 500 })
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy'
|
||||
const INSTANCES_PREFIX = '/api/openshell/instances/'
|
||||
const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy'
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'accept-encoding',
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade',
|
||||
'content-length',
|
||||
])
|
||||
|
||||
type ProxyTargetResolution = {
|
||||
instanceId: string | null
|
||||
proxyPrefix: string
|
||||
targetBaseUrl: string
|
||||
authorityMode: 'direct-host' | 'bridged-sandbox-map' | 'bridged-instance-override'
|
||||
bridgeActive: boolean
|
||||
}
|
||||
|
||||
function normalizeDashboardProxyInstanceId(instanceId: string | null) {
|
||||
if (!instanceId) return null
|
||||
return instanceId === getDefaultOpenClawDashboardInstanceId() ? null : instanceId
|
||||
}
|
||||
|
||||
function resolveProxyTarget(requestUrl: URL): ProxyTargetResolution {
|
||||
const pathname = requestUrl.pathname
|
||||
|
||||
if (pathname.startsWith(INSTANCES_PREFIX)) {
|
||||
const suffixIndex = pathname.indexOf(DASHBOARD_PROXY_SUFFIX, INSTANCES_PREFIX.length)
|
||||
if (suffixIndex !== -1) {
|
||||
const rawInstanceId = pathname.slice(INSTANCES_PREFIX.length, suffixIndex)
|
||||
const decodedInstanceId = decodeURIComponent(rawInstanceId)
|
||||
const normalizedInstanceId = normalizeDashboardProxyInstanceId(decodedInstanceId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId: requestUrl.searchParams.get('sandboxId'),
|
||||
instanceId: normalizedInstanceId,
|
||||
})
|
||||
return {
|
||||
instanceId: authority.openclaw.id,
|
||||
proxyPrefix: `/api/openshell/instances/${encodeURIComponent(decodedInstanceId)}/dashboard/proxy`,
|
||||
targetBaseUrl: authority.openclaw.dashboardUrl,
|
||||
authorityMode: authority.authorityMode,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId: requestUrl.searchParams.get('sandboxId'),
|
||||
})
|
||||
|
||||
return {
|
||||
instanceId: authority.bridgeActive ? authority.openclaw.id : null,
|
||||
proxyPrefix: LEGACY_PROXY_PREFIX,
|
||||
targetBaseUrl: authority.openclaw.dashboardUrl,
|
||||
authorityMode: authority.authorityMode,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
}
|
||||
}
|
||||
|
||||
function buildTargetUrl(requestUrl: URL) {
|
||||
const { proxyPrefix, targetBaseUrl, authorityMode, bridgeActive } = resolveProxyTarget(requestUrl)
|
||||
const pathParam = requestUrl.searchParams.get('path')
|
||||
const bootstrapUrl = requestUrl.searchParams.get('bootstrapUrl')
|
||||
const pathname = requestUrl.pathname.startsWith(proxyPrefix)
|
||||
? requestUrl.pathname.slice(proxyPrefix.length)
|
||||
: '/'
|
||||
const upstreamPath = pathParam ?? pathname ?? '/'
|
||||
const normalizedPath = upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`
|
||||
const target = bootstrapUrl
|
||||
? new URL(bootstrapUrl)
|
||||
: new URL(normalizedPath, targetBaseUrl)
|
||||
|
||||
if (!bootstrapUrl) {
|
||||
requestUrl.searchParams.forEach((value, key) => {
|
||||
if (key !== 'path') target.searchParams.append(key, value)
|
||||
})
|
||||
}
|
||||
|
||||
return { target, proxyPrefix, authorityMode, bridgeActive }
|
||||
}
|
||||
|
||||
function copyRequestHeaders(request: Request, target: URL) {
|
||||
const headers = new Headers()
|
||||
|
||||
request.headers.forEach((value, key) => {
|
||||
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase()) && key.toLowerCase() !== 'host') {
|
||||
headers.set(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
headers.set('host', target.host)
|
||||
return headers
|
||||
}
|
||||
|
||||
function copyResponseHeaders(upstream: Response) {
|
||||
const headers = new Headers()
|
||||
|
||||
upstream.headers.forEach((value, key) => {
|
||||
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {
|
||||
headers.set(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
headers.set('cache-control', 'no-store')
|
||||
return headers
|
||||
}
|
||||
|
||||
function proxiedAssetPath(value: string, proxyPrefix: string) {
|
||||
if (
|
||||
!value ||
|
||||
value.startsWith('#') ||
|
||||
value.startsWith('//') ||
|
||||
/^[a-z][a-z\d+.-]*:/i.test(value)
|
||||
) {
|
||||
return value
|
||||
}
|
||||
|
||||
const normalized = value.startsWith('./')
|
||||
? value.slice(2)
|
||||
: value.startsWith('/')
|
||||
? value.slice(1)
|
||||
: value
|
||||
|
||||
return `${proxyPrefix}/${normalized}`
|
||||
}
|
||||
|
||||
function rewriteHtml(body: string, proxyPrefix: string) {
|
||||
return body.replace(
|
||||
/(<(?:script|img|link)\b[^>]*\s(?:src|href)=)(["'])([^"']+)(["'])/gi,
|
||||
(_match, prefix: string, quote: string, value: string, suffix: string) =>
|
||||
`${prefix}${quote}${proxiedAssetPath(value, proxyPrefix)}${suffix}`
|
||||
)
|
||||
}
|
||||
|
||||
export async function proxyOpenClawDashboard(request: Request) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const { target, proxyPrefix, authorityMode, bridgeActive } = buildTargetUrl(requestUrl)
|
||||
const method = request.method.toUpperCase()
|
||||
const headers = copyRequestHeaders(request, target)
|
||||
const shouldSendBody = !['GET', 'HEAD'].includes(method)
|
||||
const upstreamInit: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers,
|
||||
body: shouldSendBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
cache: 'no-store',
|
||||
}
|
||||
|
||||
if (shouldSendBody) {
|
||||
upstreamInit.duplex = 'half'
|
||||
}
|
||||
|
||||
const upstream = await fetch(target.toString(), {
|
||||
...upstreamInit,
|
||||
})
|
||||
|
||||
const responseHeaders = copyResponseHeaders(upstream)
|
||||
responseHeaders.set('x-openclaw-authority-mode', authorityMode)
|
||||
responseHeaders.set('x-openclaw-bridge-active', bridgeActive ? 'true' : 'false')
|
||||
responseHeaders.set('x-openclaw-dashboard-bootstrap-contract', 'tokenized-openclaw-dashboard')
|
||||
const location = upstream.headers.get('location')
|
||||
if (location) {
|
||||
responseHeaders.set('location', location.startsWith('/') ? `${proxyPrefix}${location}` : location)
|
||||
}
|
||||
const contentType = upstream.headers.get('content-type') || 'application/octet-stream'
|
||||
|
||||
if (contentType.includes('text/html')) {
|
||||
const body = rewriteHtml(await upstream.text(), proxyPrefix)
|
||||
responseHeaders.set('content-type', contentType)
|
||||
return new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
return new NextResponse(upstream.body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
export function proxyErrorResponse(error: unknown) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../../../../../dashboard/proxy/shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../../../../dashboard/proxy/shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { dockerExecInOpenShell, OPENSHELL_NAMESPACE } from '../../../../lib/openshellHost'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = searchParams.get('sandboxId')
|
||||
|
||||
if (!sandboxId) {
|
||||
return NextResponse.json({ error: 'sandboxId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const result = await dockerExecInOpenShell(
|
||||
`kubectl -n ${OPENSHELL_NAMESPACE} get pod ${sandboxId} -o json`
|
||||
)
|
||||
|
||||
const pod = JSON.parse(result.stdout)
|
||||
const containerNames = Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.name) : []
|
||||
const containerImages = Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.image) : []
|
||||
const statusNames = Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses.map((c: any) => c.name) : []
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
containers: containerNames,
|
||||
images: containerImages,
|
||||
runningStatuses: statusNames,
|
||||
raw: result.stdout.trim(),
|
||||
stderr: result.stderr.trim(),
|
||||
note: 'Pod/container introspection succeeded. Use this to select the right exec target for terminal attach.'
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to introspect sandbox pod'
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,131 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { inspectSandbox } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
const TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011'
|
||||
const TERMINAL_WS_PROXY_PATH = '/api/openshell/terminal/live/ws'
|
||||
const PUBLIC_BROWSER_HOST = process.env.PUBLIC_BROWSER_HOST || process.env.PUBLIC_WS_HOST || null
|
||||
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL || null
|
||||
|
||||
function isNonRoutableHost(candidate: string, protocol = 'http:') {
|
||||
const normalized = candidate.trim()
|
||||
if (!normalized) return true
|
||||
|
||||
try {
|
||||
const parsed = new URL(`${protocol}//${normalized}`)
|
||||
return (
|
||||
parsed.hostname === '0.0.0.0' ||
|
||||
parsed.hostname === '::' ||
|
||||
parsed.hostname === '127.0.0.1' ||
|
||||
parsed.hostname === 'localhost' ||
|
||||
parsed.hostname === '[::1]' ||
|
||||
parsed.hostname === '::1'
|
||||
)
|
||||
} catch {
|
||||
return (
|
||||
normalized.startsWith('0.0.0.0') ||
|
||||
normalized.startsWith('[::]') ||
|
||||
normalized.startsWith('127.0.0.1') ||
|
||||
normalized.startsWith('localhost') ||
|
||||
normalized.startsWith('[::1]') ||
|
||||
normalized.startsWith('::1')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function resolveBrowserHost(requestUrl: URL, forwardedHost: string | null) {
|
||||
const forwardedCandidate = (forwardedHost && forwardedHost.trim()) || ''
|
||||
if (forwardedCandidate && !isNonRoutableHost(forwardedCandidate, requestUrl.protocol)) {
|
||||
return forwardedCandidate
|
||||
}
|
||||
|
||||
if (PUBLIC_BROWSER_HOST && !isNonRoutableHost(PUBLIC_BROWSER_HOST, requestUrl.protocol)) {
|
||||
return PUBLIC_BROWSER_HOST.trim()
|
||||
}
|
||||
|
||||
if (PUBLIC_BASE_URL) {
|
||||
try {
|
||||
const parsed = new URL(PUBLIC_BASE_URL)
|
||||
if (!isNonRoutableHost(parsed.host, parsed.protocol)) {
|
||||
return parsed.host
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed PUBLIC_BASE_URL
|
||||
}
|
||||
}
|
||||
|
||||
const requestHostHeader = requestUrl.host
|
||||
if (!isNonRoutableHost(requestHostHeader, requestUrl.protocol)) {
|
||||
return requestHostHeader
|
||||
}
|
||||
|
||||
const hostHeader = requestUrl.hostname
|
||||
const requestPort = requestUrl.port
|
||||
if (hostHeader && !isNonRoutableHost(hostHeader, requestUrl.protocol)) {
|
||||
return requestPort ? `${hostHeader}:${requestPort}` : hostHeader
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getBrowserWebSocketUrl(request: Request, params: {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
dashboardSessionId: string
|
||||
}) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const forwardedProto = request.headers.get('x-forwarded-proto')
|
||||
const forwardedHost = request.headers.get('x-forwarded-host')
|
||||
const host = resolveBrowserHost(requestUrl, forwardedHost)
|
||||
if (!host) {
|
||||
throw new Error('No routable browser host available for terminal websocket URL. Set PUBLIC_BROWSER_HOST or PUBLIC_BASE_URL.')
|
||||
}
|
||||
const baseProtocol = (forwardedProto && forwardedProto.trim()) || requestUrl.protocol.replace(/:$/, '')
|
||||
const protocol = baseProtocol === 'https' ? 'wss:' : 'ws:'
|
||||
const websocketUrl = new URL(TERMINAL_WS_PROXY_PATH, `${protocol}//${host}`)
|
||||
websocketUrl.searchParams.set('sessionId', params.sessionId)
|
||||
websocketUrl.searchParams.set('sandboxId', params.sandboxId)
|
||||
websocketUrl.searchParams.set('dashboardSessionId', params.dashboardSessionId)
|
||||
return websocketUrl.toString()
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const response = await fetch(`${TERMINAL_SERVER_URL}/session`, {
|
||||
const sandboxId = typeof body?.sandboxId === 'string' ? body.sandboxId.trim() : ''
|
||||
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
|
||||
const dashboardSessionId = typeof body?.dashboardSessionId === 'string' && body.dashboardSessionId.trim()
|
||||
? body.dashboardSessionId.trim()
|
||||
: 'dashboard-host'
|
||||
|
||||
const requestedSandboxId = sandboxId || 'host'
|
||||
|
||||
let inspection = null
|
||||
if (sandboxId) {
|
||||
try {
|
||||
inspection = await inspectSandbox(sandboxId)
|
||||
} catch {
|
||||
inspection = null
|
||||
}
|
||||
}
|
||||
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
resolvedSandboxId: inspection?.name || null,
|
||||
instanceId: typeof body?.instanceId === 'string' ? body.instanceId.trim() : '',
|
||||
})
|
||||
const terminalServerUrl = authority.terminalServerUrl || TERMINAL_SERVER_URL
|
||||
const resolvedSandboxId = authority.resolvedSandboxId || requestedSandboxId
|
||||
|
||||
const response = await fetch(`${terminalServerUrl}/session`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sandboxId: body?.sandboxId,
|
||||
sessionId: body?.sessionId,
|
||||
sandboxId: resolvedSandboxId,
|
||||
sessionId,
|
||||
dashboardSessionId,
|
||||
}),
|
||||
cache: 'no-store',
|
||||
})
|
||||
@@ -22,13 +135,31 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ ok: false, error: result.error || 'Failed to initialize live terminal session.' }, { status: 502 })
|
||||
}
|
||||
|
||||
const wsBase = TERMINAL_SERVER_URL.replace(/^http/, 'ws')
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
replay: result.replay,
|
||||
websocketUrl: `${wsBase}/ws?sessionId=${encodeURIComponent(result.sessionId)}&sandboxId=${encodeURIComponent(result.sandboxId)}`,
|
||||
transport: result.transport,
|
||||
instanceId: authority.openclaw.id,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
},
|
||||
sshHostAlias: inspection?.sshHostAlias || null,
|
||||
websocketUrl: getBrowserWebSocketUrl(request, {
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
}),
|
||||
degraded: !inspection,
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -16,14 +16,19 @@ export async function GET(request: Request) {
|
||||
ok: true,
|
||||
sandboxId,
|
||||
attached: true,
|
||||
output: result.stdout.trim(),
|
||||
stderr: result.stderr.trim(),
|
||||
note: 'Backend-local terminal probe succeeded. Next step is persistent interactive terminal transport.'
|
||||
name: result.name,
|
||||
resolvedId: result.id,
|
||||
namespace: result.namespace,
|
||||
phase: result.phase,
|
||||
sshHostAlias: result.sshHostAlias,
|
||||
sshConfig: result.sshConfig,
|
||||
output: result.rawDetails,
|
||||
note: 'Sandbox inspection succeeded. Next step is persistent interactive terminal transport.',
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to probe terminal attach'
|
||||
error: error instanceof Error ? error.message : 'Failed to probe terminal attach',
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,131 +1,150 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { dockerExecInOpenShell, OPENSHELL_NAMESPACE, probeSandboxShell, validateSandboxId } from '../../../../lib/openshellHost'
|
||||
import { inspectSandbox, isOpenShellTransportError } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
interface PodSummary {
|
||||
containers: string[]
|
||||
images: string[]
|
||||
runningStatuses: string[]
|
||||
phase?: string
|
||||
readyCondition?: string
|
||||
function normalizeSandboxId(value: string | null) {
|
||||
return (value || '').trim()
|
||||
}
|
||||
|
||||
const EMPTY_POD_SUMMARY: PodSummary = {
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
}
|
||||
function buildAttach(alias: string, sandboxId: string) {
|
||||
const loginShell = process.platform === 'darwin' ? 'zsh' : 'bash'
|
||||
const extraPath = process.platform === 'darwin' ? '/opt/homebrew/bin' : `${process.env.HOME || '~'}/.local/bin`
|
||||
|
||||
async function inspectPod(sandboxId: string): Promise<PodSummary> {
|
||||
const result = await dockerExecInOpenShell(
|
||||
`kubectl -n ${OPENSHELL_NAMESPACE} get pod ${sandboxId} -o json`
|
||||
)
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
const failureText = `${result.stderr}\n${result.stdout}`.toLowerCase()
|
||||
if (failureText.includes('(notfound)') || failureText.includes('not found')) {
|
||||
return EMPTY_POD_SUMMARY
|
||||
}
|
||||
throw new Error(result.stderr.trim() || result.stdout.trim() || `kubectl get pod failed with exit code ${result.exitCode}`)
|
||||
}
|
||||
|
||||
if (!result.stdout.trim()) {
|
||||
throw new Error('kubectl get pod returned empty stdout')
|
||||
}
|
||||
|
||||
const pod = JSON.parse(result.stdout)
|
||||
return {
|
||||
containers: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.name) : [],
|
||||
images: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.image) : [],
|
||||
runningStatuses: Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses.map((c: any) => c.name) : [],
|
||||
phase: pod?.status?.phase,
|
||||
readyCondition: Array.isArray(pod?.status?.conditions)
|
||||
? pod.status.conditions.find((c: any) => c.type === 'Ready')?.status
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function buildAttachContract(sandboxId: string) {
|
||||
const alias = `openshell-${sandboxId}`
|
||||
return {
|
||||
alias,
|
||||
aliasCommand: `ssh ${alias}`,
|
||||
fallbackCommand: `ssh -i ~/.ssh/id_ed25519_openclaw_labmac ${alias}`,
|
||||
loginShellCommand: `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh ${alias}'`,
|
||||
shellHint: 'If a non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.',
|
||||
fallbackCommand: `ssh ${alias}`,
|
||||
loginShellCommand: `env PATH=${extraPath}:$PATH ${loginShell} -l -c 'ssh ${alias}'`,
|
||||
shellHint: process.platform === 'darwin'
|
||||
? 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.'
|
||||
: 'If your non-interactive shell misses local tooling, retry from a login shell or prepend PATH=$HOME/.local/bin:$PATH before ssh.',
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
let sandboxId = 'unknown'
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = validateSandboxId(searchParams.get('sandboxId') || '')
|
||||
sandboxId = normalizeSandboxId(url.searchParams.get('sandboxId'))
|
||||
|
||||
const attach = buildAttachContract(sandboxId)
|
||||
const pod = await inspectPod(sandboxId)
|
||||
|
||||
let shellProbe: {
|
||||
ok: boolean
|
||||
output?: string
|
||||
stderr?: string
|
||||
error?: string
|
||||
} = { ok: false }
|
||||
|
||||
const podExists = Boolean(pod.containers.length || pod.images.length || pod.phase)
|
||||
|
||||
if (podExists) {
|
||||
try {
|
||||
const probe = await probeSandboxShell(sandboxId)
|
||||
shellProbe = {
|
||||
if (!sandboxId) {
|
||||
const authority = resolveRuntimeAuthority({ sandboxId: null })
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId: 'host',
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: true,
|
||||
},
|
||||
podExists: false,
|
||||
podReady: true,
|
||||
sshReachable: true,
|
||||
degraded: true,
|
||||
attach: null,
|
||||
pod: {
|
||||
phase: 'Host',
|
||||
readyCondition: 'Host',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: true,
|
||||
output: probe.stdout.trim(),
|
||||
stderr: probe.stderr.trim(),
|
||||
}
|
||||
} catch (error) {
|
||||
shellProbe = {
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Shell probe failed',
|
||||
}
|
||||
}
|
||||
} else {
|
||||
shellProbe = {
|
||||
ok: false,
|
||||
error: `Sandbox pod ${sandboxId} was not found in ${OPENSHELL_NAMESPACE}.`,
|
||||
}
|
||||
output: 'Host terminal mode active. No sandbox selected.',
|
||||
stderr: '',
|
||||
},
|
||||
note: 'Host operator terminal is ready. Sandbox context is optional.',
|
||||
})
|
||||
}
|
||||
|
||||
const podReady = pod.readyCondition === 'True' || pod.phase === 'Running'
|
||||
const sshReachable = shellProbe.ok
|
||||
const sandbox = await inspectSandbox(sandboxId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
resolvedSandboxId: sandbox.name,
|
||||
})
|
||||
const podReady = sandbox.phase === 'Running'
|
||||
const sshReachable = sandbox.phase === 'Running'
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
podExists,
|
||||
sandboxId: sandbox.name,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: false,
|
||||
},
|
||||
podExists: true,
|
||||
podReady,
|
||||
sshReachable,
|
||||
degraded: podExists && !sshReachable,
|
||||
attach,
|
||||
pod,
|
||||
shellProbe,
|
||||
note: !podExists
|
||||
? `Sandbox pod ${sandboxId} is not present in ${OPENSHELL_NAMESPACE}.`
|
||||
: sshReachable
|
||||
? 'Pod introspection and bounded shell probe both succeeded.'
|
||||
: 'Pod introspection succeeded, but bounded shell probe did not. Treat this as degraded dashboard reachability until direct SSH is confirmed.',
|
||||
degraded: !sshReachable,
|
||||
attach: buildAttach(sandbox.sshHostAlias, sandbox.name),
|
||||
pod: {
|
||||
phase: sandbox.phase,
|
||||
readyCondition: podReady ? 'True' : sandbox.rawPhase || 'Unknown',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: sshReachable,
|
||||
output: sandbox.rawDetails,
|
||||
stderr: '',
|
||||
},
|
||||
note: sshReachable
|
||||
? 'Sandbox inspection succeeded and the normalized phase is Running.'
|
||||
: `Sandbox inspection succeeded, but authoritative phase is ${sandbox.rawPhase || 'Unknown'} (normalized ${sandbox.phase || 'Unknown'}).`,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to build readiness contract'
|
||||
const status = message === 'sandboxId is required'
|
||||
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
? 400
|
||||
: 500
|
||||
|
||||
const message = error instanceof Error ? error.message : 'Failed to inspect terminal readiness.'
|
||||
const transportError = isOpenShellTransportError(error)
|
||||
const authority = resolveRuntimeAuthority({ sandboxId })
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
ok: true,
|
||||
sandboxId: sandboxId || 'host',
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: true,
|
||||
},
|
||||
podExists: false,
|
||||
podReady: false,
|
||||
sshReachable: false,
|
||||
degraded: false,
|
||||
podReady: true,
|
||||
sshReachable: true,
|
||||
degraded: true,
|
||||
error: message,
|
||||
}, { status })
|
||||
attach: null,
|
||||
pod: {
|
||||
phase: 'Host',
|
||||
readyCondition: 'Host',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: true,
|
||||
output: 'Host terminal mode active. Sandbox inspection failed, but host shell remains available.',
|
||||
stderr: message,
|
||||
},
|
||||
note: transportError ? 'OpenShell transport is unavailable for sandbox inspection; host operator terminal remains available.' : 'Sandbox inspection failed; host operator terminal remains available.',
|
||||
}, { status: 200 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { DEFAULT_EXEC_TIMEOUT_MS, MAX_COMMAND_LENGTH, runSandboxCommand, validateSandboxId, validateTerminalCommand } from '../../../lib/openshellHost'
|
||||
|
||||
type TranscriptEntry = {
|
||||
id: string
|
||||
command: string
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number
|
||||
executionMode?: string
|
||||
ranAt: string
|
||||
}
|
||||
|
||||
type TerminalSession = {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
cwd?: string
|
||||
transcript: TranscriptEntry[]
|
||||
}
|
||||
|
||||
const sessions = new Map<string, TerminalSession>()
|
||||
const MAX_TRANSCRIPT = 100
|
||||
|
||||
function ensureSession(sessionId: string, sandboxId: string) {
|
||||
const existing = sessions.get(sessionId)
|
||||
if (existing) {
|
||||
if (existing.sandboxId !== sandboxId) {
|
||||
throw new Error('sessionId does not match sandboxId')
|
||||
}
|
||||
return existing
|
||||
}
|
||||
|
||||
const now = new Date().toISOString()
|
||||
const created: TerminalSession = {
|
||||
sessionId,
|
||||
sandboxId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
cwd: undefined,
|
||||
transcript: [],
|
||||
}
|
||||
sessions.set(sessionId, created)
|
||||
return created
|
||||
}
|
||||
|
||||
function sanitizePromptPath(cwd?: string) {
|
||||
if (!cwd) return '~'
|
||||
return cwd
|
||||
}
|
||||
|
||||
function buildWrappedCommand(command: string, cwd?: string) {
|
||||
const trimmed = validateTerminalCommand(command)
|
||||
const cdPrefix = cwd ? `cd ${quoteForSingleQuotedShell(cwd)} >/dev/null 2>&1 || exit 98; ` : ''
|
||||
const shellBody = `${cdPrefix}${trimmed}; __cmd_exit=$?; printf '\n__OPENCLAW_PWD__=%s\n' "$PWD"; exit $__cmd_exit`
|
||||
return shellBody
|
||||
}
|
||||
|
||||
function quoteForSingleQuotedShell(value: string) {
|
||||
return `'${value.replace(/'/g, `'"'"'`)}'`
|
||||
}
|
||||
|
||||
function extractPwd(stdout: string) {
|
||||
const match = stdout.match(/\n__OPENCLAW_PWD__=(.*)\n?$/)
|
||||
if (!match) {
|
||||
return { cleanedStdout: stdout.trim(), cwd: undefined }
|
||||
}
|
||||
|
||||
const cwd = match[1]?.trim() || undefined
|
||||
const cleanedStdout = stdout.slice(0, match.index).trimEnd()
|
||||
return { cleanedStdout, cwd }
|
||||
}
|
||||
|
||||
function serializeSession(session: TerminalSession) {
|
||||
return {
|
||||
ok: true,
|
||||
interactive: false,
|
||||
terminalLike: true,
|
||||
mode: 'session-backed-command-terminal',
|
||||
session: {
|
||||
sessionId: session.sessionId,
|
||||
sandboxId: session.sandboxId,
|
||||
cwd: session.cwd,
|
||||
createdAt: session.createdAt,
|
||||
updatedAt: session.updatedAt,
|
||||
prompt: `${session.sandboxId}:${sanitizePromptPath(session.cwd)}$`,
|
||||
transcript: session.transcript,
|
||||
},
|
||||
limits: {
|
||||
timeoutMs: DEFAULT_EXEC_TIMEOUT_MS,
|
||||
maxCommandLength: MAX_COMMAND_LENGTH,
|
||||
},
|
||||
note: 'Dashboard terminal is session-backed and command-scoped. It preserves transcript and working directory across commands, but it is not a raw PTY stream yet.',
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = searchParams.get('sandboxId') || ''
|
||||
const sessionId = searchParams.get('sessionId') || ''
|
||||
|
||||
if (!sandboxId) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: 'sandboxId is required',
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const validatedSandboxId = validateSandboxId(sandboxId)
|
||||
|
||||
if (!sessionId) {
|
||||
const createdSession = ensureSession(randomUUID(), validatedSandboxId)
|
||||
return NextResponse.json(serializeSession(createdSession))
|
||||
}
|
||||
|
||||
const session = sessions.get(sessionId)
|
||||
if (!session || session.sandboxId !== validatedSandboxId) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: 'session not found',
|
||||
}, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json(serializeSession(session))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to inspect terminal session'
|
||||
const status = message.includes('sandboxId') ? 400 : 500
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: message,
|
||||
}, { status })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const sandboxInput = typeof body?.sandboxId === 'string' ? body.sandboxId : ''
|
||||
const sessionInput = typeof body?.sessionId === 'string' ? body.sessionId : ''
|
||||
const commandInput = typeof body?.command === 'string' ? body.command : ''
|
||||
|
||||
const sandboxId = validateSandboxId(sandboxInput)
|
||||
const command = validateTerminalCommand(commandInput)
|
||||
const sessionId = sessionInput || randomUUID()
|
||||
const session = ensureSession(sessionId, sandboxId)
|
||||
|
||||
const wrappedCommand = buildWrappedCommand(command, session.cwd)
|
||||
const result = await runSandboxCommand(sandboxId, wrappedCommand)
|
||||
const { cleanedStdout, cwd } = extractPwd(result.stdout)
|
||||
|
||||
session.cwd = cwd || session.cwd
|
||||
session.updatedAt = new Date().toISOString()
|
||||
session.transcript.push({
|
||||
id: randomUUID(),
|
||||
command,
|
||||
stdout: cleanedStdout,
|
||||
stderr: result.stderr.trim(),
|
||||
exitCode: result.exitCode,
|
||||
executionMode: result.mode,
|
||||
ranAt: session.updatedAt,
|
||||
})
|
||||
if (session.transcript.length > MAX_TRANSCRIPT) {
|
||||
session.transcript.splice(0, session.transcript.length - MAX_TRANSCRIPT)
|
||||
}
|
||||
|
||||
const ok = result.exitCode === 0
|
||||
|
||||
return NextResponse.json({
|
||||
...serializeSession(session),
|
||||
ok,
|
||||
command,
|
||||
exitCode: result.exitCode,
|
||||
executionMode: result.mode,
|
||||
stdout: cleanedStdout,
|
||||
stderr: result.stderr.trim(),
|
||||
note: ok
|
||||
? 'Command completed and terminal session state was updated.'
|
||||
: `Command exited non-zero (${result.exitCode}); transcript preserved for inspection.`,
|
||||
}, { status: ok ? 200 : 502 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to run sandbox command'
|
||||
const status = message === 'sandboxId is required'
|
||||
|| message === 'command is required'
|
||||
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
|| message.includes('command exceeds')
|
||||
|| message.includes('sessionId does not match sandboxId')
|
||||
? 400
|
||||
: 500
|
||||
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: message,
|
||||
}, { status })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { inspectSandbox } from "@/app/lib/openshellHost"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const HOME = process.env.HOME || ""
|
||||
const NEMOCLAW_SETUP = process.env.NEMOCLAW_SETUP || `${HOME}/NemoClaw/scripts/setup.sh`
|
||||
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(":")
|
||||
|
||||
const GATEWAY_REUSE_POLICY = [
|
||||
"Gateway reuse policy:",
|
||||
"- reuse the existing OpenShell gateway when `openshell status` reports `Connected`",
|
||||
"- only start a fresh gateway when no healthy gateway is already connected",
|
||||
`- force non-interactive PATH to include ${HOME}/.local/bin so openshell resolves during setup`,
|
||||
].join("\n")
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
type SandboxVerification = {
|
||||
verified: boolean
|
||||
summary: string
|
||||
details?: {
|
||||
name: string
|
||||
id: string | null
|
||||
phase: string | null
|
||||
namespace: string | null
|
||||
sshHostAlias: string
|
||||
rawPhase: string | null
|
||||
rawDetails: string
|
||||
}
|
||||
error?: string
|
||||
}
|
||||
|
||||
const AUTHORITATIVE_SUCCESS_PHASE = "Ready"
|
||||
|
||||
function elapsedMs(start: number) {
|
||||
return Date.now() - start
|
||||
}
|
||||
|
||||
async function verifySandboxCreation(sandboxName: string): Promise<SandboxVerification> {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] verify:start sandbox=${sandboxName}`)
|
||||
try {
|
||||
const sandbox = await inspectSandbox(sandboxName)
|
||||
const phase = sandbox.phase ?? "Unknown"
|
||||
const rawPhase = sandbox.rawPhase ?? "Unknown"
|
||||
const verified = rawPhase === AUTHORITATIVE_SUCCESS_PHASE
|
||||
console.log(
|
||||
`[sandbox/create] verify:done sandbox=${sandboxName} rawPhase=${rawPhase} normalizedPhase=${phase} verified=${verified} elapsedMs=${elapsedMs(startedAt)}`,
|
||||
)
|
||||
|
||||
return {
|
||||
verified,
|
||||
summary: verified
|
||||
? `Verified via openshell sandbox get with authoritative phase (${rawPhase}).`
|
||||
: `Sandbox lookup succeeded, but authoritative phase was not ready (${rawPhase}); normalized phase=${phase}.`,
|
||||
details: {
|
||||
name: sandbox.name,
|
||||
id: sandbox.id,
|
||||
phase: sandbox.phase,
|
||||
namespace: sandbox.namespace,
|
||||
sshHostAlias: sandbox.sshHostAlias,
|
||||
rawPhase: sandbox.rawPhase,
|
||||
rawDetails: sandbox.rawDetails,
|
||||
},
|
||||
...(verified ? {} : { error: `Sandbox authoritative phase ${rawPhase} is not the required success state ${AUTHORITATIVE_SUCCESS_PHASE}.` }),
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Sandbox verification failed")
|
||||
console.log(`[sandbox/create] verify:error sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
return {
|
||||
verified: false,
|
||||
summary: "Create command returned success, but post-create authoritative verification failed.",
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runCommand(file: string, args: string[], env: NodeJS.ProcessEnv) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] command:start file=${file} args=${JSON.stringify(args)}`)
|
||||
console.log(`[sandbox/create] gateway-policy ${GATEWAY_REUSE_POLICY.replace(/\n/g, " | ")}`)
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(file, args, {
|
||||
env,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
})
|
||||
console.log(`[sandbox/create] command:done file=${file} elapsedMs=${elapsedMs(startedAt)} stdoutBytes=${String(stdout).length} stderrBytes=${String(stderr).length}`)
|
||||
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 ?? "Command failed")
|
||||
console.log(
|
||||
`[sandbox/create] command:error file=${file} elapsedMs=${elapsedMs(startedAt)} message=${message} stdoutBytes=${String(error?.stdout || "").length} stderrBytes=${String(error?.stderr || "").length}`,
|
||||
)
|
||||
return {
|
||||
ok: false as const,
|
||||
stdout: String(error?.stdout || "").trim(),
|
||||
stderr: String(error?.stderr || "").trim(),
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runCreateCommandBounded(file: string, args: string[], env: NodeJS.ProcessEnv, timeoutMs: number) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] bounded-command:start file=${file} args=${JSON.stringify(args)} timeoutMs=${timeoutMs}`)
|
||||
|
||||
return await new Promise<{
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}>((resolve) => {
|
||||
const child = spawn(file, args, {
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
let settled = false
|
||||
|
||||
const finish = (result: {
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += String(chunk)
|
||||
})
|
||||
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += String(chunk)
|
||||
})
|
||||
|
||||
child.on("error", (error) => {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Command failed")
|
||||
console.log(`[sandbox/create] bounded-command:error file=${file} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: false,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: message,
|
||||
})
|
||||
})
|
||||
|
||||
child.on("close", (code, signal) => {
|
||||
console.log(`[sandbox/create] bounded-command:close file=${file} elapsedMs=${elapsedMs(startedAt)} code=${code} signal=${signal} stdoutBytes=${stdout.length} stderrBytes=${stderr.length}`)
|
||||
finish({
|
||||
completed: true,
|
||||
timedOut: false,
|
||||
exitCode: code,
|
||||
signal,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
...(code === 0 ? {} : { error: `Command exited with code ${code}${signal ? ` signal ${signal}` : ""}` }),
|
||||
})
|
||||
})
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
console.log(`[sandbox/create] bounded-command:timeout file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGTERM`)
|
||||
child.kill("SIGTERM")
|
||||
setTimeout(() => {
|
||||
if (!settled) {
|
||||
console.log(`[sandbox/create] bounded-command:timeout-escalate file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGKILL`)
|
||||
child.kill("SIGKILL")
|
||||
}
|
||||
}, 2000)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: true,
|
||||
exitCode: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: `Command exceeded timeout of ${timeoutMs}ms`,
|
||||
})
|
||||
}, timeoutMs)
|
||||
})
|
||||
}
|
||||
|
||||
async function waitForSandboxReady(sandboxName: string, timeoutMs: number, intervalMs: number) {
|
||||
const startedAt = Date.now()
|
||||
let lastVerification: SandboxVerification | null = null
|
||||
let attempts = 0
|
||||
|
||||
while (elapsedMs(startedAt) < timeoutMs) {
|
||||
attempts += 1
|
||||
lastVerification = await verifySandboxCreation(sandboxName)
|
||||
console.log(`[sandbox/create] readiness:attempt sandbox=${sandboxName} attempt=${attempts} verified=${lastVerification.verified} elapsedMs=${elapsedMs(startedAt)}`)
|
||||
if (lastVerification.verified) {
|
||||
return {
|
||||
verified: true as const,
|
||||
verification: lastVerification,
|
||||
attempts,
|
||||
elapsedMs: elapsedMs(startedAt),
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalMs))
|
||||
}
|
||||
|
||||
return {
|
||||
verified: false as const,
|
||||
verification: lastVerification,
|
||||
attempts,
|
||||
elapsedMs: elapsedMs(startedAt),
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
blueprints: [
|
||||
{
|
||||
id: "nemoclaw-blueprint",
|
||||
label: "New NemoClaw Sandbox",
|
||||
description: "Bootstraps a full NemoClaw sandbox using the nemoclaw-blueprint workflow.",
|
||||
type: "blueprint",
|
||||
source: "~/NemoClaw/nemoclaw-blueprint/blueprint.yaml",
|
||||
supportsTailscale: true,
|
||||
},
|
||||
{
|
||||
id: "custom-sandbox",
|
||||
label: "New Custom Sandbox",
|
||||
description: "Create a generic OpenShell sandbox with a custom policy path.",
|
||||
type: "custom",
|
||||
source: "dashboard-custom",
|
||||
supportsTailscale: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestStartedAt = Date.now()
|
||||
console.log(`[sandbox/create] request:start elapsedMs=0`)
|
||||
try {
|
||||
const body = await request.json()
|
||||
const blueprint = typeof body?.blueprint === "string" ? body.blueprint : ""
|
||||
const sandboxName = validateSandboxName(typeof body?.sandboxName === "string" ? body.sandboxName.trim() : "")
|
||||
const policy = body?.policy && typeof body.policy === "object" ? body.policy : null
|
||||
const enableTailscale = Boolean(body?.enableTailscale)
|
||||
console.log(`[sandbox/create] request:parsed sandbox=${sandboxName} blueprint=${blueprint} enableTailscale=${enableTailscale} elapsedMs=${elapsedMs(requestStartedAt)}`)
|
||||
|
||||
if (!blueprint) {
|
||||
return NextResponse.json({ ok: false, error: "blueprint is required" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (blueprint === "nemoclaw-blueprint") {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
NEMOCLAW_SANDBOX_NAME: sandboxName,
|
||||
}
|
||||
|
||||
if (!enableTailscale) {
|
||||
env.NVIDIA_API_KEY = env.NVIDIA_API_KEY || "optional-local-mode"
|
||||
}
|
||||
|
||||
const result = await runCommand("/bin/bash", [NEMOCLAW_SETUP, sandboxName], env)
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: result.error,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
enableTailscale,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
const verification = await verifySandboxCreation(sandboxName)
|
||||
const created = verification.verified
|
||||
console.log(`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} elapsedMs=${elapsedMs(requestStartedAt)}`)
|
||||
|
||||
return NextResponse.json({
|
||||
ok: created,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
created,
|
||||
verified: verification.verified,
|
||||
verification,
|
||||
mode: "nemoclaw-blueprint",
|
||||
enableTailscale,
|
||||
gatewayReusePolicy: GATEWAY_REUSE_POLICY,
|
||||
setupPath: NEMOCLAW_SETUP,
|
||||
hostPath: HOST_PATH,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
note: created
|
||||
? (enableTailscale
|
||||
? "NemoClaw blueprint workflow completed with Tailscale-enabled prerequisites. Existing healthy OpenShell gateways are reused before any new gateway start is attempted."
|
||||
: "NemoClaw blueprint workflow completed in local/default mode. Existing healthy OpenShell gateways are reused before any new gateway start is attempted.")
|
||||
: "Blueprint command reported success, but the sandbox never reached a ready verification state afterward.",
|
||||
}, { status: created ? 200 : 502 })
|
||||
}
|
||||
|
||||
if (blueprint === "custom-sandbox") {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
const createAttempt = await runCreateCommandBounded(OPENSHELL_BIN, ["sandbox", "create", "--name", sandboxName], env, 15000)
|
||||
|
||||
if (createAttempt.completed && createAttempt.exitCode !== 0) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: createAttempt.error ?? `create command failed with exit code ${createAttempt.exitCode}`,
|
||||
stdout: createAttempt.stdout,
|
||||
stderr: createAttempt.stderr,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
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
|
||||
const policyPrepared = Boolean(policy)
|
||||
console.log(
|
||||
`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} createTimedOut=${createAttempt.timedOut} readinessAttempts=${readiness.attempts} elapsedMs=${elapsedMs(requestStartedAt)}`,
|
||||
)
|
||||
return NextResponse.json({
|
||||
ok: created,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
created,
|
||||
verified: verification.verified,
|
||||
verification,
|
||||
mode: "custom-sandbox",
|
||||
stdout: createAttempt.stdout,
|
||||
stderr: createAttempt.stderr,
|
||||
createCommand: {
|
||||
completed: createAttempt.completed,
|
||||
timedOut: createAttempt.timedOut,
|
||||
exitCode: createAttempt.exitCode,
|
||||
signal: createAttempt.signal,
|
||||
error: createAttempt.error,
|
||||
},
|
||||
readiness: {
|
||||
attempts: readiness.attempts,
|
||||
elapsedMs: readiness.elapsedMs,
|
||||
},
|
||||
policyPrepared,
|
||||
note: created
|
||||
? (createAttempt.timedOut
|
||||
? "Custom sandbox reached Ready even though the create CLI did not exit promptly."
|
||||
: (policyPrepared
|
||||
? "Custom sandbox created. Policy draft is prepared, but applying it live should be a follow-up action."
|
||||
: "Custom sandbox created."))
|
||||
: "Create command started, but the sandbox never reached a ready verification state afterward.",
|
||||
}, { status: created ? 200 : 502 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: false, error: `unknown blueprint: ${blueprint}` }, { status: 400 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Sandbox creation failed"
|
||||
const status = /required|must be|too long|unknown blueprint/.test(message) ? 400 : 500
|
||||
console.log(`[sandbox/create] request:error elapsedMs=${elapsedMs(requestStartedAt)} message=${message}`)
|
||||
return NextResponse.json({ ok: false, error: message }, { status })
|
||||
}
|
||||
}
|
||||
+388
-82
@@ -1,94 +1,400 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execFile } from "node:child_process"
|
||||
import { existsSync } from "node:fs"
|
||||
import { hostname, networkInterfaces } from "node:os"
|
||||
import { promisify } from "node:util"
|
||||
import { resolveRuntimeAuthority } from "@/app/lib/runtimeAuthority"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const HOME = process.env.HOME || ""
|
||||
|
||||
const NODE_BIN_CANDIDATES = [
|
||||
process.env.NODE_BIN,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.2/bin/node` : undefined,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.1/bin/node` : undefined,
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.2/bin/node",
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.1/bin/node",
|
||||
"/opt/homebrew/bin/node",
|
||||
"/usr/local/bin/node",
|
||||
"/usr/bin/node",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const NODE_BIN = NODE_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? NODE_BIN_CANDIDATES[0]
|
||||
const NEMOCLAW_BIN_CANDIDATES = [
|
||||
process.env.NEMOCLAW_BIN,
|
||||
HOME ? `${HOME}/.local/bin/nemoclaw` : undefined,
|
||||
HOME ? `${HOME}/.nemoclaw/source/bin/nemoclaw.js` : undefined,
|
||||
HOME ? `${HOME}/NemoClaw/bin/nemoclaw.js` : undefined,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.2/bin/nemoclaw` : undefined,
|
||||
"/Users/markmckeen/.local/bin/nemoclaw",
|
||||
"/Users/markmckeen/.nemoclaw/source/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/NemoClaw/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/NemoClaw-mmckeen/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.2/bin/nemoclaw",
|
||||
"/usr/local/bin/nemoclaw",
|
||||
"/opt/homebrew/bin/nemoclaw",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const NEMOCLAW_BIN =
|
||||
NEMOCLAW_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? NEMOCLAW_BIN_CANDIDATES[0]
|
||||
|
||||
const OPENSHELL_BIN_CANDIDATES = [
|
||||
process.env.OPENSHELL_BIN,
|
||||
HOME ? `${HOME}/.local/bin/openshell` : undefined,
|
||||
"/Users/markmckeen/.local/bin/openshell",
|
||||
"/Users/markmckeen/OpenShell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/scripts/bin/openshell",
|
||||
"/usr/local/bin/openshell",
|
||||
"/opt/homebrew/bin/openshell",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const OPENSHELL_BIN =
|
||||
OPENSHELL_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENSHELL_BIN_CANDIDATES[0]
|
||||
|
||||
type SandboxSummary = {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
status: string
|
||||
sshHostAlias: string
|
||||
hasSshConfig: boolean
|
||||
source: "openshell"
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
type NemoClawSummary = {
|
||||
available: boolean
|
||||
defaultSandboxNames: string[]
|
||||
serviceLines: string[]
|
||||
summaryLines: string[]
|
||||
source: "nemoclaw-cli" | "none"
|
||||
}
|
||||
|
||||
type SandboxItem = {
|
||||
metadata: {
|
||||
name: string
|
||||
namespace: string
|
||||
labels: Record<string, string>
|
||||
}
|
||||
spec: {
|
||||
template: {
|
||||
image: string | null
|
||||
}
|
||||
}
|
||||
status: {
|
||||
phase: string
|
||||
podIP: string | null
|
||||
conditions: Array<{
|
||||
type: string
|
||||
status: string
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseField(output: string, label: string) {
|
||||
const normalizedLabel = label.toLowerCase()
|
||||
const line = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith(`${normalizedLabel}:`))
|
||||
|
||||
return line ? line.slice(label.length + 1).trim() : null
|
||||
}
|
||||
|
||||
function parseSshHostAlias(sshConfig: string, fallbackName: string) {
|
||||
const hostLine = sshConfig
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith("host "))
|
||||
|
||||
const alias = hostLine
|
||||
?.split(/\s+/)
|
||||
.slice(1)
|
||||
.find((entry) => entry !== "*")
|
||||
|
||||
return alias || `openshell-${fallbackName}`
|
||||
}
|
||||
|
||||
function normalizePhase(phase: string | null) {
|
||||
const value = (phase ?? "Unknown").toLowerCase()
|
||||
|
||||
switch (value) {
|
||||
case "ready":
|
||||
return "Running"
|
||||
case "provisioning":
|
||||
return "Pending"
|
||||
case "deleting":
|
||||
return "Stopping"
|
||||
case "error":
|
||||
return "Error"
|
||||
default:
|
||||
return phase ?? "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry &&
|
||||
!/^name\s+/i.test(entry) &&
|
||||
!/^[\s\-=]+$/.test(entry) &&
|
||||
!/^no sandboxes found\.?$/i.test(entry)
|
||||
)
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
function parseDefaultSandboxNames(output: string) {
|
||||
return new Set(
|
||||
output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry))
|
||||
.filter((entry) => /^\s{2,}[\w.-]+(?:\s+\*)?\s*$/.test(entry) && entry.includes("*"))
|
||||
.map((entry) => entry.replace("*", "").trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
}
|
||||
|
||||
function buildNemoClawSummary(output: string | null, defaultSandboxNames: Set<string>): NemoClawSummary {
|
||||
if (!output) {
|
||||
return {
|
||||
available: false,
|
||||
defaultSandboxNames: [],
|
||||
serviceLines: [],
|
||||
summaryLines: [],
|
||||
source: "none",
|
||||
}
|
||||
}
|
||||
|
||||
const lines = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const serviceLines = lines.filter((entry) => /\((running|stopped|failed|error|unknown)\)/i.test(entry))
|
||||
|
||||
return {
|
||||
available: true,
|
||||
defaultSandboxNames: Array.from(defaultSandboxNames),
|
||||
serviceLines,
|
||||
summaryLines: lines.slice(0, 20),
|
||||
source: "nemoclaw-cli",
|
||||
}
|
||||
}
|
||||
|
||||
async function execNemoclaw(args: string[]) {
|
||||
const env = {
|
||||
...process.env,
|
||||
PATH: `${process.env.PATH ?? ""}:${HOME ? `${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`,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
|
||||
const command = /\.(?:c?m?js|ts)$/i.test(NEMOCLAW_BIN)
|
||||
? execFileAsync(NODE_BIN, [NEMOCLAW_BIN, ...args], { env })
|
||||
: execFileAsync(NEMOCLAW_BIN, args, { env })
|
||||
|
||||
const { stdout, stderr } = await command
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
async function execOpenShell(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
})
|
||||
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
|
||||
function readHostIdentity() {
|
||||
const interfaces = networkInterfaces()
|
||||
const preferred = ["en0", "en1", "bridge0", "lo0"]
|
||||
|
||||
for (const name of preferred) {
|
||||
const entries = interfaces[name] ?? []
|
||||
const match = entries.find((entry) => entry.family === "IPv4" && !entry.internal)
|
||||
if (match?.address) {
|
||||
return { hostname: hostname(), address: match.address, interface: name }
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, entries] of Object.entries(interfaces)) {
|
||||
const match = (entries ?? []).find((entry) => entry.family === "IPv4" && !entry.internal)
|
||||
if (match?.address) {
|
||||
return { hostname: hostname(), address: match.address, interface: name }
|
||||
}
|
||||
}
|
||||
|
||||
return { hostname: hostname(), address: "127.0.0.1", interface: "lo0" }
|
||||
}
|
||||
|
||||
async function readSandbox(name: string, defaultSandboxNames: Set<string>): Promise<{ summary: SandboxSummary; pod: SandboxItem }> {
|
||||
try {
|
||||
const [{ stdout: detailsStdout }, { stdout: sshStdout }] = await Promise.all([
|
||||
execOpenShell(["sandbox", "get", name]),
|
||||
execOpenShell(["sandbox", "ssh-config", name]),
|
||||
])
|
||||
|
||||
const sandboxName = parseField(detailsStdout, "Name") ?? name
|
||||
const namespace = parseField(detailsStdout, "Namespace") ?? "openshell"
|
||||
const phase = normalizePhase(parseField(detailsStdout, "Phase"))
|
||||
const sandboxId = parseField(detailsStdout, "Id") ?? sandboxName
|
||||
const sshConfig = sshStdout.trim()
|
||||
const sshHostAlias = parseSshHostAlias(sshConfig, sandboxName)
|
||||
const isDefault = defaultSandboxNames.has(sandboxName)
|
||||
|
||||
return {
|
||||
summary: {
|
||||
id: sandboxId,
|
||||
name: sandboxName,
|
||||
namespace,
|
||||
status: phase,
|
||||
sshHostAlias,
|
||||
hasSshConfig: Boolean(sshConfig),
|
||||
source: "openshell",
|
||||
isDefault,
|
||||
},
|
||||
pod: {
|
||||
metadata: {
|
||||
name: sandboxName,
|
||||
namespace,
|
||||
labels: {
|
||||
"nemoclaw.ai/sandbox-name": sandboxName,
|
||||
...(sandboxId ? { "nemoclaw.ai/sandbox-id": sandboxId } : {}),
|
||||
...(isDefault ? { "nemoclaw.ai/default": "true" } : {}),
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
template: {
|
||||
image: null,
|
||||
},
|
||||
},
|
||||
status: {
|
||||
phase,
|
||||
podIP: sshHostAlias,
|
||||
conditions: [
|
||||
{
|
||||
type: "Ready",
|
||||
status: phase === "Running" ? "True" : "False",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
const sandboxName = name
|
||||
const isDefault = defaultSandboxNames.has(sandboxName)
|
||||
return {
|
||||
summary: {
|
||||
id: sandboxName,
|
||||
name: sandboxName,
|
||||
namespace: "openshell",
|
||||
status: "Unknown",
|
||||
sshHostAlias: `openshell-${sandboxName}`,
|
||||
hasSshConfig: false,
|
||||
source: "openshell",
|
||||
isDefault,
|
||||
},
|
||||
pod: {
|
||||
metadata: {
|
||||
name: sandboxName,
|
||||
namespace: "openshell",
|
||||
labels: {
|
||||
"nemoclaw.ai/sandbox-name": sandboxName,
|
||||
"nemoclaw.ai/sandbox-id": sandboxName,
|
||||
...(isDefault ? { "nemoclaw.ai/default": "true" } : {}),
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
template: {
|
||||
image: null,
|
||||
},
|
||||
},
|
||||
status: {
|
||||
phase: "Unknown",
|
||||
podIP: `openshell-${sandboxName}`,
|
||||
conditions: [
|
||||
{
|
||||
type: "Ready",
|
||||
status: "False",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Use docker exec with a timeout and direct kubectl inside container
|
||||
const { exec } = await import('child_process')
|
||||
const util = await import('util')
|
||||
const execPromise = util.promisify(exec)
|
||||
const [{ stdout: sandboxListStdout }, nemoclawListResult, nemoclawStatusResult] = await Promise.all([
|
||||
execOpenShell(["sandbox", "list"]),
|
||||
execNemoclaw(["list"]).catch(() => null),
|
||||
execNemoclaw(["status"]).catch(() => null),
|
||||
])
|
||||
|
||||
const dockerPath = '/Applications/Docker.app/Contents/Resources/bin/docker'
|
||||
|
||||
// Run kubectl inside container with explicit kubeconfig
|
||||
const command = `${dockerPath} exec openshell-cluster-openshell /bin/sh -c 'KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get pods -o json -n agent-sandbox-system'`
|
||||
|
||||
const execWithTimeout = (cmd: string, timeoutMs: number): Promise<{ stdout: string; stderr: string }> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = exec(cmd, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve({ stdout, stderr })
|
||||
}
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
child.kill('SIGKILL')
|
||||
reject(new Error('Command timed out'))
|
||||
}, timeoutMs)
|
||||
})
|
||||
}
|
||||
|
||||
const { stdout, stderr } = await execWithTimeout(command, 10000)
|
||||
const defaultSandboxNames = parseDefaultSandboxNames(nemoclawListResult?.stdout ?? "")
|
||||
const names = parseOpenShellSandboxNames(sandboxListStdout)
|
||||
const results = await Promise.all(names.map((name) => readSandbox(name, defaultSandboxNames)))
|
||||
const sandboxes = results.map((result) => result.summary)
|
||||
const items = results.map((result) => result.pod)
|
||||
const nemoclaw = buildNemoClawSummary(nemoclawStatusResult?.stdout ?? null, defaultSandboxNames)
|
||||
|
||||
if (stderr && !stderr.includes('Waiting')) {
|
||||
console.error('kubectl stderr:', stderr)
|
||||
}
|
||||
const authorities = sandboxes.map((sandbox) => ({
|
||||
sandboxId: sandbox.id,
|
||||
...resolveRuntimeAuthority({ sandboxId: sandbox.id }),
|
||||
}))
|
||||
|
||||
if (!stdout.trim()) {
|
||||
throw new Error('No output from kubectl')
|
||||
}
|
||||
const inventoryCount = sandboxes.length
|
||||
const hasMappedFallbackWithoutInventory = inventoryCount === 0
|
||||
|
||||
const pods = JSON.parse(stdout)
|
||||
|
||||
// Filter to only sandbox-related pods
|
||||
const sandboxPods = pods.items
|
||||
.filter((pod: any) =>
|
||||
pod.metadata.namespace === 'agent-sandbox-system' ||
|
||||
pod.metadata.name.includes('sandbox')
|
||||
)
|
||||
.map((pod: any) => ({
|
||||
metadata: {
|
||||
name: pod.metadata.name,
|
||||
namespace: pod.metadata.namespace
|
||||
},
|
||||
status: {
|
||||
phase: pod.status.phase,
|
||||
podIP: pod.status.podIP,
|
||||
conditions: pod.status.conditions || []
|
||||
}
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
pods: { items: sandboxPods },
|
||||
message: 'Real telemetry fetched from container'
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching real telemetry:', error.message)
|
||||
|
||||
// Fallback to mock data
|
||||
return NextResponse.json({
|
||||
pods: {
|
||||
items: [
|
||||
{
|
||||
metadata: { name: 'agent-sandbox-1', namespace: 'agent-sandbox-system' },
|
||||
status: {
|
||||
phase: 'Running',
|
||||
podIP: '10.42.0.2',
|
||||
conditions: [{ type: 'Ready', status: 'True' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
metadata: { name: 'agent-sandbox-2', namespace: 'agent-sandbox-system' },
|
||||
status: {
|
||||
phase: 'Pending',
|
||||
podIP: null,
|
||||
conditions: [{ type: 'Ready', status: 'False' }]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
message: `Using mock data (${error.message})`
|
||||
sandboxes,
|
||||
pods: { items },
|
||||
nemoclaw,
|
||||
host: readHostIdentity(),
|
||||
source: "openshell-cli",
|
||||
authoritySource: "runtimeAuthority",
|
||||
truthState: hasMappedFallbackWithoutInventory ? "unverified" : "verified",
|
||||
degraded: hasMappedFallbackWithoutInventory,
|
||||
inventoryCount,
|
||||
authorities: authorities.map((authority) => ({
|
||||
sandboxId: authority.sandboxId,
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
})),
|
||||
defaultSource: defaultSandboxNames.size > 0 ? "nemoclaw-cli" : "none",
|
||||
count: inventoryCount,
|
||||
message: hasMappedFallbackWithoutInventory
|
||||
? "Fetched live OpenShell inventory: zero sandboxes reported, so any mapped NemoClaw dashboard should be treated as fallback-only."
|
||||
: "Fetched live sandbox inventory from the clean OpenShell runtime",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error fetching real telemetry:", error)
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : "Failed to fetch live OpenShell sandbox inventory",
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import CompactGauge from './CompactGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -9,6 +9,7 @@ interface TelemetryData {
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
interface Sandbox {
|
||||
@@ -30,25 +31,6 @@ export default function CompactTelemetryDisplay() {
|
||||
fetchSandboxes()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
@@ -67,7 +49,7 @@ export default function CompactTelemetryDisplay() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
const fetchTelemetry = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/combined')
|
||||
const data = await response.json()
|
||||
@@ -75,10 +57,29 @@ export default function CompactTelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchCombinedTelemetry = fetchTelemetry
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-40">
|
||||
|
||||
@@ -8,97 +8,44 @@ type EndpointTls = "" | "terminate" | "passthrough"
|
||||
type EndpointEnforcement = "" | "enforce" | "audit"
|
||||
type EndpointAccess = "" | "read-only" | "read-write" | "full"
|
||||
|
||||
interface NetworkRule {
|
||||
method: string
|
||||
path: string
|
||||
}
|
||||
|
||||
interface NetworkEndpoint {
|
||||
host: string
|
||||
port: string
|
||||
protocol: EndpointProtocol
|
||||
tls: EndpointTls
|
||||
enforcement: EndpointEnforcement
|
||||
access: EndpointAccess
|
||||
rules: NetworkRule[]
|
||||
}
|
||||
|
||||
interface NetworkBinary {
|
||||
path: string
|
||||
}
|
||||
|
||||
interface NetworkPolicyBlock {
|
||||
key: string
|
||||
name: string
|
||||
endpoints: NetworkEndpoint[]
|
||||
binaries: NetworkBinary[]
|
||||
}
|
||||
|
||||
interface NetworkRule { method: string; path: string }
|
||||
interface NetworkEndpoint { host: string; port: string; protocol: EndpointProtocol; tls: EndpointTls; enforcement: EndpointEnforcement; access: EndpointAccess; rules: NetworkRule[] }
|
||||
interface NetworkBinary { path: string }
|
||||
interface NetworkPolicyBlock { key: string; name: string; endpoints: NetworkEndpoint[]; binaries: NetworkBinary[] }
|
||||
type OpenShellPolicy = OpenShellPolicyShape
|
||||
|
||||
type BlueprintOption = {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
type: "blueprint" | "custom"
|
||||
source: string
|
||||
supportsTailscale?: boolean
|
||||
}
|
||||
|
||||
interface ConfigurationPanelProps {
|
||||
sandboxId: string
|
||||
mode?: 'existing' | 'create'
|
||||
onCreateSuccess?: (sandboxId: string) => void | Promise<void>
|
||||
onInventoryRefresh?: () => Promise<unknown>
|
||||
}
|
||||
|
||||
function FieldHelp({ text }: { text: string }) {
|
||||
return (
|
||||
<span className="ml-2 inline-flex align-middle group relative">
|
||||
<span className="w-4 h-4 rounded-full border border-[var(--foreground-dim)] text-[10px] text-[var(--foreground-dim)] flex items-center justify-center cursor-help">?</span>
|
||||
<span className="pointer-events-none absolute left-0 top-6 z-50 hidden w-80 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-panel)] p-2 text-[11px] text-[var(--foreground)] shadow-lg group-hover:block">
|
||||
{text}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
return <span className="ml-2 inline-flex align-middle group relative"><span className="w-4 h-4 rounded-full border border-[var(--foreground-dim)] text-[10px] text-[var(--foreground-dim)] flex items-center justify-center cursor-help">?</span><span className="pointer-events-none absolute left-0 top-6 z-50 hidden w-80 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-panel)] p-2 text-[11px] text-[var(--foreground)] shadow-lg group-hover:block">{text}</span></span>
|
||||
}
|
||||
|
||||
function Badge({ children, tone }: { children: React.ReactNode; tone: "dynamic" | "static" | "danger" }) {
|
||||
const cls = tone === "dynamic"
|
||||
? "bg-[rgba(118,185,0,0.12)] text-[var(--nvidia-green)] border-[rgba(118,185,0,0.35)]"
|
||||
: tone === "danger"
|
||||
? "bg-[rgba(220,38,38,0.12)] text-red-400 border-[rgba(220,38,38,0.35)]"
|
||||
: "bg-[rgba(245,158,11,0.10)] text-amber-400 border-[rgba(245,158,11,0.35)]"
|
||||
const cls = tone === "dynamic" ? "bg-[rgba(118,185,0,0.12)] text-[var(--nvidia-green)] border-[rgba(118,185,0,0.35)]" : tone === "danger" ? "bg-[rgba(220,38,38,0.12)] text-red-400 border-[rgba(220,38,38,0.35)]" : "bg-[rgba(245,158,11,0.10)] text-amber-400 border-[rgba(245,158,11,0.35)]"
|
||||
return <span className={`text-[10px] uppercase tracking-wider border px-2 py-1 rounded-sm ${cls}`}>{children}</span>
|
||||
}
|
||||
|
||||
function TextListEditor({ label, tooltipText, value, onChange, placeholder }: {
|
||||
label: string
|
||||
tooltipText: string
|
||||
value: string[]
|
||||
onChange: (v: string[]) => void
|
||||
placeholder: string
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">
|
||||
{label}
|
||||
<FieldHelp text={tooltipText} />
|
||||
</label>
|
||||
<textarea
|
||||
value={value.join("\n")}
|
||||
onChange={(e) => onChange(e.target.value.split("\n").map(s => s.trim()).filter(Boolean))}
|
||||
placeholder={placeholder}
|
||||
rows={4}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
function TextListEditor({ label, tooltipText, value, onChange, placeholder }: { label: string; tooltipText: string; value: string[]; onChange: (v: string[]) => void; placeholder: string }) {
|
||||
return <div className="space-y-2"><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">{label}<FieldHelp text={tooltipText} /></label><textarea value={value.join("\n")} onChange={(e) => onChange(e.target.value.split("\n").map(s => s.trim()).filter(Boolean))} placeholder={placeholder} rows={4} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" /></div>
|
||||
}
|
||||
|
||||
const defaultPolicy: OpenShellPolicy = {
|
||||
version: 1,
|
||||
filesystem_policy: {
|
||||
include_workdir: true,
|
||||
read_only: ["/usr", "/lib", "/etc", "/proc", "/dev/urandom"],
|
||||
read_write: ["/sandbox", "/tmp", "/dev/null"],
|
||||
},
|
||||
landlock: {
|
||||
compatibility: "best_effort",
|
||||
},
|
||||
process: {
|
||||
run_as_user: "sandbox",
|
||||
run_as_group: "sandbox",
|
||||
},
|
||||
filesystem_policy: { include_workdir: true, read_only: ["/usr", "/lib", "/etc", "/proc", "/dev/urandom"], read_write: ["/sandbox", "/tmp", "/dev/null"] },
|
||||
landlock: { compatibility: "best_effort" },
|
||||
process: { run_as_user: "sandbox", run_as_group: "sandbox" },
|
||||
network_policies: {},
|
||||
}
|
||||
|
||||
@@ -111,67 +58,39 @@ function normalizeFromApi(data: any): OpenShellPolicy {
|
||||
read_only: Array.isArray(current.filesystem_policy?.read_only) ? current.filesystem_policy.read_only : defaultPolicy.filesystem_policy.read_only,
|
||||
read_write: Array.isArray(current.filesystem_policy?.read_write) ? current.filesystem_policy.read_write : defaultPolicy.filesystem_policy.read_write,
|
||||
},
|
||||
landlock: {
|
||||
compatibility: current.landlock?.compatibility === "hard_requirement" ? "hard_requirement" : "best_effort",
|
||||
},
|
||||
process: {
|
||||
run_as_user: String(current.process?.run_as_user ?? "sandbox"),
|
||||
run_as_group: String(current.process?.run_as_group ?? "sandbox"),
|
||||
},
|
||||
landlock: { compatibility: current.landlock?.compatibility === "hard_requirement" ? "hard_requirement" : "best_effort" },
|
||||
process: { run_as_user: String(current.process?.run_as_user ?? "sandbox"), run_as_group: String(current.process?.run_as_group ?? "sandbox") },
|
||||
network_policies: current.network_policies && typeof current.network_policies === "object" ? current.network_policies : {},
|
||||
}
|
||||
}
|
||||
|
||||
function policyBlocksFromPolicy(policy: OpenShellPolicy): NetworkPolicyBlock[] {
|
||||
return Object.entries(policy.network_policies).map(([key, value]) => ({
|
||||
key,
|
||||
name: value.name || key,
|
||||
endpoints: (value.endpoints || []).map((ep) => ({
|
||||
host: ep.host || "",
|
||||
port: String(ep.port ?? "443"),
|
||||
protocol: ep.protocol === "rest" ? "rest" : "",
|
||||
tls: ep.tls === "terminate" || ep.tls === "passthrough" ? ep.tls : "",
|
||||
enforcement: ep.enforcement === "enforce" || ep.enforcement === "audit" ? ep.enforcement : "",
|
||||
access: ep.access === "read-only" || ep.access === "read-write" || ep.access === "full" ? ep.access : "",
|
||||
rules: Array.isArray(ep.rules) ? ep.rules.map((r) => ({ method: r.allow?.method || "GET", path: r.allow?.path || "/**" })) : [],
|
||||
})),
|
||||
binaries: (value.binaries || []).map((b) => ({ path: b.path || "" })),
|
||||
}))
|
||||
return Object.entries(policy.network_policies).map(([key, value]) => ({ key, name: value.name || key, endpoints: (value.endpoints || []).map((ep) => ({ host: ep.host || "", port: String(ep.port ?? "443"), protocol: ep.protocol === "rest" ? "rest" : "", tls: ep.tls === "terminate" || ep.tls === "passthrough" ? ep.tls : "", enforcement: ep.enforcement === "enforce" || ep.enforcement === "audit" ? ep.enforcement : "", access: ep.access === "read-only" || ep.access === "read-write" || ep.access === "full" ? ep.access : "", rules: Array.isArray(ep.rules) ? ep.rules.map((r) => ({ method: r.allow?.method || "GET", path: r.allow?.path || "/**" })) : [] })), binaries: (value.binaries || []).map((b) => ({ path: b.path || "" })) }))
|
||||
}
|
||||
|
||||
function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_policies"] {
|
||||
const out: OpenShellPolicy["network_policies"] = {}
|
||||
for (const block of blocks) {
|
||||
const key = block.key.trim()
|
||||
if (!key) continue
|
||||
out[key] = {
|
||||
name: block.name.trim() || key,
|
||||
endpoints: block.endpoints.filter((ep) => ep.host.trim() && ep.port.trim()).map((ep) => ({
|
||||
host: ep.host.trim(),
|
||||
port: Number(ep.port),
|
||||
...(ep.protocol ? { protocol: ep.protocol } : {}),
|
||||
...(ep.tls ? { tls: ep.tls } : {}),
|
||||
...(ep.enforcement ? { enforcement: ep.enforcement } : {}),
|
||||
...(ep.access ? { access: ep.access } : {}),
|
||||
...(!ep.access && ep.rules.length ? { rules: ep.rules.filter((r) => r.method.trim() && r.path.trim()).map((r) => ({ allow: { method: r.method.trim(), path: r.path.trim() } })) } : {}),
|
||||
})),
|
||||
binaries: block.binaries.filter((b) => b.path.trim()).map((b) => ({ path: b.path.trim() })),
|
||||
}
|
||||
const key = block.key.trim(); if (!key) continue
|
||||
out[key] = { name: block.name.trim() || key, endpoints: block.endpoints.filter((ep) => ep.host.trim() && ep.port.trim()).map((ep) => ({ host: ep.host.trim(), port: Number(ep.port), ...(ep.protocol ? { protocol: ep.protocol } : {}), ...(ep.tls ? { tls: ep.tls } : {}), ...(ep.enforcement ? { enforcement: ep.enforcement } : {}), ...(ep.access ? { access: ep.access } : {}), ...(!ep.access && ep.rules.length ? { rules: ep.rules.filter((r) => r.method.trim() && r.path.trim()).map((r) => ({ allow: { method: r.method.trim(), path: r.path.trim() } })) } : {}) })), binaries: block.binaries.filter((b) => b.path.trim()).map((b) => ({ path: b.path.trim() })) }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export default function ConfigurationPanel({ sandboxId, mode = 'existing' }: ConfigurationPanelProps) {
|
||||
export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess, onInventoryRefresh }: ConfigurationPanelProps) {
|
||||
const [policy, setPolicy] = useState<OpenShellPolicy>(defaultPolicy)
|
||||
const [blocks, setBlocks] = useState<NetworkPolicyBlock[]>([])
|
||||
const [loading, setLoading] = useState(mode === 'existing')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [message, setMessage] = useState("")
|
||||
const [selectedPreset, setSelectedPreset] = useState<SecurityPresetId | ''>('')
|
||||
const [blueprints, setBlueprints] = useState<BlueprintOption[]>([])
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState<string>('nemoclaw-blueprint')
|
||||
const [sandboxName, setSandboxName] = useState<string>('')
|
||||
const [enableTailscale, setEnableTailscale] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'create') {
|
||||
setLoading(false)
|
||||
fetch('/api/sandbox/create', { cache: 'no-store' }).then((res) => res.json()).then((data) => { if (Array.isArray(data?.blueprints)) setBlueprints(data.blueprints) }).catch(() => {})
|
||||
return
|
||||
}
|
||||
let active = true
|
||||
@@ -197,184 +116,60 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing' }: Con
|
||||
|
||||
const assembledPolicy = useMemo(() => ({ ...policy, network_policies: blocksToPolicy(blocks) }), [policy, blocks])
|
||||
const activePreset = selectedPreset ? getSecurityPreset(selectedPreset) : null
|
||||
const showDangerWarning = activePreset?.id === 'spicy' || activePreset?.id === 'ultra-lobster'
|
||||
const activeBlueprint = blueprints.find((bp) => bp.id === selectedBlueprint)
|
||||
|
||||
function applyPreset(presetId: SecurityPresetId) {
|
||||
const preset = getSecurityPreset(presetId)
|
||||
if (!preset) return
|
||||
setSelectedPreset(presetId)
|
||||
setPolicy(preset.policy)
|
||||
setBlocks(policyBlocksFromPolicy(preset.policy))
|
||||
setMessage(`${preset.label} applied. Review before saving.${preset.id === 'spicy' || preset.id === 'ultra-lobster' ? ' Warning: this preset is intentionally permissive.' : ''}`)
|
||||
const preset = getSecurityPreset(presetId); if (!preset) return
|
||||
setSelectedPreset(presetId); setPolicy(preset.policy); setBlocks(policyBlocksFromPolicy(preset.policy)); setMessage(`${preset.label} applied. Review before saving.`)
|
||||
}
|
||||
|
||||
async function savePolicy() {
|
||||
try {
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ policy: assembledPolicy, preset: selectedPreset || null, mode }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error || "Failed to save policy")
|
||||
setMessage(mode === 'create'
|
||||
? 'Preset and policy prepared for new sandbox creation. Static sections will apply at create time.'
|
||||
: 'Policy saved. Dynamic network policy can apply live; static sections require sandbox recreation.')
|
||||
setSaving(true); setMessage("")
|
||||
if (mode === 'create') {
|
||||
if (!sandboxName.trim()) throw new Error('sandbox name is required')
|
||||
const res = await fetch('/api/sandbox/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: sandboxName.trim(), enableTailscale, policy: assembledPolicy, preset: selectedPreset || null }) })
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error([data.error, data.verification?.summary, data.verification?.error, data.gatewayReusePolicy, 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 via ${data.mode}.${data.enableTailscale ? ' Tailscale-enabled path requested.' : ' Tailscale disabled.'}`,
|
||||
data.verification?.summary,
|
||||
data.gatewayReusePolicy,
|
||||
'Inventory refresh requested immediately.',
|
||||
].filter(Boolean).join('\n\n'))
|
||||
if (createdSandboxId && onCreateSuccess) {
|
||||
await onCreateSuccess(createdSandboxId)
|
||||
}
|
||||
return
|
||||
}
|
||||
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ policy: assembledPolicy, preset: selectedPreset || null, mode }) })
|
||||
const data = await res.json(); if (!res.ok) throw new Error(data.error || "Failed to save policy")
|
||||
setMessage('Policy saved. Dynamic network policy can apply live; static sections require sandbox recreation.')
|
||||
} catch (err) {
|
||||
setMessage(err instanceof Error ? err.message : "Failed to save policy")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
} finally { setSaving(false) }
|
||||
}
|
||||
|
||||
function updateBlock(idx: number, next: NetworkPolicyBlock) {
|
||||
setBlocks((prev) => prev.map((b, i) => (i === idx ? next : b)))
|
||||
}
|
||||
|
||||
function addBlock() {
|
||||
setBlocks((prev) => [...prev, {
|
||||
key: `policy_${prev.length + 1}`,
|
||||
name: `policy-${prev.length + 1}`,
|
||||
endpoints: [{ host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "read-only", rules: [] }],
|
||||
binaries: [{ path: "" }],
|
||||
}])
|
||||
}
|
||||
function updateBlock(idx: number, next: NetworkPolicyBlock) { setBlocks((prev) => prev.map((b, i) => (i === idx ? next : b))) }
|
||||
function addBlock() { setBlocks((prev) => [...prev, { key: `policy_${prev.length + 1}`, name: `policy-${prev.length + 1}`, endpoints: [{ host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "read-only", rules: [] }], binaries: [{ path: "" }] }]) }
|
||||
|
||||
return (
|
||||
<div className="panel p-6 mt-6 border-t-2 border-[var(--nvidia-green)]">
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]">
|
||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{sandboxId} — {mode === 'create' ? 'NEW SANDBOX PRESET + POLICY' : 'OPENSHELL POLICY'}</h4>
|
||||
<div className="flex gap-2">
|
||||
<Badge tone="static">Static / Recreate Required</Badge>
|
||||
<Badge tone="dynamic">Dynamic / Apply Live</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : (
|
||||
<div className="space-y-8">
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p>
|
||||
</div>
|
||||
<div className="min-w-[260px]">
|
||||
<select
|
||||
value={selectedPreset}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value as SecurityPresetId | ''
|
||||
setSelectedPreset(value)
|
||||
if (value) applyPreset(value)
|
||||
}}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"
|
||||
>
|
||||
<option value="">Select preset…</option>
|
||||
{SECURITY_PRESETS.map((preset) => (
|
||||
<option key={preset.id} value={preset.id}>{preset.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activePreset && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span>
|
||||
<Badge tone={showDangerWarning ? 'danger' : 'dynamic'}>{activePreset.danger.replace('-', ' ')}</Badge>
|
||||
{showDangerWarning && <Badge tone="danger">Dangerous / Permissive</Badge>}
|
||||
</div>
|
||||
<p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p>
|
||||
{(activePreset.id === 'spicy' || activePreset.id === 'ultra-lobster') && (
|
||||
<div className="rounded-sm border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-300">
|
||||
Warning: {activePreset.label} may be dangerous due to its permissive security stance. Use only on trusted lab workloads.
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wider text-[var(--foreground-dim)] mb-2">Preset exec allowlist</p>
|
||||
<pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-[11px] text-[var(--foreground)]">{activePreset.execAllowlist.paths.join('\n')}</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div>
|
||||
<label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono">
|
||||
<input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />
|
||||
Include workdir
|
||||
<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." />
|
||||
</label>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" />
|
||||
<TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Landlock + Process</h5><Badge tone="static">Static</Badge></div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Landlock compatibility<FieldHelp text="best_effort uses the highest kernel ABI available. hard_requirement fails if the required ABI is unavailable." /></label>
|
||||
<select value={policy.landlock.compatibility} onChange={(e) => setPolicy({ ...policy, landlock: { compatibility: e.target.value as LandlockCompatibility } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono"><option value="best_effort">best_effort</option><option value="hard_requirement">hard_requirement</option></select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Run as user<FieldHelp text="OS-level user for the sandbox process. Upstream policy validation expects sandbox; root is rejected." /></label>
|
||||
<input value={policy.process.run_as_user} onChange={(e) => setPolicy({ ...policy, process: { ...policy.process, run_as_user: e.target.value } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Run as group<FieldHelp text="OS-level group for the sandbox process. Upstream policy validation expects sandbox; root is rejected." /></label>
|
||||
<input value={policy.process.run_as_group} onChange={(e) => setPolicy({ ...policy, process: { ...policy.process, run_as_group: e.target.value } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div>
|
||||
<button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)]">Named endpoint + binary allowlists. These are hot-reloadable on running sandboxes via policy updates.</p>
|
||||
<div className="space-y-6">
|
||||
{blocks.length === 0 && <div className="text-sm text-[var(--foreground-dim)]">No network policies defined.</div>}
|
||||
{blocks.map((block, idx) => (
|
||||
<div key={idx} className="border border-[var(--border-subtle)] rounded-sm p-4 space-y-4 bg-[var(--background-tertiary)]">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Policy key<FieldHelp text="Logical identifier in network_policies map." /></label><input value={block.key} onChange={(e) => updateBlock(idx, { ...block, key: e.target.value })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" /></div>
|
||||
<div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Display name<FieldHelp text="Optional display name used in logs; defaults to the key." /></label><input value={block.name} onChange={(e) => updateBlock(idx, { ...block, name: e.target.value })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" /></div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="text-xs uppercase tracking-wider text-[var(--foreground)]">Endpoints</div>
|
||||
{block.endpoints.map((ep, epIdx) => (
|
||||
<div key={epIdx} className="grid grid-cols-1 md:grid-cols-6 gap-3 border border-[var(--border-subtle)] p-3 rounded-sm">
|
||||
<input placeholder="host" value={ep.host} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, host: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
|
||||
<input placeholder="port" value={ep.port} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, port: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
|
||||
<select value={ep.protocol} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, protocol: e.target.value as EndpointProtocol }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">protocol</option><option value="rest">rest</option></select>
|
||||
<select value={ep.tls} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, tls: e.target.value as EndpointTls }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">tls</option><option value="terminate">terminate</option><option value="passthrough">passthrough</option></select>
|
||||
<select value={ep.enforcement} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, enforcement: e.target.value as EndpointEnforcement }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">enforcement</option><option value="enforce">enforce</option><option value="audit">audit</option></select>
|
||||
<select value={ep.access} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, access: e.target.value as EndpointAccess }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">rules mode</option><option value="read-only">read-only</option><option value="read-write">read-write</option><option value="full">full</option></select>
|
||||
</div>
|
||||
))}
|
||||
<button onClick={() => updateBlock(idx, { ...block, endpoints: [...block.endpoints, { host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "", rules: [{ method: "GET", path: "/**" }] }] })} className="px-3 py-2 rounded-sm bg-[var(--background)] text-xs font-mono uppercase tracking-wider">Add endpoint</button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs uppercase tracking-wider text-[var(--foreground)]">Binaries</div>
|
||||
{block.binaries.map((bin, binIdx) => (<input key={binIdx} placeholder="/usr/bin/curl" value={bin.path} onChange={(e) => { const next = [...block.binaries]; next[binIdx] = { path: e.target.value }; updateBlock(idx, { ...block, binaries: next }) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" />))}
|
||||
<button onClick={() => updateBlock(idx, { ...block, binaries: [...block.binaries, { path: "" }] })} className="px-3 py-2 rounded-sm bg-[var(--background)] text-xs font-mono uppercase tracking-wider">Add binary</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div className="flex items-center justify-between"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON Preview</h5><button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">{saving ? "Saving…" : mode === 'create' ? 'Use For New Sandbox' : 'Save Policy'}</button></div>
|
||||
<pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre>
|
||||
{message && <div className="text-sm text-[var(--foreground-dim)]">{message}</div>}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]"><h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{mode === 'create' ? 'CREATE SANDBOX WORKFLOW' : `${sandboxId} — OPENSHELL POLICY`}</h4><div className="flex gap-2"><Badge tone="static">Static / Recreate Required</Badge><Badge tone="dynamic">Dynamic / Apply Live</Badge></div></div>
|
||||
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8">
|
||||
{mode === 'create' && <section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a blueprint-backed workflow or create a custom sandbox, then provide a sandbox name.</p></div><div className="rounded-sm border border-[rgba(118,185,0,0.25)] bg-[rgba(118,185,0,0.08)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">Gateway reuse policy:
|
||||
- reuse the existing OpenShell gateway when `openshell status` reports `Connected`
|
||||
- only start a fresh gateway when no healthy gateway is already connected
|
||||
- force non-interactive PATH to include $HOME/.local/bin so openshell resolves during setup</div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{blueprints.map((bp) => <button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}><div className="flex items-center justify-between gap-3"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span><Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge></div><p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p><p className="text-[10px] font-mono text-[var(--foreground-dim)] mt-3">{bp.source}</p></button>)}</div><div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Operator-facing sandbox name used by OpenShell create/connect flows. Lowercase letters, numbers, and hyphens only." /></label><input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" /></div>{activeBlueprint?.supportsTailscale && <label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale <FieldHelp text="Optional. Only enable this when you want the Tailscale/NVIDIA-backed path. This is the only case where NVIDIA_API_KEY should be required." /></label>}{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}</section>}
|
||||
<section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(value) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section>
|
||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section>
|
||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section>
|
||||
<section className="space-y-3"><div className="flex items-center justify-between"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON Preview</h5><button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">{saving ? "Working…" : mode === 'create' ? 'Create Sandbox' : 'Save Policy'}</button></div><pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre>{message && <div className="text-sm text-[var(--foreground-dim)] whitespace-pre-wrap">{message}</div>}</section>
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import CompactGauge from './CompactGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -9,6 +9,7 @@ interface TelemetryData {
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
interface SandboxConfig {
|
||||
@@ -42,15 +43,7 @@ export default function SandboxDetails({
|
||||
{ name: 'debugMode', description: 'Enable debug logging', enabled: false }
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (sandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
const fetchTelemetry = useCallback(async () => {
|
||||
if (!sandboxId) return
|
||||
setLoading(true)
|
||||
try {
|
||||
@@ -62,7 +55,15 @@ export default function SandboxDetails({
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
useEffect(() => {
|
||||
if (sandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [sandboxId, fetchTelemetry])
|
||||
|
||||
const toggleConfig = (name: string) => {
|
||||
setConfig(config.map(item =>
|
||||
|
||||
+160
-106
@@ -1,16 +1,8 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import ConfigurationPanel from './ConfigurationPanel'
|
||||
|
||||
interface Sandbox {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
ip: string
|
||||
status: 'running' | 'pending' | 'stopped' | 'unknown'
|
||||
ready: boolean
|
||||
}
|
||||
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
||||
import { buildOperatorTerminalRoute } from '../lib/dashboardSession'
|
||||
|
||||
interface TelemetryData {
|
||||
cpu: number
|
||||
@@ -23,63 +15,68 @@ interface TelemetryData {
|
||||
}
|
||||
|
||||
interface SandboxListProps {
|
||||
selectedSandbox: string | null
|
||||
sandboxes: SandboxInventoryItem[]
|
||||
nemoclaw: NemoClawSummary | null
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
selectedSandbox: SandboxInventoryItem | null
|
||||
onSandboxSelect: (id: string | null) => void
|
||||
isDestroyMode: boolean
|
||||
onInventoryRefresh: () => Promise<SandboxInventoryItem[]>
|
||||
}
|
||||
|
||||
function renderDashboardTruthMessage(data: any) {
|
||||
const listenerSummary = data.listenerSummary ? `\nListener: ${data.listenerSummary}` : ''
|
||||
const showUpstreamSummary = !data.reachable || data.degraded || data.truthState !== 'verified'
|
||||
const upstreamSummary = showUpstreamSummary && (data.upstreamStatus || data.upstreamStatusText)
|
||||
? `\nUpstream probe: ${data.upstreamStatus ?? 'no-status'} ${data.upstreamStatusText ?? ''}`.trimEnd()
|
||||
: ''
|
||||
const inventorySummary = typeof data.inventoryCount === 'number'
|
||||
? `Inventory visibility: ${data.inventoryCount} live sandbox${data.inventoryCount === 1 ? '' : 'es'}.`
|
||||
: 'Inventory visibility: unknown.'
|
||||
const mappingSummary = data.sandboxId
|
||||
? (data.authority?.usedMappedSandboxInstance
|
||||
? `Sandbox ${data.sandboxId} resolved to OpenClaw instance ${data.instanceId} via bridge mapping (fallback-active).`
|
||||
: `Sandbox ${data.sandboxId} resolved to OpenClaw instance ${data.instanceId}.`)
|
||||
: `OpenClaw instance: ${data.instanceId}.`
|
||||
const reachabilitySummary = data.reachable
|
||||
? `Dashboard reachability: reachable at ${data.dashboardUrl}.`
|
||||
: `Dashboard reachability: unreachable at ${data.dashboardUrl}.`
|
||||
|
||||
if (data.degraded) {
|
||||
return `${inventorySummary} ${mappingSummary} ${reachabilitySummary} Degraded truth: the dashboard is reachable, but live OpenShell inventory is zero, so mapping alone does not prove the sandbox currently exists.${listenerSummary}${upstreamSummary}`
|
||||
}
|
||||
|
||||
if (data.reachable) {
|
||||
return `${inventorySummary} ${mappingSummary} ${data.note || reachabilitySummary}`.trim()
|
||||
}
|
||||
|
||||
return `${inventorySummary} ${mappingSummary} ${data.note || `OpenClaw Dashboard at ${data.dashboardUrl} is currently unreachable from this host.`}${listenerSummary}${upstreamSummary}`
|
||||
}
|
||||
|
||||
export default function SandboxList({
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
dashboardSessionId,
|
||||
selectedSandboxId,
|
||||
selectedSandbox,
|
||||
onSandboxSelect,
|
||||
isDestroyMode
|
||||
isDestroyMode,
|
||||
onInventoryRefresh,
|
||||
}: SandboxListProps) {
|
||||
const router = useRouter()
|
||||
const [terminalMessage, setTerminalMessage] = useState<string>('')
|
||||
const [dashboardMessage, setDashboardMessage] = useState<string>('')
|
||||
const [sandboxes, setSandboxes] = useState<Sandbox[]>([])
|
||||
const [telemetry, setTelemetry] = useState<TelemetryData>({
|
||||
cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString()
|
||||
})
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
fetchSandboxes()
|
||||
const interval = setInterval(fetchSandboxes, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
if (selectedSandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
const data = await response.json()
|
||||
|
||||
const sandboxList = (data.pods?.items || [])
|
||||
.filter((pod: any) => pod.metadata?.namespace === 'agent-sandbox-system')
|
||||
.map((pod: any) => ({
|
||||
id: pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.name || 'Unknown Sandbox',
|
||||
namespace: pod.metadata?.namespace || 'unknown',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status: pod.status?.phase === 'Running' ? 'running' :
|
||||
pod.status?.phase === 'Pending' ? 'pending' :
|
||||
pod.status?.phase === 'Stopped' ? 'stopped' : 'unknown' as const,
|
||||
ready: pod.status?.conditions?.find((c: any) => c.type === 'Ready')?.status === 'True'
|
||||
}))
|
||||
|
||||
setSandboxes(sandboxList)
|
||||
setLoading(false)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sandboxes:', error)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [selectedSandboxId])
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
try {
|
||||
@@ -91,16 +88,6 @@ export default function SandboxList({
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-xs text-[var(--foreground-dim)] font-mono uppercase tracking-wider">
|
||||
INITIALIZING...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{sandboxes.length === 0 ? (
|
||||
@@ -110,7 +97,7 @@ export default function SandboxList({
|
||||
</svg>
|
||||
<h3 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">No Sandboxes Detected</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
No sandboxes running in agent-sandbox-system namespace
|
||||
No live OpenShell sandboxes reported yet
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -123,7 +110,52 @@ export default function SandboxList({
|
||||
REFRESH: 10s
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
{!isDestroyMode && (
|
||||
<div className="panel p-4 space-y-2">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Inventory Source</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">Live OpenShell gateway inventory</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">NemoClaw Operator Surface</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">
|
||||
{nemoclaw?.available ? 'Local registry + services' : 'Unavailable'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-2 pt-1">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]">
|
||||
Inventory visibility: {sandboxes.length} live sandbox{sandboxes.length === 1 ? '' : 'es'}
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]">
|
||||
Mapping truth: intent only, not proof of sandbox existence
|
||||
</div>
|
||||
<div className={`rounded-sm border px-3 py-2 text-xs font-mono ${sandboxes.length === 0 ? 'border-[var(--status-pending)] bg-[var(--status-pending-bg)] text-[var(--status-pending)]' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'}`}>
|
||||
{sandboxes.length === 0 ? 'Truth state: degraded / unverified' : 'Truth state: verified from live inventory'}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)] font-mono">
|
||||
Dashboard session: {dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
{nemoclaw?.defaultSandboxNames?.length ? (
|
||||
<p className="text-xs text-[var(--foreground-dim)] font-mono">
|
||||
Default sandbox marker: {nemoclaw.defaultSandboxNames.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
{nemoclaw?.serviceLines?.length ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-2 pt-1">
|
||||
{nemoclaw.serviceLines.slice(0, 4).map((line) => (
|
||||
<div key={line} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]" title={line}>
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{sandboxes.map((sandbox) => (
|
||||
<button
|
||||
@@ -132,62 +164,81 @@ export default function SandboxList({
|
||||
className={`p-4 rounded-sm text-left transition-all border-2 ${
|
||||
isDestroyMode
|
||||
? 'border-[var(--status-stopped)] hover:bg-[var(--status-stopped-bg)]'
|
||||
: selectedSandbox === sandbox.id
|
||||
: selectedSandboxId === sandbox.id
|
||||
? 'bg-[var(--nvidia-green)] text-white border-[var(--nvidia-green)]'
|
||||
: 'panel hover:border-[var(--nvidia-green)]'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className={`text-sm font-mono font-semibold truncate ${
|
||||
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
||||
}`}>
|
||||
{sandbox.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className={`text-sm font-mono font-semibold truncate ${
|
||||
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
||||
}`}>
|
||||
{sandbox.name}
|
||||
</span>
|
||||
{sandbox.isDefault ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={`px-2 py-0.5 rounded-sm text-[10px] font-mono uppercase ${
|
||||
isDestroyMode
|
||||
? 'bg-[var(--status-stopped)] text-white animate-pulse'
|
||||
: sandbox.status === 'running' && sandbox.ready
|
||||
? 'bg-[var(--status-running)] text-white'
|
||||
: 'bg-[var(--status-pending)] text-white'
|
||||
: sandbox.status === 'stopped'
|
||||
? 'bg-[var(--status-stopped)] text-white'
|
||||
: sandbox.status === 'error'
|
||||
? 'bg-red-500 text-white'
|
||||
: 'bg-[var(--status-pending)] text-white'
|
||||
}`}>
|
||||
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : 'PENDING'}
|
||||
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : sandbox.status.toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">IP Address</span>
|
||||
<span className="text-xs font-mono">{sandbox.ip}</span>
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Attach Target</span>
|
||||
<span className="text-xs font-mono truncate max-w-[180px]" title={sandbox.ip}>{sandbox.ip}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Namespace</span>
|
||||
<span className="text-xs font-mono truncate max-w-[120px]">{sandbox.namespace}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Host Alias</span>
|
||||
<span className="text-xs font-mono truncate max-w-[140px]">{sandbox.sshHostAlias || 'N/A'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Sandbox ID</span>
|
||||
<span className="text-xs font-mono truncate max-w-[140px]" title={sandbox.id}>{sandbox.id}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Selected Sandbox Details - Technical Data Panel */}
|
||||
{!isDestroyMode && selectedSandbox && (
|
||||
<>
|
||||
<div className="panel p-6">
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)] gap-4 flex-wrap">
|
||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
||||
{sandboxes.find(s => s.id === selectedSandbox)?.name} — TELEMETRY
|
||||
{selectedSandbox.name} — TELEMETRY
|
||||
</h4>
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const res = await fetch('/api/openshell/dashboard/open')
|
||||
const searchParams = new URLSearchParams()
|
||||
searchParams.set('sandboxId', selectedSandbox.id)
|
||||
searchParams.set('inventoryCount', String(sandboxes.length))
|
||||
const res = await fetch(`/api/openshell/dashboard/open?${searchParams.toString()}`)
|
||||
const data = await res.json()
|
||||
setDashboardMessage(data.loopbackOnly
|
||||
? `OpenClaw Dashboard detected at ${data.dashboardUrl}. Opening proxied dashboard route.`
|
||||
: `OpenClaw Dashboard: ${data.dashboardUrl}`)
|
||||
if (data.proxiedUrl) {
|
||||
window.open(data.proxiedUrl, '_blank', 'noopener,noreferrer')
|
||||
} else if (data.dashboardUrl && !data.loopbackOnly) {
|
||||
window.open(data.dashboardUrl, '_blank', 'noopener,noreferrer')
|
||||
setDashboardMessage(renderDashboardTruthMessage(data))
|
||||
if (data.reachable && data.launchUrl) {
|
||||
window.location.href = data.launchUrl
|
||||
} else if (data.reachable && data.proxiedUrl) {
|
||||
window.location.href = data.proxiedUrl
|
||||
} else if (data.reachable && data.dashboardUrl && !data.loopbackOnly) {
|
||||
window.location.href = data.dashboardUrl
|
||||
}
|
||||
} catch (error) {
|
||||
setDashboardMessage('Failed to resolve OpenClaw Dashboard endpoint.')
|
||||
@@ -199,55 +250,58 @@ export default function SandboxList({
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
router.push(`/operator-terminal?sandboxId=${encodeURIComponent(selectedSandbox)}`)
|
||||
const nextUrl = buildOperatorTerminalRoute({
|
||||
sandboxId: selectedSandbox.id,
|
||||
dashboardSessionId,
|
||||
})
|
||||
window.open(nextUrl, '_blank', 'noopener,noreferrer')
|
||||
}}
|
||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
|
||||
>
|
||||
Open Operator Terminal
|
||||
Open Operator Terminal Path
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await onInventoryRefresh()
|
||||
}}
|
||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
|
||||
>
|
||||
Refresh Inventory
|
||||
</button>
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] font-mono">
|
||||
LIVE
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{dashboardMessage && (
|
||||
|
||||
{(dashboardMessage || terminalMessage) && (
|
||||
<div className="mb-4 space-y-2">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>
|
||||
{dashboardMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>}
|
||||
{terminalMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap font-mono">{terminalMessage}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.cpu.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEMORY</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.memory.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEM</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.memory.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">DISK</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.disk.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.disk.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">UPDATED</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">{new Date(telemetry.timestamp).toLocaleTimeString()}</p>
|
||||
</div>
|
||||
{telemetry.gpuTemperature && (
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">GPU TEMP</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.gpuTemperature.toFixed(1)}°C
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfigurationPanel sandboxId={selectedSandbox} mode="existing" />
|
||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" onInventoryRefresh={onInventoryRefresh} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
+55
-70
@@ -1,16 +1,13 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
interface Sandbox {
|
||||
id: string
|
||||
name: string
|
||||
ip: string
|
||||
status: 'running' | 'stopped' | 'unknown'
|
||||
}
|
||||
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
||||
|
||||
interface SidebarProps {
|
||||
hostIP: string
|
||||
selectedSandbox: string | null
|
||||
sandboxes: SandboxInventoryItem[]
|
||||
nemoclaw: NemoClawSummary | null
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
onSandboxSelect: (id: string | null) => void
|
||||
isSubmenuOpen: boolean
|
||||
onToggleSubmenu: () => void
|
||||
@@ -26,7 +23,10 @@ interface SidebarProps {
|
||||
|
||||
export default function Sidebar({
|
||||
hostIP,
|
||||
selectedSandbox,
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
dashboardSessionId,
|
||||
selectedSandboxId,
|
||||
onSandboxSelect,
|
||||
isSubmenuOpen,
|
||||
onToggleSubmenu,
|
||||
@@ -39,49 +39,9 @@ export default function Sidebar({
|
||||
onSettingsClick,
|
||||
onExitMode
|
||||
}: SidebarProps) {
|
||||
const [sandboxes, setSandboxes] = useState<Sandbox[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
const data = await response.json()
|
||||
|
||||
const items = data?.pods?.items || []
|
||||
if (!Array.isArray(items)) {
|
||||
setSandboxes([])
|
||||
return
|
||||
}
|
||||
|
||||
const sandboxList = items
|
||||
.filter((pod: any) => pod?.metadata?.namespace === 'agent-sandbox-system')
|
||||
.map((pod: any) => ({
|
||||
id: pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.name || 'Unknown Sandbox',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status: pod.status?.phase === 'Running' ? 'running' :
|
||||
pod.status?.phase === 'Pending' ? 'pending' :
|
||||
pod.status?.phase === 'Stopped' ? 'stopped' : 'unknown' as const
|
||||
}))
|
||||
|
||||
setSandboxes(sandboxList)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sandboxes in Sidebar:', error)
|
||||
setSandboxes([])
|
||||
}
|
||||
}
|
||||
|
||||
if (isSubmenuOpen || isDestroyMode || isCreateMode) {
|
||||
fetchSandboxes()
|
||||
const interval = setInterval(fetchSandboxes, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [isSubmenuOpen, isDestroyMode, isCreateMode])
|
||||
return (
|
||||
<>
|
||||
{/* Main Sidebar */}
|
||||
<aside className="fixed left-0 top-0 h-screen w-64 bg-[var(--background-secondary)] border-r border-[var(--border-subtle)] flex flex-col z-20">
|
||||
{/* Host IP Header - Industrial Style */}
|
||||
<div className="p-4 border-b border-[var(--border-subtle)]">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-[var(--nvidia-green)] rounded-sm flex items-center justify-center">
|
||||
@@ -92,11 +52,11 @@ export default function Sidebar({
|
||||
<div>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider font-semibold">Host</p>
|
||||
<p className="text-sm font-mono text-[var(--nvidia-green)] tracking-tight">{hostIP}</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono mt-1">session {dashboardSessionId.slice(0, 8)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation Menu - Technical */}
|
||||
<nav className="flex-1 p-2">
|
||||
<button
|
||||
onClick={onToggleSubmenu}
|
||||
@@ -112,19 +72,18 @@ export default function Sidebar({
|
||||
</svg>
|
||||
<span className="text-sm font-medium tracking-tight">Sandboxes</span>
|
||||
</span>
|
||||
<svg
|
||||
className={`w-4 h-4 transition-transform ${isSubmenuOpen ? 'rotate-90' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
<svg
|
||||
className={`w-4 h-4 transition-transform ${isSubmenuOpen ? 'rotate-90' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Quick Actions - Technical Icons */}
|
||||
<div className="mt-4 space-y-1">
|
||||
<button
|
||||
<button
|
||||
onClick={onCreateClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
isCreateMode
|
||||
@@ -137,8 +96,8 @@ export default function Sidebar({
|
||||
</svg>
|
||||
<span className="text-sm">Create Sandbox</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
<button
|
||||
onClick={onDestroyClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
isDestroyMode
|
||||
@@ -153,7 +112,7 @@ export default function Sidebar({
|
||||
</button>
|
||||
|
||||
{(isCreateMode || isDestroyMode) && (
|
||||
<button
|
||||
<button
|
||||
onClick={onExitMode}
|
||||
className="w-full flex items-center gap-3 px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:bg-[var(--background-panel)] transition-colors"
|
||||
>
|
||||
@@ -163,27 +122,29 @@ export default function Sidebar({
|
||||
<span className="text-sm">Cancel</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
|
||||
<button
|
||||
onClick={onSettingsClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
activeView === 'settings'
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'
|
||||
}`}>
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
<span className="text-sm">Settings</span>
|
||||
</button>
|
||||
<button
|
||||
<button
|
||||
onClick={onOverviewClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
activeView === 'overview'
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'
|
||||
}`}>
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
@@ -192,14 +153,12 @@ export default function Sidebar({
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Footer - Technical */}
|
||||
<div className="p-4 border-t border-[var(--border-subtle)]">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">OpenShell Control</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono">v1.0.0</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Slide-out Sandbox Submenu - Technical Data Panel */}
|
||||
<div
|
||||
className={`fixed left-64 top-0 h-screen w-72 bg-[var(--background)] border-r border-[var(--border-subtle)] transform transition-transform duration-200 ease-in-out z-10 ${
|
||||
isSubmenuOpen ? 'translate-x-0' : '-translate-x-full'
|
||||
@@ -213,6 +172,25 @@ export default function Sidebar({
|
||||
{isDestroyMode && 'SELECT A SANDBOX BELOW'}
|
||||
{!isCreateMode && !isDestroyMode && `${sandboxes.filter(s => s.status === 'running').length} RUNNING / ${sandboxes.length} TOTAL`}
|
||||
</p>
|
||||
{!isCreateMode && !isDestroyMode && (
|
||||
<div className="mt-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-2">
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Inventory Source</p>
|
||||
<p className="mt-1 text-[11px] text-[var(--foreground)] font-mono">Live OpenShell sandboxes</p>
|
||||
<p className="mt-2 text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">NemoClaw Operator</p>
|
||||
<p className="mt-1 text-[11px] text-[var(--foreground)] font-mono">
|
||||
{nemoclaw?.available ? 'Registry/service summary available' : 'No NemoClaw summary detected'}
|
||||
</p>
|
||||
<p className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono">Dashboard session: {dashboardSessionId.slice(0, 8)}</p>
|
||||
{nemoclaw?.defaultSandboxNames?.length ? (
|
||||
<p className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono">
|
||||
Default: {nemoclaw.defaultSandboxNames.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
{nemoclaw?.serviceLines?.slice(0, 2).map((line) => (
|
||||
<p key={line} className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono truncate" title={line}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-2 overflow-y-auto h-[calc(100vh-80px)]">
|
||||
@@ -257,7 +235,7 @@ export default function Sidebar({
|
||||
<button
|
||||
onClick={() => onSandboxSelect(null)}
|
||||
className={`w-full px-3 py-2 rounded-sm text-left transition-colors ${
|
||||
selectedSandbox === null
|
||||
selectedSandboxId === null
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground)]'
|
||||
}`}
|
||||
@@ -275,7 +253,7 @@ export default function Sidebar({
|
||||
key={sandbox.id}
|
||||
onClick={() => onSandboxSelect(sandbox.id)}
|
||||
className={`w-full px-3 py-2 rounded-sm text-left transition-colors ${
|
||||
selectedSandbox === sandbox.id
|
||||
selectedSandboxId === sandbox.id
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground)]'
|
||||
}`}
|
||||
@@ -286,17 +264,24 @@ export default function Sidebar({
|
||||
className={`w-2 h-2 rounded-sm ${
|
||||
sandbox.status === 'running'
|
||||
? 'bg-[var(--status-running)]'
|
||||
: 'bg-[var(--status-pending)]'
|
||||
: sandbox.status === 'stopped'
|
||||
? 'bg-[var(--status-stopped)]'
|
||||
: sandbox.status === 'error'
|
||||
? 'bg-red-500'
|
||||
: 'bg-[var(--status-pending)]'
|
||||
}`}
|
||||
/>
|
||||
<span className="text-sm font-mono truncate">{sandbox.name}</span>
|
||||
{sandbox.isDefault ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
|
||||
) : null}
|
||||
</div>
|
||||
<svg className="w-3 h-3 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono mt-1 ml-4">
|
||||
{sandbox.ip}
|
||||
{sandbox.namespace} · {sandbox.ip}
|
||||
</p>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import SpeedometerGauge from './SpeedometerGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -36,15 +36,6 @@ export default function TelemetryDisplay() {
|
||||
fetchSandboxes()
|
||||
}, [])
|
||||
|
||||
// Fetch telemetry when sandbox changes
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry(selectedSandbox)
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
@@ -64,7 +55,7 @@ export default function TelemetryDisplay() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchTelemetry = async (sandboxId: string) => {
|
||||
const fetchTelemetry = useCallback(async (sandboxId: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/telemetry/sandbox/${sandboxId}`)
|
||||
const data = await response.json()
|
||||
@@ -72,9 +63,9 @@ export default function TelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchCombinedTelemetry = async () => {
|
||||
const fetchCombinedTelemetry = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/combined')
|
||||
const data = await response.json()
|
||||
@@ -82,11 +73,20 @@ export default function TelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSandboxClick = (sandboxId: string | null) => {
|
||||
setSelectedSandbox(current => current === sandboxId ? null : sandboxId)
|
||||
}
|
||||
|
||||
const handleSandboxClick = (sandboxId: string) => {
|
||||
setSelectedSandbox(selectedSandbox === sandboxId ? null : sandboxId)
|
||||
}
|
||||
// Fetch telemetry when sandbox changes
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry(selectedSandbox)
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-center text-gray-600 dark:text-gray-400">Loading telemetry...</div>
|
||||
@@ -165,7 +165,7 @@ export default function TelemetryDisplay() {
|
||||
</div>
|
||||
|
||||
{/* Additional Metrics */}
|
||||
{telemetry.gpuTemperature && (
|
||||
{telemetry.gpuTemperature !== undefined && telemetry.gpuMemoryUsed !== undefined && telemetry.gpuMemoryTotal !== undefined && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h3 className="text-lg font-semibold mb-4 dark:text-white">GPU Metrics</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
+15
-15
@@ -3,6 +3,7 @@
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
/* NVIDIA Industrial Design System */
|
||||
--nvidia-green: #76B900;
|
||||
--nvidia-green-hover: #5d9600;
|
||||
@@ -33,23 +34,22 @@
|
||||
--metric-border: #2a2a2a;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
/* Light mode - still professional */
|
||||
--background: #f5f5f5;
|
||||
--background-secondary: #eeeeee;
|
||||
--background-tertiary: #e5e5e5;
|
||||
--background-panel: #ffffff;
|
||||
--foreground: #171717;
|
||||
--foreground-dim: #525252;
|
||||
--border-subtle: #d4d4d4;
|
||||
--border-medium: #a3a3a3;
|
||||
--metric-bg: #fafafa;
|
||||
--metric-border: #e5e5e5;
|
||||
}
|
||||
html[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
--background: #f5f5f5;
|
||||
--background-secondary: #eeeeee;
|
||||
--background-tertiary: #e5e5e5;
|
||||
--background-panel: #ffffff;
|
||||
--foreground: #171717;
|
||||
--foreground-dim: #525252;
|
||||
--border-subtle: #d4d4d4;
|
||||
--border-medium: #a3a3a3;
|
||||
--metric-bg: #fafafa;
|
||||
--metric-border: #e5e5e5;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
@@ -113,4 +113,4 @@ body {
|
||||
border: 1px solid var(--metric-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
export interface SandboxInventoryItem {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
ip: string
|
||||
status: 'running' | 'pending' | 'stopped' | 'unknown' | 'error'
|
||||
ready: boolean
|
||||
sshHostAlias?: string
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
export interface NemoClawSummary {
|
||||
available: boolean
|
||||
defaultSandboxNames: string[]
|
||||
serviceLines: string[]
|
||||
summaryLines: string[]
|
||||
source: 'nemoclaw-cli' | 'none'
|
||||
}
|
||||
|
||||
interface InventoryResponse {
|
||||
sandboxes?: any[]
|
||||
pods?: { items?: any[] }
|
||||
nemoclaw?: NemoClawSummary | null
|
||||
}
|
||||
|
||||
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
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function mapSandboxSummary(sandbox: any): SandboxInventoryItem {
|
||||
const status = normalizeStatus(sandbox.status)
|
||||
return {
|
||||
id: sandbox.id || sandbox.name || 'unknown',
|
||||
name: sandbox.name || 'Unknown Sandbox',
|
||||
namespace: sandbox.namespace || 'openshell',
|
||||
ip: sandbox.sshHostAlias || 'N/A',
|
||||
status,
|
||||
ready: status === 'running',
|
||||
sshHostAlias: sandbox.sshHostAlias || undefined,
|
||||
isDefault: Boolean(sandbox.isDefault),
|
||||
}
|
||||
}
|
||||
|
||||
function mapPodItem(pod: any): SandboxInventoryItem {
|
||||
const status = normalizeStatus(pod.status?.phase)
|
||||
return {
|
||||
id: pod.metadata?.labels?.['nemoclaw.ai/sandbox-id'] || pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.labels?.['nemoclaw.ai/sandbox-name'] || pod.metadata?.name || 'Unknown Sandbox',
|
||||
namespace: pod.metadata?.namespace || 'unknown',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status,
|
||||
ready: pod.status?.conditions?.find((c: any) => c.type === 'Ready')?.status === 'True',
|
||||
sshHostAlias: pod.status?.podIP || undefined,
|
||||
isDefault: pod.metadata?.labels?.['nemoclaw.ai/default'] === 'true',
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFromResponse(data: InventoryResponse): SandboxInventoryItem[] {
|
||||
if (Array.isArray(data?.sandboxes)) {
|
||||
return data.sandboxes.map(mapSandboxSummary)
|
||||
}
|
||||
|
||||
return (data?.pods?.items || [])
|
||||
.filter((pod: any) => Boolean(pod?.metadata?.name))
|
||||
.map(mapPodItem)
|
||||
}
|
||||
|
||||
export function useSandboxInventory(options?: { enabled?: boolean; refreshIntervalMs?: number }) {
|
||||
const enabled = options?.enabled ?? true
|
||||
const refreshIntervalMs = options?.refreshIntervalMs ?? 10000
|
||||
const [sandboxes, setSandboxes] = useState<SandboxInventoryItem[]>([])
|
||||
const [nemoclaw, setNemoclaw] = useState<NemoClawSummary | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const inFlightRef = useRef<Promise<SandboxInventoryItem[]> | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inFlightRef.current) {
|
||||
return inFlightRef.current
|
||||
}
|
||||
|
||||
const run = (async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real', { cache: 'no-store' })
|
||||
const data: InventoryResponse & { error?: string } = await response.json()
|
||||
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)
|
||||
return nextSandboxes
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to fetch sandbox inventory'
|
||||
setSandboxes([])
|
||||
setNemoclaw(null)
|
||||
setError(message)
|
||||
throw err
|
||||
} finally {
|
||||
setLoading(false)
|
||||
inFlightRef.current = null
|
||||
}
|
||||
})()
|
||||
|
||||
inFlightRef.current = run
|
||||
return run
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
let active = true
|
||||
setLoading(true)
|
||||
refresh().catch(() => {
|
||||
if (!active) return
|
||||
})
|
||||
|
||||
const interval = window.setInterval(() => {
|
||||
refresh().catch(() => {})
|
||||
}, refreshIntervalMs)
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [enabled, refresh, refreshIntervalMs])
|
||||
|
||||
const byId = useMemo(() => {
|
||||
const map = new Map<string, SandboxInventoryItem>()
|
||||
for (const sandbox of sandboxes) map.set(sandbox.id, sandbox)
|
||||
return map
|
||||
}, [sandboxes])
|
||||
|
||||
return {
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
byId,
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -4,6 +4,10 @@ import "./globals.css"
|
||||
export const metadata: Metadata = {
|
||||
title: "OpenShell/NemoClaw Dashboard",
|
||||
description: "Control plane dashboard for OpenShell and NemoClaw",
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
shortcut: "/favicon.ico",
|
||||
},
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -12,8 +16,8 @@ export default function RootLayout({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<html lang="en" data-theme="dark">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
const DASHBOARD_SESSION_STORAGE_KEY = 'nemoclaw-dashboard-session-id'
|
||||
export const HYDRATION_SAFE_DASHBOARD_SESSION_ID = 'dashboard-session'
|
||||
|
||||
export interface DashboardSessionState {
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function generateDashboardSessionId() {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
return `dashboard-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
export function createDashboardSessionState(selectedSandboxId: string | null = null): DashboardSessionState {
|
||||
return {
|
||||
dashboardSessionId: generateDashboardSessionId(),
|
||||
selectedSandboxId,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export function createHydrationSafeDashboardSessionState(
|
||||
selectedSandboxId: string | null = null
|
||||
): DashboardSessionState {
|
||||
return {
|
||||
dashboardSessionId: HYDRATION_SAFE_DASHBOARD_SESSION_ID,
|
||||
selectedSandboxId,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function updateDashboardSessionSelection(
|
||||
session: DashboardSessionState,
|
||||
selectedSandboxId: string | null
|
||||
): DashboardSessionState {
|
||||
return {
|
||||
...session,
|
||||
selectedSandboxId,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureDashboardSessionId(existingId: string | null | undefined) {
|
||||
return existingId && existingId.trim() ? existingId.trim() : generateDashboardSessionId()
|
||||
}
|
||||
|
||||
export function loadDashboardSessionState(): DashboardSessionState {
|
||||
if (typeof window === 'undefined') {
|
||||
return createHydrationSafeDashboardSessionState()
|
||||
}
|
||||
|
||||
const stored = window.sessionStorage.getItem(DASHBOARD_SESSION_STORAGE_KEY)
|
||||
if (!stored) {
|
||||
return createDashboardSessionState()
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(stored) as Partial<DashboardSessionState>
|
||||
return {
|
||||
dashboardSessionId: ensureDashboardSessionId(parsed.dashboardSessionId),
|
||||
selectedSandboxId: typeof parsed.selectedSandboxId === 'string' ? parsed.selectedSandboxId : null,
|
||||
updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : Date.now(),
|
||||
}
|
||||
} catch {
|
||||
return createDashboardSessionState()
|
||||
}
|
||||
}
|
||||
|
||||
export function persistDashboardSessionState(session: DashboardSessionState) {
|
||||
if (typeof window === 'undefined') return
|
||||
window.sessionStorage.setItem(DASHBOARD_SESSION_STORAGE_KEY, JSON.stringify(session))
|
||||
}
|
||||
|
||||
export function buildOperatorTerminalRoute(params: {
|
||||
sandboxId?: string | null
|
||||
dashboardSessionId: string
|
||||
}) {
|
||||
const searchParams = new URLSearchParams()
|
||||
if (params.sandboxId) {
|
||||
searchParams.set('sandboxId', params.sandboxId)
|
||||
}
|
||||
searchParams.set('dashboardSessionId', params.dashboardSessionId)
|
||||
const query = searchParams.toString()
|
||||
return query ? `/operator-terminal?${query}` : '/operator-terminal'
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
export type OpenClawInstanceRecord = {
|
||||
id: string
|
||||
label: string
|
||||
dashboardUrl: string
|
||||
terminalServerUrl?: string | null
|
||||
loopbackOnly: boolean
|
||||
default?: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_OPENCLAW_DASHBOARD_URL = 'http://127.0.0.1:18789/'
|
||||
const DEFAULT_TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011'
|
||||
const DEFAULT_INSTANCE_ID = 'default'
|
||||
|
||||
const DEFAULT_INSTANCE: OpenClawInstanceRecord = {
|
||||
id: DEFAULT_INSTANCE_ID,
|
||||
label: 'Default local OpenClaw',
|
||||
dashboardUrl: process.env.OPENCLAW_DASHBOARD_URL || DEFAULT_OPENCLAW_DASHBOARD_URL,
|
||||
terminalServerUrl: DEFAULT_TERMINAL_SERVER_URL,
|
||||
loopbackOnly: true,
|
||||
default: true,
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean) {
|
||||
if (typeof value !== 'string') return fallback
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (!normalized) return fallback
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) return false
|
||||
return fallback
|
||||
}
|
||||
|
||||
function parseRegistryFromEnv(): OpenClawInstanceRecord[] {
|
||||
const raw = process.env.OPENCLAW_INSTANCE_REGISTRY_JSON?.trim()
|
||||
if (!raw) return [DEFAULT_INSTANCE]
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return [DEFAULT_INSTANCE]
|
||||
|
||||
const normalized = parsed
|
||||
.map((entry): OpenClawInstanceRecord | null => {
|
||||
if (!entry || typeof entry !== 'object') return null
|
||||
|
||||
const id = typeof entry.id === 'string' && entry.id.trim() ? entry.id.trim() : null
|
||||
const dashboardUrl = typeof entry.dashboardUrl === 'string' && entry.dashboardUrl.trim() ? entry.dashboardUrl.trim() : null
|
||||
if (!id || !dashboardUrl) return null
|
||||
|
||||
return {
|
||||
id,
|
||||
label: typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim() : id,
|
||||
dashboardUrl,
|
||||
terminalServerUrl: typeof entry.terminalServerUrl === 'string' && entry.terminalServerUrl.trim() ? entry.terminalServerUrl.trim() : DEFAULT_TERMINAL_SERVER_URL,
|
||||
loopbackOnly: parseBoolean(typeof entry.loopbackOnly === 'string' ? entry.loopbackOnly : undefined, entry.loopbackOnly ?? true),
|
||||
default: Boolean(entry.default),
|
||||
}
|
||||
})
|
||||
.filter((entry): entry is OpenClawInstanceRecord => Boolean(entry))
|
||||
|
||||
if (normalized.length === 0) return [DEFAULT_INSTANCE]
|
||||
|
||||
const hasDefault = normalized.some((entry) => entry.default || entry.id === DEFAULT_INSTANCE_ID)
|
||||
if (!hasDefault) {
|
||||
normalized.unshift(DEFAULT_INSTANCE)
|
||||
} else if (!normalized.some((entry) => entry.id === DEFAULT_INSTANCE_ID)) {
|
||||
normalized.unshift({ ...DEFAULT_INSTANCE, default: false })
|
||||
}
|
||||
|
||||
return normalized
|
||||
} catch {
|
||||
return [DEFAULT_INSTANCE]
|
||||
}
|
||||
}
|
||||
|
||||
const OPENCLAW_INSTANCE_REGISTRY = parseRegistryFromEnv()
|
||||
const DEFAULT_SANDBOX_INSTANCE_MAP = process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID?.trim()
|
||||
? { 'my-assistant': process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID.trim() }
|
||||
: { 'my-assistant': DEFAULT_INSTANCE_ID }
|
||||
|
||||
function parseSandboxInstanceMapFromEnv(): Record<string, string> {
|
||||
const raw = process.env.OPENCLAW_SANDBOX_INSTANCE_MAP_JSON?.trim()
|
||||
if (!raw) return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
}
|
||||
|
||||
const normalized = Object.entries(parsed).reduce<Record<string, string>>((acc, [sandboxId, instanceId]) => {
|
||||
const normalizedSandboxId = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
const normalizedInstanceId = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (normalizedSandboxId && normalizedInstanceId) {
|
||||
acc[normalizedSandboxId] = normalizedInstanceId
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return Object.keys(normalized).length > 0
|
||||
? { ...DEFAULT_SANDBOX_INSTANCE_MAP, ...normalized }
|
||||
: DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
} catch {
|
||||
return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
}
|
||||
}
|
||||
|
||||
const OPENCLAW_SANDBOX_INSTANCE_MAP = parseSandboxInstanceMapFromEnv()
|
||||
|
||||
export function listOpenClawInstances() {
|
||||
return OPENCLAW_INSTANCE_REGISTRY.map((entry) => ({ ...entry }))
|
||||
}
|
||||
|
||||
export function getDefaultOpenClawInstance() {
|
||||
return OPENCLAW_INSTANCE_REGISTRY.find((entry) => entry.default) || OPENCLAW_INSTANCE_REGISTRY[0] || DEFAULT_INSTANCE
|
||||
}
|
||||
|
||||
export function resolveOpenClawInstance(instanceId?: string | null) {
|
||||
const requested = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (!requested) return getDefaultOpenClawInstance()
|
||||
return OPENCLAW_INSTANCE_REGISTRY.find((entry) => entry.id === requested) || getDefaultOpenClawInstance()
|
||||
}
|
||||
|
||||
export function getOpenClawInstanceIdForSandbox(sandboxId?: string | null) {
|
||||
const requestedSandboxId = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
if (!requestedSandboxId) return null
|
||||
return OPENCLAW_SANDBOX_INSTANCE_MAP[requestedSandboxId] || null
|
||||
}
|
||||
|
||||
export function resolveOpenClawInstanceForSandbox(sandboxId?: string | null) {
|
||||
const mappedInstanceId = getOpenClawInstanceIdForSandbox(sandboxId)
|
||||
return mappedInstanceId ? resolveOpenClawInstance(mappedInstanceId) : getDefaultOpenClawInstance()
|
||||
}
|
||||
+404
-121
@@ -1,160 +1,443 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import type { ExecFileException } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { existsSync } from "node:fs"
|
||||
import { promisify } from "node:util"
|
||||
import { getDefaultOpenClawInstance, resolveOpenClawInstance } from "./openclawInstances"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const DOCKER_BIN = '/Applications/Docker.app/Contents/Resources/bin/docker'
|
||||
const OPENSHELL_CONTAINER = 'openshell-cluster-openshell'
|
||||
const OPENSHELL_NAMESPACE = 'agent-sandbox-system'
|
||||
const OPENCLAW_DASHBOARD_URL = 'http://127.0.0.1:18789/'
|
||||
const DEFAULT_EXEC_TIMEOUT_MS = 10000
|
||||
const MAX_COMMAND_LENGTH = 400
|
||||
const SANDBOX_ID_PATTERN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/
|
||||
const OPENSHELL_BIN_CANDIDATES = [
|
||||
process.env.OPENSHELL_BIN,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin/openshell` : undefined,
|
||||
"/Users/markmckeen/.local/bin/openshell",
|
||||
"/Users/markmckeen/OpenShell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/scripts/bin/openshell",
|
||||
"/usr/local/bin/openshell",
|
||||
"/opt/homebrew/bin/openshell",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
|
||||
type ExecResult = {
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number
|
||||
const OPENCLAW_BIN_CANDIDATES = [
|
||||
process.env.OPENCLAW_BIN,
|
||||
process.env.HOME ? `${process.env.HOME}/NemoClaw/node_modules/.bin/openclaw` : undefined,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin/openclaw` : undefined,
|
||||
"/usr/local/bin/openclaw",
|
||||
"/opt/homebrew/bin/openclaw",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
|
||||
const OPENSHELL_BIN =
|
||||
OPENSHELL_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENSHELL_BIN_CANDIDATES[0]
|
||||
const OPENCLAW_BIN =
|
||||
OPENCLAW_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENCLAW_BIN_CANDIDATES[0] ?? "openclaw"
|
||||
const OPENSHELL_GATEWAY = process.env.OPENSHELL_GATEWAY || "openshell"
|
||||
const OPENSHELL_NAMESPACE = "agent-sandbox-system"
|
||||
|
||||
export type HostTelemetry = {
|
||||
cpu: number
|
||||
memory: number
|
||||
disk: number
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp: string
|
||||
source: "macos-host"
|
||||
}
|
||||
|
||||
function normalizeExecError(error: unknown): ExecResult {
|
||||
const execError = error as ExecFileException & { stdout?: string, stderr?: string, code?: number | string | null }
|
||||
type SandboxInspection = {
|
||||
name: string
|
||||
id: string | null
|
||||
namespace: string | null
|
||||
phase: string | null
|
||||
rawPhase: string | null
|
||||
sshHostAlias: string
|
||||
sshConfig: string
|
||||
rawDetails: string
|
||||
}
|
||||
|
||||
export type DashboardProbe = {
|
||||
reachable: boolean
|
||||
status: number | null
|
||||
statusText: string
|
||||
listenerPresent: boolean
|
||||
listenerSummary: string | null
|
||||
bootstrapUrl: string | null
|
||||
bootstrapTokenPresent: boolean
|
||||
bootstrapSource: 'openclaw-cli' | 'static-dashboard-url' | 'unavailable'
|
||||
bootstrapAuthority: 'tokenized-cli' | 'static-fallback' | 'none'
|
||||
}
|
||||
|
||||
export async function execOpenShell(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
})
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
function buildOpenClawEnv() {
|
||||
const pathEntries = [
|
||||
process.env.HOME ? `${process.env.HOME}/NemoClaw/node_modules/.bin` : null,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin` : null,
|
||||
process.env.PATH,
|
||||
].filter(Boolean)
|
||||
|
||||
return {
|
||||
stdout: typeof execError?.stdout === 'string' ? execError.stdout : '',
|
||||
stderr: typeof execError?.stderr === 'string' ? execError.stderr : '',
|
||||
exitCode: typeof execError?.code === 'number' ? execError.code : -1,
|
||||
...process.env,
|
||||
PATH: pathEntries.join(":"),
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
}
|
||||
|
||||
export async function dockerExecInOpenShell(command: string, timeoutMs = DEFAULT_EXEC_TIMEOUT_MS): Promise<ExecResult> {
|
||||
async function execOpenClaw(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENCLAW_BIN, args, {
|
||||
env: buildOpenClawEnv(),
|
||||
})
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
async function execBash(command: string) {
|
||||
const { stdout } = await execFileAsync("/bin/bash", ["-lc", command])
|
||||
return stdout.trim()
|
||||
}
|
||||
|
||||
function clampPercentage(value: number) {
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.max(0, Math.min(100, value))
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseField(output: string, label: string) {
|
||||
const normalizedLabel = label.toLowerCase()
|
||||
const line = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith(`${normalizedLabel}:`))
|
||||
|
||||
return line ? line.slice(label.length + 1).trim() : null
|
||||
}
|
||||
|
||||
function parseSshHostAlias(sshConfig: string, fallbackName: string) {
|
||||
const hostLine = sshConfig
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith("host "))
|
||||
|
||||
const alias = hostLine
|
||||
?.split(/\s+/)
|
||||
.slice(1)
|
||||
.find((entry) => entry !== "*")
|
||||
|
||||
return alias || `openshell-${fallbackName}`
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter((entry) => entry && !/^name\s+/i.test(entry) && !/^[-=]+$/.test(entry))
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
export async function resolveSandboxRef(ref: string) {
|
||||
const requested = ref.trim()
|
||||
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(
|
||||
DOCKER_BIN,
|
||||
[
|
||||
'exec',
|
||||
OPENSHELL_CONTAINER,
|
||||
'sh',
|
||||
'-lc',
|
||||
command,
|
||||
],
|
||||
{
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: 1024 * 1024,
|
||||
}
|
||||
)
|
||||
return { stdout, stderr, exitCode: 0 }
|
||||
} catch (error) {
|
||||
const normalized = normalizeExecError(error)
|
||||
if (normalized.exitCode !== -1 || normalized.stdout || normalized.stderr) {
|
||||
return normalized
|
||||
const { stdout } = await execOpenShell(["sandbox", "get", requested])
|
||||
return {
|
||||
requested,
|
||||
name: parseField(stdout, "Name") ?? requested,
|
||||
id: parseField(stdout, "Id") ?? requested,
|
||||
details: stdout.trim(),
|
||||
resolvedBy: "direct" as const,
|
||||
}
|
||||
throw error
|
||||
} catch (directError) {
|
||||
const { stdout: sandboxListStdout } = await execOpenShell(["sandbox", "list"])
|
||||
const names = parseOpenShellSandboxNames(sandboxListStdout)
|
||||
|
||||
for (const name of names) {
|
||||
try {
|
||||
const { stdout } = await execOpenShell(["sandbox", "get", name])
|
||||
const sandboxId = parseField(stdout, "Id")
|
||||
const sandboxName = parseField(stdout, "Name") ?? name
|
||||
|
||||
if (requested === sandboxId || requested === sandboxName) {
|
||||
return {
|
||||
requested,
|
||||
name: sandboxName,
|
||||
id: sandboxId ?? sandboxName,
|
||||
details: stdout.trim(),
|
||||
resolvedBy: requested === sandboxName ? ("list-name" as const) : ("list-id" as const),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore individual sandbox lookup failures while resolving a ref.
|
||||
}
|
||||
}
|
||||
|
||||
throw directError
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxExecPlan = {
|
||||
command: string
|
||||
mode: 'shell' | 'env'
|
||||
export function normalizeSandboxPhase(phase: string | null) {
|
||||
const value = (phase ?? "Unknown").toLowerCase()
|
||||
|
||||
switch (value) {
|
||||
case "ready":
|
||||
return "Running"
|
||||
case "provisioning":
|
||||
return "Pending"
|
||||
case "deleting":
|
||||
return "Stopping"
|
||||
case "error":
|
||||
return "Error"
|
||||
default:
|
||||
return phase ?? "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
function buildSandboxExecPlans(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }): SandboxExecPlan[] {
|
||||
const escaped = quoteForSingleQuotedShell(shellCommand)
|
||||
const attempts: SandboxExecPlan[] = [
|
||||
{
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /bin/sh -lc '${escaped}'`,
|
||||
mode: 'shell',
|
||||
},
|
||||
{
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /busybox/sh -lc '${escaped}'`,
|
||||
mode: 'shell',
|
||||
},
|
||||
]
|
||||
async function readCpuUsage() {
|
||||
const output = await execBash("top -l 1 -n 0 | grep CPU")
|
||||
const match = output.match(/([\d.]+)% idle/)
|
||||
const idle = match ? Number.parseFloat(match[1]) : 0
|
||||
return clampPercentage(100 - idle)
|
||||
}
|
||||
|
||||
if (options?.allowEnvFallback) {
|
||||
attempts.push({
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- env`,
|
||||
mode: 'env',
|
||||
async function readMemoryUsage() {
|
||||
const output = await execBash("vm_stat")
|
||||
const pageSize = Number.parseInt(output.match(/page size of (\d+) bytes/i)?.[1] ?? "4096", 10)
|
||||
const valueFor = (label: string) => {
|
||||
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
const match = output.match(new RegExp(`${escaped}:\\s+(\\d+)\\.?`, "i"))
|
||||
return Number.parseInt(match?.[1] ?? "0", 10)
|
||||
}
|
||||
|
||||
const active = valueFor("Pages active")
|
||||
const wired = valueFor("Pages wired down")
|
||||
const compressed = valueFor("Pages occupied by compressor")
|
||||
const speculative = valueFor("Pages speculative")
|
||||
const inactive = valueFor("Pages inactive")
|
||||
const free = valueFor("Pages free")
|
||||
const totalPages = active + wired + compressed + speculative + inactive + free
|
||||
const usedPages = active + wired + compressed + speculative
|
||||
|
||||
if (totalPages === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return clampPercentage((usedPages * pageSize * 100) / (totalPages * pageSize))
|
||||
}
|
||||
|
||||
async function readDiskUsage() {
|
||||
const output = await execBash("df -k / | tail -1")
|
||||
const columns = output.split(/\s+/)
|
||||
const usedPercent = columns[4]?.replace("%", "") ?? "0"
|
||||
return clampPercentage(Number.parseFloat(usedPercent))
|
||||
}
|
||||
|
||||
async function inspectListeningPort(port: number) {
|
||||
const summary = await execBash(`lsof -nP -iTCP:${port} -sTCP:LISTEN 2>/dev/null || true`)
|
||||
|
||||
return {
|
||||
listenerPresent: summary.length > 0,
|
||||
listenerSummary: summary || null,
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async function waitForListeningPort(port: number, timeoutMs = 5000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
let latest = await inspectListeningPort(port)
|
||||
|
||||
while (!latest.listenerPresent && Date.now() < deadline) {
|
||||
await sleep(250)
|
||||
latest = await inspectListeningPort(port)
|
||||
}
|
||||
|
||||
return latest
|
||||
}
|
||||
|
||||
function normalizeDashboardBootstrapUrl(value: string) {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return null
|
||||
const match = trimmed.match(/https?:\/\/\S+/)
|
||||
return match ? match[0] : null
|
||||
}
|
||||
|
||||
function hasDashboardToken(value: string | null) {
|
||||
if (!value) return false
|
||||
try {
|
||||
const parsed = new URL(value)
|
||||
return parsed.hash.includes('token=') || parsed.searchParams.has('token')
|
||||
} catch {
|
||||
return /[#?&]token=/.test(value)
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveOpenClawDashboardBootstrap(instanceId?: string | null) {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const defaultInstance = getDefaultOpenClawInstance()
|
||||
const canMintBootstrapFromCli = instance.id === defaultInstance.id
|
||||
|
||||
if (canMintBootstrapFromCli) {
|
||||
try {
|
||||
const { stdout, stderr } = await execOpenClaw(['dashboard', '--no-open'])
|
||||
const combined = `${stdout}\n${stderr}`
|
||||
const bootstrapUrl = normalizeDashboardBootstrapUrl(combined)
|
||||
const bootstrapTokenPresent = hasDashboardToken(bootstrapUrl)
|
||||
|
||||
if (bootstrapUrl) {
|
||||
return {
|
||||
bootstrapUrl,
|
||||
bootstrapTokenPresent,
|
||||
bootstrapSource: 'openclaw-cli' as const,
|
||||
bootstrapAuthority: bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fall through to configured instance URL when CLI minting is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
const bootstrapTokenPresent = hasDashboardToken(instance.dashboardUrl)
|
||||
return {
|
||||
bootstrapUrl: instance.dashboardUrl,
|
||||
bootstrapTokenPresent,
|
||||
bootstrapSource: instance.dashboardUrl ? ('static-dashboard-url' as const) : ('unavailable' as const),
|
||||
bootstrapAuthority: instance.dashboardUrl
|
||||
? (bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const))
|
||||
: ('none' as const),
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureOpenClawDashboardListener(instanceId: string, port: number) {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const defaultInstance = getDefaultOpenClawInstance()
|
||||
if (instance.id !== defaultInstance.id) return inspectListeningPort(port)
|
||||
|
||||
const initial = await inspectListeningPort(port)
|
||||
if (initial.listenerPresent) return initial
|
||||
|
||||
const child = spawn(OPENCLAW_BIN, ['gateway', 'run', '--allow-unconfigured', '--bind', 'loopback', '--port', String(port)], {
|
||||
detached: true,
|
||||
env: buildOpenClawEnv(),
|
||||
stdio: 'ignore',
|
||||
})
|
||||
child.unref()
|
||||
|
||||
return waitForListeningPort(port)
|
||||
}
|
||||
|
||||
export async function probeOpenClawDashboard(instanceId?: string | null): Promise<DashboardProbe> {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const target = new URL(instance.dashboardUrl)
|
||||
const port = Number.parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10)
|
||||
const listener = await ensureOpenClawDashboardListener(instance.id, port)
|
||||
const bootstrap = await resolveOpenClawDashboardBootstrap(instance.id)
|
||||
|
||||
try {
|
||||
const response = await fetch(instance.dashboardUrl, {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
accept: 'text/html,application/json;q=0.9,*/*;q=0.8',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return attempts
|
||||
}
|
||||
|
||||
async function execInSandboxWithFallback(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }) {
|
||||
const attempts = buildSandboxExecPlans(podName, shellCommand, options)
|
||||
|
||||
let lastFailure: ({ mode: SandboxExecPlan['mode'] } & ExecResult) | undefined
|
||||
for (const plan of attempts) {
|
||||
const result = await dockerExecInOpenShell(plan.command)
|
||||
if (result.exitCode === 0) {
|
||||
return {
|
||||
...result,
|
||||
mode: plan.mode,
|
||||
}
|
||||
return {
|
||||
reachable: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
listenerPresent: listener.listenerPresent,
|
||||
listenerSummary: listener.listenerSummary,
|
||||
bootstrapUrl: bootstrap.bootstrapUrl,
|
||||
bootstrapTokenPresent: bootstrap.bootstrapTokenPresent,
|
||||
bootstrapSource: bootstrap.bootstrapSource,
|
||||
bootstrapAuthority: bootstrap.bootstrapAuthority,
|
||||
}
|
||||
|
||||
lastFailure = {
|
||||
...result,
|
||||
mode: plan.mode,
|
||||
} catch (error) {
|
||||
return {
|
||||
reachable: false,
|
||||
status: null,
|
||||
statusText: error instanceof Error ? error.message : 'Dashboard probe failed',
|
||||
listenerPresent: listener.listenerPresent,
|
||||
listenerSummary: listener.listenerSummary,
|
||||
bootstrapUrl: bootstrap.bootstrapUrl,
|
||||
bootstrapTokenPresent: bootstrap.bootstrapTokenPresent,
|
||||
bootstrapSource: bootstrap.bootstrapSource,
|
||||
bootstrapAuthority: bootstrap.bootstrapAuthority,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lastFailure) {
|
||||
return lastFailure
|
||||
export async function readHostTelemetry(): Promise<HostTelemetry> {
|
||||
const [cpu, memory, disk] = await Promise.all([readCpuUsage(), readMemoryUsage(), readDiskUsage()])
|
||||
|
||||
return {
|
||||
cpu,
|
||||
memory,
|
||||
disk,
|
||||
timestamp: new Date().toISOString(),
|
||||
source: "macos-host",
|
||||
}
|
||||
|
||||
throw new Error('Failed to probe sandbox shell')
|
||||
}
|
||||
|
||||
export async function probeSandboxShell(podName: string) {
|
||||
const result = await execInSandboxWithFallback(podName, 'echo OPENSHELL_OK && pwd && whoami', { allowEnvFallback: true })
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(result.stderr.trim() || result.stdout.trim() || `Shell probe failed with exit code ${result.exitCode}`)
|
||||
export async function inspectSandbox(ref: string): Promise<SandboxInspection> {
|
||||
const resolved = await resolveSandboxRef(ref)
|
||||
const [{ stdout: detailsStdout }, { stdout: sshStdout }] = await Promise.all([
|
||||
Promise.resolve({ stdout: resolved.details }),
|
||||
execOpenShell(["sandbox", "ssh-config", resolved.name]),
|
||||
])
|
||||
|
||||
const sshConfig = sshStdout.trim()
|
||||
|
||||
const rawPhase = parseField(detailsStdout, "Phase")
|
||||
|
||||
return {
|
||||
name: parseField(detailsStdout, "Name") ?? resolved.name,
|
||||
id: parseField(detailsStdout, "Id") ?? resolved.id,
|
||||
namespace: parseField(detailsStdout, "Namespace"),
|
||||
phase: normalizeSandboxPhase(rawPhase),
|
||||
rawPhase,
|
||||
sshHostAlias: parseSshHostAlias(sshConfig, resolved.name),
|
||||
sshConfig,
|
||||
rawDetails: detailsStdout.trim(),
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function quoteForSingleQuotedShell(command: string) {
|
||||
return command.replace(/'/g, `'"'"'`)
|
||||
export async function probeSandboxShell(name: string) {
|
||||
return inspectSandbox(name)
|
||||
}
|
||||
|
||||
export function validateSandboxId(sandboxId: string) {
|
||||
const trimmed = sandboxId.trim()
|
||||
export function isOpenShellTransportError(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "")
|
||||
const normalized = message.toLowerCase()
|
||||
|
||||
if (!trimmed) {
|
||||
throw new Error('sandboxId is required')
|
||||
}
|
||||
|
||||
if (!SANDBOX_ID_PATTERN.test(trimmed)) {
|
||||
throw new Error('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
}
|
||||
|
||||
return trimmed
|
||||
return (
|
||||
normalized.includes("transport error") ||
|
||||
normalized.includes("connection refused") ||
|
||||
normalized.includes("tcp connect error")
|
||||
)
|
||||
}
|
||||
|
||||
export function validateTerminalCommand(command: string) {
|
||||
const trimmed = command.trim()
|
||||
|
||||
if (!trimmed) {
|
||||
throw new Error('command is required')
|
||||
}
|
||||
|
||||
if (trimmed.length > MAX_COMMAND_LENGTH) {
|
||||
throw new Error(`command exceeds ${MAX_COMMAND_LENGTH} characters`)
|
||||
}
|
||||
|
||||
return trimmed
|
||||
export function getOpenClawDashboardUrl(instanceId?: string | null) {
|
||||
return resolveOpenClawInstance(instanceId).dashboardUrl
|
||||
}
|
||||
|
||||
export async function runSandboxCommand(podName: string, command: string) {
|
||||
const trimmed = validateTerminalCommand(command)
|
||||
|
||||
return await execInSandboxWithFallback(podName, trimmed)
|
||||
export function getDefaultOpenClawDashboardInstanceId() {
|
||||
return getDefaultOpenClawInstance().id
|
||||
}
|
||||
|
||||
export function getOpenClawDashboardUrl() {
|
||||
return OPENCLAW_DASHBOARD_URL
|
||||
}
|
||||
|
||||
export { DEFAULT_EXEC_TIMEOUT_MS, DOCKER_BIN, MAX_COMMAND_LENGTH, OPENSHELL_CONTAINER, OPENSHELL_NAMESPACE }
|
||||
export { OPENSHELL_BIN, OPENSHELL_GATEWAY, OPENSHELL_NAMESPACE }
|
||||
export { OPENCLAW_BIN }
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { getDefaultOpenClawInstance, getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, type OpenClawInstanceRecord } from './openclawInstances'
|
||||
|
||||
export type RuntimeAuthorityResolution = {
|
||||
requestedSandboxId: string | null
|
||||
resolvedSandboxId: string | null
|
||||
sandboxAuthority: 'host' | 'sandbox'
|
||||
authorityMode: 'direct-host' | 'bridged-sandbox-map' | 'bridged-instance-override'
|
||||
provenance: 'default-instance' | 'sandbox-instance-map' | 'explicit-instance'
|
||||
bridgeActive: boolean
|
||||
bridgeReason: string | null
|
||||
openclaw: OpenClawInstanceRecord
|
||||
mappedSandboxInstanceId: string | null
|
||||
usedMappedSandboxInstance: boolean
|
||||
requestedInstanceId: string | null
|
||||
explicitInstanceOverride: boolean
|
||||
terminalServerUrl: string | null
|
||||
}
|
||||
|
||||
function normalizeId(value: string | null | undefined) {
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
return trimmed || null
|
||||
}
|
||||
|
||||
export function resolveRuntimeAuthority(params?: {
|
||||
sandboxId?: string | null
|
||||
resolvedSandboxId?: string | null
|
||||
instanceId?: string | null
|
||||
}): RuntimeAuthorityResolution {
|
||||
const requestedSandboxId = normalizeId(params?.sandboxId)
|
||||
const resolvedSandboxId = normalizeId(params?.resolvedSandboxId) ?? requestedSandboxId
|
||||
const requestedInstanceId = normalizeId(params?.instanceId)
|
||||
const sandboxAuthority: RuntimeAuthorityResolution['sandboxAuthority'] = resolvedSandboxId ? 'sandbox' : 'host'
|
||||
const mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox(resolvedSandboxId)
|
||||
const explicitInstanceOverride = Boolean(requestedInstanceId)
|
||||
const openclaw = requestedInstanceId
|
||||
? resolveOpenClawInstance(requestedInstanceId)
|
||||
: mappedSandboxInstanceId
|
||||
? resolveOpenClawInstance(mappedSandboxInstanceId)
|
||||
: getDefaultOpenClawInstance()
|
||||
const usedMappedSandboxInstance = Boolean(!requestedInstanceId && mappedSandboxInstanceId)
|
||||
const bridgeActive = Boolean(requestedInstanceId || usedMappedSandboxInstance)
|
||||
const authorityMode: RuntimeAuthorityResolution['authorityMode'] = requestedInstanceId
|
||||
? 'bridged-instance-override'
|
||||
: usedMappedSandboxInstance
|
||||
? 'bridged-sandbox-map'
|
||||
: 'direct-host'
|
||||
const provenance: RuntimeAuthorityResolution['provenance'] = requestedInstanceId
|
||||
? 'explicit-instance'
|
||||
: usedMappedSandboxInstance
|
||||
? 'sandbox-instance-map'
|
||||
: 'default-instance'
|
||||
const bridgeReason = requestedInstanceId
|
||||
? 'Explicit instance override selected a bridged OpenClaw upstream for this dashboard action.'
|
||||
: usedMappedSandboxInstance
|
||||
? 'Sandbox-to-instance mapping selected a bridged OpenClaw upstream for this sandbox context.'
|
||||
: null
|
||||
|
||||
return {
|
||||
requestedSandboxId,
|
||||
resolvedSandboxId,
|
||||
sandboxAuthority,
|
||||
authorityMode,
|
||||
provenance,
|
||||
bridgeActive,
|
||||
bridgeReason,
|
||||
openclaw,
|
||||
mappedSandboxInstanceId,
|
||||
usedMappedSandboxInstance,
|
||||
requestedInstanceId,
|
||||
explicitInstanceOverride,
|
||||
terminalServerUrl: openclaw.terminalServerUrl || null,
|
||||
}
|
||||
}
|
||||
+85
-277
@@ -1,9 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import Link from 'next/link'
|
||||
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import 'xterm/css/xterm.css'
|
||||
import { ensureDashboardSessionId, HYDRATION_SAFE_DASHBOARD_SESSION_ID } from '../lib/dashboardSession'
|
||||
|
||||
interface ReadinessPodSummary {
|
||||
containers?: string[]
|
||||
@@ -41,25 +42,30 @@ interface ReadinessResponse {
|
||||
interface LiveTerminalSession {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
dashboardSessionId: string
|
||||
replay?: string
|
||||
websocketUrl: string
|
||||
sshHostAlias?: string
|
||||
}
|
||||
|
||||
type XTermModule = typeof import('xterm')
|
||||
type FitAddonModule = typeof import('xterm-addon-fit')
|
||||
type XTermInstance = InstanceType<XTermModule['Terminal']>
|
||||
type FitAddonInstance = InstanceType<FitAddonModule['FitAddon']>
|
||||
|
||||
type LoadState = 'idle' | 'loading' | 'ready' | 'error'
|
||||
|
||||
const defaultAlias = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultFallback = (sandboxId: string | null) => `ssh -i ~/.ssh/id_ed25519_openclaw_labmac openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultLoginShell = (sandboxId: string | null) => `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'`
|
||||
const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.'
|
||||
const defaultFallback = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultLoginShell = (sandboxId: string | null) => `env PATH=$HOME/.local/bin:$PATH bash -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'`
|
||||
const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses local tooling, retry from a login shell or prepend PATH=$HOME/.local/bin:$PATH before ssh.'
|
||||
|
||||
export default function OperatorTerminalPage() {
|
||||
function OperatorTerminalInner() {
|
||||
const searchParams = useSearchParams()
|
||||
const sandboxId = searchParams.get('sandboxId')
|
||||
const requestedDashboardSessionId = searchParams.get('dashboardSessionId')
|
||||
const [dashboardSessionId, setDashboardSessionId] = useState(
|
||||
() => requestedDashboardSessionId?.trim() || HYDRATION_SAFE_DASHBOARD_SESSION_ID
|
||||
)
|
||||
const [state, setState] = useState<LoadState>(sandboxId ? 'loading' : 'idle')
|
||||
const [data, setData] = useState<ReadinessResponse | null>(null)
|
||||
const [lastCheckedAt, setLastCheckedAt] = useState<string | null>(null)
|
||||
@@ -73,6 +79,10 @@ export default function OperatorTerminalPage() {
|
||||
const fitAddonRef = useRef<FitAddonInstance | null>(null)
|
||||
const socketRef = useRef<WebSocket | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId))
|
||||
}, [requestedDashboardSessionId])
|
||||
|
||||
const refreshReadiness = useCallback(async () => {
|
||||
if (!sandboxId) {
|
||||
setState('idle')
|
||||
@@ -84,43 +94,29 @@ export default function OperatorTerminalPage() {
|
||||
setCopyMessage('')
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, { cache: 'no-store' })
|
||||
const result: ReadinessResponse = await response.json()
|
||||
setData(result)
|
||||
setState(response.ok && result.ok ? 'ready' : 'error')
|
||||
setLastCheckedAt(new Date().toLocaleTimeString())
|
||||
} catch (error) {
|
||||
setData({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to inspect sandbox readiness.',
|
||||
})
|
||||
setData({ ok: false, error: error instanceof Error ? error.message : 'Failed to inspect sandbox readiness.' })
|
||||
setState('error')
|
||||
setLastCheckedAt(new Date().toLocaleTimeString())
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
const ensureLiveSession = useCallback(async () => {
|
||||
if (!sandboxId) {
|
||||
setLiveSession(null)
|
||||
setTerminalState('idle')
|
||||
return
|
||||
}
|
||||
|
||||
setTerminalState('connecting')
|
||||
setTerminalStatus('Initializing live PTY session…')
|
||||
setTerminalStatus(sandboxId
|
||||
? `Initializing live terminal session for ${sandboxId}…`
|
||||
: 'Initializing host-mode live terminal session…')
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/openshell/terminal/live', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sandboxId,
|
||||
sessionId: liveSession?.sessionId,
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sandboxId, sessionId: liveSession?.sessionId, dashboardSessionId }),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok || !result.ok) {
|
||||
@@ -129,50 +125,34 @@ export default function OperatorTerminalPage() {
|
||||
setLiveSession({
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
replay: result.replay,
|
||||
websocketUrl: result.websocketUrl,
|
||||
sshHostAlias: result.sshHostAlias,
|
||||
})
|
||||
} catch (error) {
|
||||
setTerminalState('error')
|
||||
setTerminalStatus(error instanceof Error ? error.message : 'Failed to initialize live terminal session.')
|
||||
}
|
||||
}, [sandboxId, liveSession?.sessionId])
|
||||
}, [dashboardSessionId, sandboxId, liveSession?.sessionId])
|
||||
|
||||
useEffect(() => { refreshReadiness() }, [refreshReadiness])
|
||||
useEffect(() => { ensureLiveSession() }, [ensureLiveSession])
|
||||
|
||||
useEffect(() => {
|
||||
refreshReadiness()
|
||||
}, [refreshReadiness])
|
||||
|
||||
useEffect(() => {
|
||||
ensureLiveSession()
|
||||
}, [ensureLiveSession])
|
||||
|
||||
useEffect(() => {
|
||||
if (!terminalContainerRef.current || terminalRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!terminalContainerRef.current || terminalRef.current) return
|
||||
let disposed = false
|
||||
let cleanupResize: (() => void) | null = null
|
||||
|
||||
;(async () => {
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([
|
||||
import('xterm'),
|
||||
import('xterm-addon-fit'),
|
||||
])
|
||||
|
||||
if (disposed || !terminalContainerRef.current) {
|
||||
return
|
||||
}
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([import('xterm'), import('xterm-addon-fit')])
|
||||
if (disposed || !terminalContainerRef.current) return
|
||||
|
||||
const term = new Terminal({
|
||||
cursorBlink: true,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
|
||||
fontSize: 13,
|
||||
theme: {
|
||||
background: '#000000',
|
||||
foreground: '#f5f5f5',
|
||||
cursor: '#76b900',
|
||||
},
|
||||
theme: { background: '#000000', foreground: '#f5f5f5', cursor: '#76b900' },
|
||||
scrollback: 5000,
|
||||
allowTransparency: false,
|
||||
})
|
||||
@@ -180,23 +160,24 @@ export default function OperatorTerminalPage() {
|
||||
term.loadAddon(fitAddon)
|
||||
term.open(terminalContainerRef.current)
|
||||
fitAddon.fit()
|
||||
|
||||
term.focus()
|
||||
terminalRef.current = term
|
||||
fitAddonRef.current = fitAddon
|
||||
|
||||
const focusTerminal = () => term.focus()
|
||||
terminalContainerRef.current.addEventListener('click', focusTerminal)
|
||||
|
||||
const handleResize = () => {
|
||||
fitAddon.fit()
|
||||
if (socketRef.current?.readyState === WebSocket.OPEN) {
|
||||
socketRef.current.send(JSON.stringify({
|
||||
type: 'resize',
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
}))
|
||||
socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('resize', handleResize)
|
||||
cleanupResize = () => window.removeEventListener('resize', handleResize)
|
||||
cleanupResize = () => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
terminalContainerRef.current?.removeEventListener('click', focusTerminal)
|
||||
}
|
||||
})().catch((error) => {
|
||||
setTerminalState('error')
|
||||
setTerminalStatus(error instanceof Error ? error.message : 'Failed to load terminal renderer.')
|
||||
@@ -213,46 +194,31 @@ export default function OperatorTerminalPage() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!liveSession?.websocketUrl || !terminalRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!liveSession?.websocketUrl || !terminalRef.current) return
|
||||
const term = terminalRef.current
|
||||
term.reset()
|
||||
if (liveSession.replay) {
|
||||
term.write(liveSession.replay)
|
||||
}
|
||||
if (liveSession.replay) term.write(liveSession.replay)
|
||||
|
||||
const socket = new WebSocket(liveSession.websocketUrl)
|
||||
socketRef.current = socket
|
||||
|
||||
const inputDisposable = term.onData((data) => {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'input', data }))
|
||||
}
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'input', data }))
|
||||
})
|
||||
|
||||
socket.addEventListener('open', () => {
|
||||
setTerminalState('connected')
|
||||
setTerminalStatus(`Live PTY connected for ${liveSession.sandboxId}.`)
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit()
|
||||
}
|
||||
socket.send(JSON.stringify({
|
||||
type: 'resize',
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
}))
|
||||
setTerminalStatus(`Live terminal connected for ${liveSession.sandboxId} in dashboard session ${liveSession.dashboardSessionId.slice(0, 8)}.`)
|
||||
fitAddonRef.current?.fit()
|
||||
term.focus()
|
||||
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
})
|
||||
|
||||
socket.addEventListener('message', (event) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data)
|
||||
if (message.type === 'ready') {
|
||||
if (message.replay) {
|
||||
term.reset()
|
||||
term.write(message.replay)
|
||||
}
|
||||
if (message.type === 'ready' && message.replay) {
|
||||
term.reset()
|
||||
term.write(message.replay)
|
||||
} else if (message.type === 'data' && typeof message.data === 'string') {
|
||||
term.write(message.data)
|
||||
} else if (message.type === 'exit') {
|
||||
@@ -277,67 +243,22 @@ export default function OperatorTerminalPage() {
|
||||
return () => {
|
||||
inputDisposable.dispose()
|
||||
socket.close()
|
||||
if (socketRef.current === socket) {
|
||||
socketRef.current = null
|
||||
}
|
||||
if (socketRef.current === socket) socketRef.current = null
|
||||
}
|
||||
}, [liveSession])
|
||||
|
||||
const readiness = useMemo(() => {
|
||||
if (!sandboxId) {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'NO SANDBOX SELECTED',
|
||||
detail: 'Return to the dashboard and choose a sandbox before opening Operator Terminal.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'loading') {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'CHECKING READINESS',
|
||||
detail: 'Verifying pod metadata and bounded shell reachability so the page can report terminal truth in one pass.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) {
|
||||
return {
|
||||
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
|
||||
label: 'LIVE TERMINAL PATH VERIFIED',
|
||||
detail: 'The backend confirmed pod readiness and shell reachability, and the dashboard is now wired for a live PTY transport.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'DEGRADED: POD UP, SHELL UNCONFIRMED',
|
||||
detail: 'The pod exists, but the readiness probe did not fully succeed. The live terminal may still connect, but direct SSH remains the stronger fallback.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podExists) {
|
||||
return {
|
||||
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
|
||||
label: 'READY FOR LIVE TERMINAL',
|
||||
detail: 'Pod metadata is present and the dashboard live terminal can attempt a real PTY session.',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]',
|
||||
label: 'READINESS CHECK FAILED',
|
||||
detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.',
|
||||
}
|
||||
if (!sandboxId) return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'HOST MODE', detail: 'No sandbox query was provided. The dashboard terminal stays in host mode and keeps dashboard-session diagnostics for reconnect behavior.' }
|
||||
if (state === 'loading') return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'CHECKING READINESS', detail: 'Verifying pod metadata and shell reachability.' }
|
||||
if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'LIVE TERMINAL PATH VERIFIED', detail: 'The backend confirmed pod readiness and shell reachability, and the dashboard is wired for a live terminal transport.' }
|
||||
if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'DEGRADED: POD UP, SHELL UNCONFIRMED', detail: 'The pod exists, but the readiness probe did not fully succeed. The live terminal may still connect, but direct SSH remains the stronger fallback.' }
|
||||
if (state === 'ready' && data?.ok && data?.podExists) return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'READY FOR LIVE TERMINAL', detail: 'Pod metadata is present and the dashboard live terminal can attempt a real shell session.' }
|
||||
return { tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]', label: 'READINESS CHECK FAILED', detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.' }
|
||||
}, [sandboxId, state, data])
|
||||
|
||||
const copyCommand = useCallback(async (command: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopyMessage(`Copied: ${command}`)
|
||||
} catch {
|
||||
setCopyMessage(`Copy failed. Use: ${command}`)
|
||||
}
|
||||
try { await navigator.clipboard.writeText(command); setCopyMessage(`Copied: ${command}`) }
|
||||
catch { setCopyMessage(`Copy failed. Use: ${command}`) }
|
||||
}, [])
|
||||
|
||||
const aliasCommand = data?.attach?.aliasCommand || defaultAlias(sandboxId)
|
||||
@@ -352,169 +273,56 @@ export default function OperatorTerminalPage() {
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">Operator path</p>
|
||||
<h1 className="text-2xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
||||
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-3xl">
|
||||
Real live terminal surface for the selected sandbox. Browser keys flow into a PTY-backed shell process and output streams back live into the dashboard.
|
||||
</p>
|
||||
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-3xl">{sandboxId ? 'Live operator terminal for the selected sandbox, brokered through the dashboard-owned terminal bridge.' : 'Live operator terminal for host mode, brokered through the dashboard-owned terminal bridge.'}</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono mt-2">Dashboard session {dashboardSessionId.slice(0, 8)}</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/"
|
||||
className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]"
|
||||
>
|
||||
Back to Dashboard
|
||||
</Link>
|
||||
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
||||
</div>
|
||||
|
||||
<section className={`panel p-6 border-2 ${readiness.tone}`}>
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Sandbox</p>
|
||||
<h2 className="text-lg font-semibold mt-1">{sandboxId || 'UNSELECTED'}</h2>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Status</p>
|
||||
<p className="text-sm font-mono mt-1">{readiness.label}</p>
|
||||
{lastCheckedAt && <p className="text-[10px] mt-1 opacity-80">Last checked {lastCheckedAt}</p>}
|
||||
</div>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Sandbox</p><h2 className="text-lg font-semibold mt-1">{sandboxId || 'HOST'}</h2></div>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Dashboard Session</p><h2 className="text-lg font-semibold mt-1">{dashboardSessionId.slice(0, 8)}</h2></div>
|
||||
<div className="text-right"><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Status</p><p className="text-sm font-mono mt-1">{readiness.label}</p>{lastCheckedAt && <p className="text-[10px] mt-1 opacity-80">Last checked {lastCheckedAt}</p>}</div>
|
||||
</div>
|
||||
<p className="text-sm mt-4 text-[var(--foreground)]">{readiness.detail}</p>
|
||||
</section>
|
||||
|
||||
<section className="panel p-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Live Dashboard Terminal</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
xterm-backed live terminal. Supports typed input, streamed output, resize, and session reconnect.
|
||||
</p>
|
||||
</div>
|
||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Live Dashboard Terminal</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">Browser terminal backed by the dashboard terminal server.</p></div>
|
||||
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">{terminalStatus}</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3">
|
||||
<div ref={terminalContainerRef} className="h-[520px] w-full" />
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[520px] w-full" /></div>
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<button
|
||||
onClick={ensureLiveSession}
|
||||
disabled={!sandboxId || terminalState === 'connecting'}
|
||||
className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}
|
||||
</button>
|
||||
<button
|
||||
onClick={refreshReadiness}
|
||||
className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Refresh Readiness
|
||||
</button>
|
||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}
|
||||
</span>
|
||||
<button onClick={ensureLiveSession} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
||||
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 xl:grid-cols-[1.1fr_0.9fr] gap-6">
|
||||
<div className="panel p-6 space-y-5">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Direct Attach Fallbacks</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
If the live dashboard terminal is degraded, these remain the authoritative escape hatches.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Direct Attach Fallbacks</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">If the live dashboard terminal is degraded, these remain the authoritative escape hatches.</p></div>
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code>
|
||||
<button
|
||||
onClick={() => copyCommand(aliasCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Alias Command
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p><code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code><button onClick={() => copyCommand(aliasCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Alias Command</button></div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Fallback if alias or agent config is missing</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{fallbackCommand}</code>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">{shellHint}</p>
|
||||
<button
|
||||
onClick={() => copyCommand(fallbackCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Fallback Command
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Login-shell retry for Homebrew/path issues</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{loginShellCommand}</code>
|
||||
<button
|
||||
onClick={() => copyCommand(loginShellCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Login-Shell Retry
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{copyMessage && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||
{copyMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="panel p-6 space-y-5">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Readiness Evidence</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
Live pod introspection and bounded shell evidence from the backend.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Pod phase / ready</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.phase || 'Unknown'} / {data?.pod?.readyCondition || 'Unknown'}</p>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Containers</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.containers?.length ? data.pod.containers.join(', ') : 'Unavailable'}</p>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Images</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.images?.length ? data.pod.images.join(', ') : 'Unavailable'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Shell probe</p>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">Readiness-side shell evidence.</p>
|
||||
</div>
|
||||
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
{data?.shellProbe?.ok ? 'Probe passed' : 'Probe not confirmed'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stdout</p>
|
||||
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.output || 'No backend shell output captured yet.'}</pre>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stderr / status</p>
|
||||
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.error || data?.shellProbe?.stderr || data?.note || 'No stderr.'}</pre>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Fallback if alias or agent config is missing</p><code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{fallbackCommand}</code><p className="text-xs text-[var(--foreground-dim)] mt-2">{shellHint}</p><button onClick={() => copyCommand(fallbackCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Fallback Command</button></div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Login-shell retry for Homebrew/path issues</p><code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{loginShellCommand}</code><button onClick={() => copyCommand(loginShellCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Login-Shell Retry</button></div>
|
||||
</div>
|
||||
</div>
|
||||
{copyMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{copyMessage}</div>}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OperatorTerminalPage() {
|
||||
return (
|
||||
<Suspense fallback={<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-8"><div className="mx-auto max-w-6xl"><div className="panel p-6">Loading operator terminal…</div></div></main>}>
|
||||
<OperatorTerminalInner />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
+96
-21
@@ -1,19 +1,47 @@
|
||||
"use client"
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import Sidebar from './components/Sidebar'
|
||||
import SandboxList from './components/SandboxList'
|
||||
import ConfigurationPanel from './components/ConfigurationPanel'
|
||||
import { useSandboxInventory } from './hooks/useSandboxInventory'
|
||||
import {
|
||||
createHydrationSafeDashboardSessionState,
|
||||
loadDashboardSessionState,
|
||||
persistDashboardSessionState,
|
||||
updateDashboardSessionSelection,
|
||||
} from './lib/dashboardSession'
|
||||
|
||||
export default function Dashboard() {
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>('dark')
|
||||
const [isSubmenuOpen, setIsSubmenuOpen] = useState(false)
|
||||
const [hostIP] = useState('192.168.50.173')
|
||||
const [selectedSandbox, setSelectedSandbox] = useState<string | null>(null)
|
||||
const [dashboardSession, setDashboardSession] = useState(() => createHydrationSafeDashboardSessionState())
|
||||
const [isCreateMode, setIsCreateMode] = useState(false)
|
||||
const [isDestroyMode, setIsDestroyMode] = useState(false)
|
||||
const [activeView, setActiveView] = useState<'overview' | 'settings' | 'sandboxes'>('sandboxes')
|
||||
const [deletingSandboxId, setDeletingSandboxId] = useState<string | null>(null)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const inventoryEnabled = isSubmenuOpen || activeView === 'sandboxes' || isCreateMode || isDestroyMode
|
||||
const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({
|
||||
enabled: inventoryEnabled,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setDashboardSession(loadDashboardSessionState())
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
persistDashboardSessionState(dashboardSession)
|
||||
}, [dashboardSession])
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
}, [theme])
|
||||
|
||||
const selectedSandbox = useMemo(
|
||||
() => sandboxes.find((sandbox) => sandbox.id === dashboardSession.selectedSandboxId) ?? null,
|
||||
[sandboxes, dashboardSession.selectedSandboxId]
|
||||
)
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(theme === 'light' ? 'dark' : 'light')
|
||||
@@ -24,12 +52,25 @@ export default function Dashboard() {
|
||||
setDeletingSandboxId(id)
|
||||
setShowDeleteConfirm(true)
|
||||
} else {
|
||||
setSelectedSandbox(id)
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, id))
|
||||
}
|
||||
}
|
||||
|
||||
const clearSelection = () => {
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, null))
|
||||
}
|
||||
|
||||
const handleCreateSuccess = async (createdSandboxId: string) => {
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setActiveView('sandboxes')
|
||||
setIsSubmenuOpen(true)
|
||||
const latest = await refresh()
|
||||
const created = latest.find((sandbox) => sandbox.id === createdSandboxId || sandbox.name === createdSandboxId)
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, created?.id ?? createdSandboxId))
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
// TODO: Call destroy sandbox API
|
||||
console.log('Destroying sandbox:', deletingSandboxId)
|
||||
setShowDeleteConfirm(false)
|
||||
setDeletingSandboxId(null)
|
||||
@@ -49,10 +90,12 @@ export default function Dashboard() {
|
||||
: 'bg-[var(--background)] text-[var(--foreground)]'
|
||||
}`}
|
||||
>
|
||||
{/* Sidebar */}
|
||||
<Sidebar
|
||||
hostIP={hostIP}
|
||||
selectedSandbox={selectedSandbox}
|
||||
sandboxes={sandboxes}
|
||||
nemoclaw={nemoclaw}
|
||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isSubmenuOpen={isSubmenuOpen}
|
||||
onToggleSubmenu={() => {
|
||||
@@ -67,7 +110,7 @@ export default function Dashboard() {
|
||||
setActiveView('sandboxes')
|
||||
setIsCreateMode(true)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(true)
|
||||
}}
|
||||
onDestroyClick={() => {
|
||||
@@ -80,24 +123,23 @@ export default function Dashboard() {
|
||||
setActiveView('overview')
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(false)
|
||||
}}
|
||||
onSettingsClick={() => {
|
||||
setActiveView('settings')
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(false)
|
||||
}}
|
||||
onExitMode={() => {
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="ml-64 transition-all duration-300">
|
||||
<div className={isSubmenuOpen ? 'ml-72' : ''}>
|
||||
<div className="p-8">
|
||||
@@ -145,8 +187,11 @@ export default function Dashboard() {
|
||||
<p className="text-sm text-[var(--foreground-dim)] mb-6">
|
||||
Global defaults and preset-driven policy controls for this dashboard instance.
|
||||
</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
Dashboard session {dashboardSession.dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
</div>
|
||||
<ConfigurationPanel sandboxId="global-settings" mode="create" />
|
||||
<ConfigurationPanel sandboxId="global-settings" mode="create" onCreateSuccess={handleCreateSuccess} onInventoryRefresh={refresh} />
|
||||
</div>
|
||||
) : isCreateMode ? (
|
||||
<div className="space-y-6">
|
||||
@@ -158,7 +203,7 @@ export default function Dashboard() {
|
||||
Start from a named security preset, then refine the OpenShell policy before creating the sandbox.
|
||||
</p>
|
||||
</div>
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" />
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" onCreateSuccess={handleCreateSuccess} onInventoryRefresh={refresh} />
|
||||
</div>
|
||||
) : isDestroyMode ? (
|
||||
<div className="panel p-8 border-2 border-[var(--status-stopped)]">
|
||||
@@ -172,7 +217,7 @@ export default function Dashboard() {
|
||||
<button
|
||||
onClick={() => {
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
}}
|
||||
className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]"
|
||||
>
|
||||
@@ -190,6 +235,9 @@ export default function Dashboard() {
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-1">
|
||||
Real-time OpenShell sandbox monitoring
|
||||
</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono mt-2">
|
||||
Dashboard session {dashboardSession.dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
@@ -199,18 +247,45 @@ export default function Dashboard() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<SandboxList
|
||||
selectedSandbox={selectedSandbox}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isDestroyMode={isDestroyMode}
|
||||
/>
|
||||
{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">
|
||||
INITIALIZING...
|
||||
</div>
|
||||
</div>
|
||||
) : inventoryEnabled && error ? (
|
||||
<div className="panel p-8 text-center" data-testid="inventory-error-state">
|
||||
<h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p>
|
||||
</div>
|
||||
) : sandboxes.length === 0 ? (
|
||||
<div className="panel p-8 text-center" data-testid="inventory-empty-state">
|
||||
<svg className="w-12 h-12 mx-auto mb-4 text-[var(--foreground-dim)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={1.5} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
|
||||
</svg>
|
||||
<h3 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">No Sandboxes Detected</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
No live OpenShell sandboxes reported yet
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<SandboxList
|
||||
sandboxes={sandboxes}
|
||||
nemoclaw={nemoclaw}
|
||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||
selectedSandbox={selectedSandbox}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isDestroyMode={isDestroyMode}
|
||||
onInventoryRefresh={refresh}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{/* Delete Confirmation Overlay */}
|
||||
{showDeleteConfirm && (
|
||||
<div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">
|
||||
<div className="panel p-8 max-w-md border-2 border-[var(--status-stopped)]">
|
||||
@@ -244,4 +319,4 @@ export default function Dashboard() {
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user