From 94bd7737d385111bd059dd13a37b4c6077c6418a Mon Sep 17 00:00:00 2001 From: mmckeen-nv Date: Fri, 8 May 2026 09:32:56 -0700 Subject: [PATCH] Integrate NemoClaw recovery and dashboard routing --- .env.example | 8 +- README.md | 24 +- app/api/auth/login/route.ts | 4 +- app/api/auth/logout/route.ts | 11 +- app/api/auth/recover/route.ts | 4 +- app/api/auth/setup/route.ts | 4 +- app/api/inference/route.ts | 8 +- app/api/openshell/dashboard/open/route.ts | 32 +- app/api/openshell/dashboard/proxy/shared.ts | 63 ++- app/api/sandbox/[sandboxId]/health/route.ts | 33 ++ app/api/sandbox/[sandboxId]/restart/route.ts | 21 +- app/components/InferenceEndpointPanel.tsx | 74 ++-- app/lib/controlAuth.ts | 47 ++- app/lib/controllerNodePlan.ts | 3 +- app/lib/nemoclawCli.ts | 217 ++++++++++ app/lib/openclawDashboardToken.ts | 34 ++ install.sh | 9 +- package.json | 7 +- server.mjs | 373 ++++++++++++++---- tests/control-auth-cookie-check.mjs | 78 ++++ tests/nemoclaw-compat-check.mjs | 40 ++ ...-dashboard-bootstrap-token-scope-check.mjs | 27 +- ...penclaw-dashboard-origin-rewrite-check.mjs | 13 + tests/runtime-authority-resolution-check.mjs | 10 +- tests/sandbox-lifecycle-check.mjs | 9 +- 25 files changed, 1001 insertions(+), 152 deletions(-) create mode 100644 app/lib/nemoclawCli.ts create mode 100644 app/lib/openclawDashboardToken.ts create mode 100644 tests/control-auth-cookie-check.mjs create mode 100644 tests/nemoclaw-compat-check.mjs diff --git a/.env.example b/.env.example index a4ded91..0c88e98 100644 --- a/.env.example +++ b/.env.example @@ -15,8 +15,14 @@ OPENSHELL_GATEWAY=nemoclaw # OPENSHELL_GATEWAY_PORT=8080 # OPENSHELL_GATEWAY_URL=http://host.docker.internal:8080 -# Dashboard port +# Dashboard port. PORT controls the server listener; NEXT_PUBLIC_DASHBOARD_PORT is exposed to the UI. +PORT=3000 NEXT_PUBLIC_DASHBOARD_PORT=3000 +# Browser-visible OpenClaw dashboard websocket base. +# Leave unset for same-origin reverse-proxy deployments. +# OPENCLAW_DASHBOARD_BASE_WS_URL=wss://control.example.com +# BASE_WS_URL=wss://control.example.com +# OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001 # Simple operator login for the dashboard # Generate both values before exposing the UI beyond localhost. diff --git a/README.md b/README.md index 46324ec..af2c562 100644 --- a/README.md +++ b/README.md @@ -130,10 +130,19 @@ grep OPENSHELL_CONTROL_PASSWORD .env.local ## Run +For local development with hot reload: + ```bash npm run dev ``` +For a long-running dashboard or controller node, build once and run the custom server in production mode: + +```bash +npm run build +npm run start +``` + Open: ```text @@ -143,9 +152,10 @@ http://localhost:3000 Default ports: - `3000`: dashboard HTTP server -- `3001`: OpenClaw dashboard websocket sidecar - `3011`: operator terminal upstream +The dashboard WebSocket proxy is served on the same listener by default, using `/api/openshell/dashboard/proxy` or `/api/openshell/instances/[instanceId]/dashboard/proxy`. Set `OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001` only if you intentionally want the legacy dedicated sidecar listener. + ## Authentication This project currently uses a simple local password and signed HTTP-only cookie. @@ -169,8 +179,8 @@ There is no email sender. Forgot-password uses `OPENSHELL_CONTROL_RECOVERY_TOKEN After changing `.env.local`, restart the server: ```bash -pkill -f 'node server.mjs|npm run dev' || true -npm run dev +pkill -f 'node server.mjs|npm run dev|npm run start' || true +npm run start ``` ## OpenShell And OpenClaw Notes @@ -195,6 +205,7 @@ The custom server in `server.mjs` also handles websocket upgrades for: - OpenClaw dashboard websocket traffic. Those upgrade paths are protected by the same auth cookie as the HTTP routes. +Behind a reverse proxy, route WebSocket upgrades for the dashboard proxy paths to the same `server.mjs` listener as the HTTP app. Use `OPENCLAW_DASHBOARD_BASE_WS_URL` or `BASE_WS_URL` only when the browser-visible WebSocket base must be a fully qualified override such as `wss://control.example.com/api/ws-proxy`. ## Remote Controller Nodes @@ -281,6 +292,7 @@ npm run dev npm run lint npx tsc --noEmit npm run build +npm run start ``` After running `npm run build` during development, restart cleanly: @@ -302,9 +314,13 @@ cp .env.example .env.local Common keys: ```bash +PORT=3000 NEXT_PUBLIC_DASHBOARD_PORT=3000 NEXT_PUBLIC_API_BASE=/api NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true +# OPENCLAW_DASHBOARD_BASE_WS_URL=wss://control.example.com +# BASE_WS_URL=wss://control.example.com +# OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001 OPEN_SHELL_CONTAINER=openshell-cluster-nemoclaw OPENSHELL_GATEWAY=nemoclaw # For containerized CLI runs, when supported by the installed OpenShell/NemoClaw versions: @@ -372,7 +388,7 @@ npm run build If the UI behaves oddly after a production build: ```bash -pkill -f 'node server.mjs|npm run dev' || true +pkill -f 'node server.mjs|npm run dev|npm run start' || true rm -rf .next npm run dev ``` diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts index 2e47db6..6241885 100644 --- a/app/api/auth/login/route.ts +++ b/app/api/auth/login/route.ts @@ -1,5 +1,5 @@ import { NextRequest, NextResponse } from "next/server" -import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyPassword } from "@/app/lib/controlAuth" +import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyPassword } from "@/app/lib/controlAuth" import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit" const AUTH_WINDOW_MS = 5 * 60 * 1000 @@ -34,6 +34,6 @@ export async function POST(request: NextRequest) { clearRateLimit(limitKey) const response = NextResponse.json({ ok: true, next: nextPath }) - response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request)) return response } diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts index 70db2d2..e376454 100644 --- a/app/api/auth/logout/route.ts +++ b/app/api/auth/logout/route.ts @@ -1,14 +1,11 @@ -import { NextResponse } from "next/server" -import { getAuthSettings } from "@/app/lib/controlAuth" +import { NextRequest, NextResponse } from "next/server" +import { getAuthSettings, sessionCookieOptionsForRequest } from "@/app/lib/controlAuth" -export async function POST() { +export async function POST(request: NextRequest) { const settings = getAuthSettings() const response = NextResponse.json({ ok: true }) response.cookies.set(settings.cookieName, "", { - httpOnly: true, - sameSite: "lax", - secure: process.env.NODE_ENV === "production", - path: "/", + ...sessionCookieOptionsForRequest(request), maxAge: 0, }) return response diff --git a/app/api/auth/recover/route.ts b/app/api/auth/recover/route.ts index 512a3b5..21d64a5 100644 --- a/app/api/auth/recover/route.ts +++ b/app/api/auth/recover/route.ts @@ -1,5 +1,5 @@ import { NextRequest, NextResponse } from "next/server" -import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyRecoveryToken } from "@/app/lib/controlAuth" +import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyRecoveryToken } from "@/app/lib/controlAuth" import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig" import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit" @@ -37,6 +37,6 @@ export async function POST(request: NextRequest) { recoveryToken: result.recoveryToken, note: "Password reset. Save the new recovery token from .env.local.", }) - response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request)) return response } diff --git a/app/api/auth/setup/route.ts b/app/api/auth/setup/route.ts index 683aff3..08fdc1a 100644 --- a/app/api/auth/setup/route.ts +++ b/app/api/auth/setup/route.ts @@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server" import { createSessionCookieValue, getAuthSettings, - sessionCookieOptions, + sessionCookieOptionsForRequest, verifyPassword, verifyRecoveryToken, verifySessionCookieValue, @@ -54,6 +54,6 @@ export async function POST(request: NextRequest) { recoveryToken: result.recoveryToken, note: "Password updated. Save the new recovery token from .env.local.", }) - response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request)) return response } diff --git a/app/api/inference/route.ts b/app/api/inference/route.ts index d886b75..32191f1 100644 --- a/app/api/inference/route.ts +++ b/app/api/inference/route.ts @@ -106,8 +106,12 @@ function isVllmEndpoint(name: string, baseUrl: string) { return [name, baseUrl].some((value) => /vllm/i.test(value)) } +function isOllamaEndpoint(name: string, baseUrl: string) { + return [name, baseUrl].some((value) => /ollama|11434/i.test(value)) +} + function normalizeProviderType(type: string, name: string, baseUrl: string) { - return isVllmEndpoint(name, baseUrl) ? "openai" : type + return isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl) ? "openai" : type } function redactSecretOutput(value: string, secrets: string[] = []) { @@ -153,7 +157,7 @@ export async function POST(request: Request) { const credentialKey = optionalString(body?.credentialKey) || "OPENAI_API_KEY" const makeActive = body?.makeActive !== false const system = body?.route === "system" || body?.system === true - const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl) + const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl) const timeout = Number(body?.timeout ?? 0) if (makeActive && !model) throw new Error("model is required when making the endpoint active") diff --git a/app/api/openshell/dashboard/open/route.ts b/app/api/openshell/dashboard/open/route.ts index d9b7a81..77796be 100644 --- a/app/api/openshell/dashboard/open/route.ts +++ b/app/api/openshell/dashboard/open/route.ts @@ -2,6 +2,7 @@ import { NextResponse } from 'next/server' import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost' import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances' import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority' +import { extractOpenClawDashboardToken, setOpenClawDashboardTokenCookie } from '../../../../lib/openclawDashboardToken' function parseInventoryCount(requestUrl: URL) { const raw = requestUrl.searchParams.get('inventoryCount') @@ -14,12 +15,37 @@ function firstHeaderValue(value: string | null) { return value?.split(',')[0]?.trim() || null } +function getConfiguredBaseWsUrl() { + return process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || null +} + +function normalizeBrowserWebSocketBase(value: string | null, proxiedUrl: string) { + if (!value) return null + const parsed = new URL(value) + if (parsed.protocol === 'http:') parsed.protocol = 'ws:' + if (parsed.protocol === 'https:') parsed.protocol = 'wss:' + if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') { + throw new Error('OPENCLAW_DASHBOARD_BASE_WS_URL/BASE_WS_URL must use ws://, wss://, http://, or https://') + } + + parsed.hash = '' + if (parsed.pathname === '/' || parsed.pathname === '') { + parsed.pathname = proxiedUrl + } else { + parsed.pathname = parsed.pathname.replace(/\/+$/, '') || '/' + } + return parsed.toString() +} + function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: string) { + const configuredBaseWsUrl = normalizeBrowserWebSocketBase(getConfiguredBaseWsUrl(), proxiedUrl) + if (configuredBaseWsUrl) return configuredBaseWsUrl + const forwardedProtocol = firstHeaderValue(request.headers.get('x-forwarded-proto')) const forwardedHost = firstHeaderValue(request.headers.get('x-forwarded-host')) const host = forwardedHost || request.headers.get('host') || requestUrl.host const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, '')) === 'https' ? 'wss:' : 'ws:' - const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001' + const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '' const gatewayHost = wsProxyPort ? new URL(`${requestUrl.protocol}//${host}`).hostname + `:${wsProxyPort}` : host @@ -82,7 +108,7 @@ export async function GET(request: Request) { const proxiedUrl = authority.bridgeActive ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy' const launchUrl = buildLaunchUrl(request, requestUrl, proxiedUrl, probe.bootstrapUrl) - return NextResponse.json({ + const response = NextResponse.json({ ok: true, sandboxId, sandboxInstanceId: mappedSandboxInstanceId, @@ -130,4 +156,6 @@ export async function GET(request: Request) { ? '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.' }) + setOpenClawDashboardTokenCookie(response, request, proxiedUrl, extractOpenClawDashboardToken(probe.bootstrapUrl)) + return response } diff --git a/app/api/openshell/dashboard/proxy/shared.ts b/app/api/openshell/dashboard/proxy/shared.ts index c1d161c..c1af3be 100644 --- a/app/api/openshell/dashboard/proxy/shared.ts +++ b/app/api/openshell/dashboard/proxy/shared.ts @@ -1,11 +1,13 @@ import { NextResponse } from 'next/server' import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost' +import { OPENCLAW_DASHBOARD_TOKEN_COOKIE } from '@/app/lib/openclawDashboardToken' 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 BOOTSTRAP_SCRIPT_NAME = '__nemoclaw_openclaw_bootstrap.js' +const CONTROL_AUTH_COOKIE_NAME = 'openshell_control_session' const HOP_BY_HOP_HEADERS = new Set([ 'accept-encoding', 'connection', @@ -95,6 +97,7 @@ function buildTargetUrl(requestUrl: URL) { function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: string) { const headers = new Headers() + const dashboardToken = readCookieValue(request.headers.get('cookie'), OPENCLAW_DASHBOARD_TOKEN_COOKIE) request.headers.forEach((value, key) => { const lowerKey = key.toLowerCase() @@ -104,16 +107,42 @@ function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: stri lowerKey !== 'origin' && lowerKey !== 'referer' ) { - headers.set(key, value) + const filteredValue = lowerKey === 'cookie' ? filterCookieHeader(value) : value + if (filteredValue) headers.set(key, filteredValue) } }) headers.set('host', target.host) headers.set('origin', controlUiOrigin) headers.set('referer', `${controlUiOrigin}/`) + if (dashboardToken && !headers.has('authorization')) { + headers.set('authorization', `Bearer ${dashboardToken}`) + } return headers } +function readCookieValue(value: string | null, name: string) { + return String(value || '') + .split(';') + .map((part) => part.trim()) + .reduce((found, part) => { + if (found || !part.startsWith(`${name}=`)) return found + try { + return decodeURIComponent(part.slice(name.length + 1)) + } catch { + return part.slice(name.length + 1) + } + }, null) +} + +function filterCookieHeader(value: string) { + return value + .split(';') + .map((part) => part.trim()) + .filter((part) => part && !part.startsWith(`${CONTROL_AUTH_COOKIE_NAME}=`) && !part.startsWith(`${OPENCLAW_DASHBOARD_TOKEN_COOKIE}=`)) + .join('; ') +} + function copyResponseHeaders(upstream: Response) { const headers = new Headers() @@ -151,24 +180,46 @@ function isBootstrapScriptRequest(requestUrl: URL, proxyPrefix: string) { } function bootstrapScriptResponse(proxyPrefix: string) { - const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001' + const baseWsUrl = process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || '' + const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '' const script = ` (() => { const proxyPrefix = ${JSON.stringify(proxyPrefix)}; + const baseWsUrl = ${JSON.stringify(baseWsUrl)}; const wsProxyPort = ${JSON.stringify(wsProxyPort)}; window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix; try { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix; - const sidecarHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host; - const sidecarGatewayUrl = protocol + '//' + sidecarHost + proxyPrefix; + const portGatewayUrl = wsProxyPort ? protocol + '//' + window.location.hostname + ':' + wsProxyPort + proxyPrefix : ''; + const normalizeGatewayUrl = (value) => { + const raw = (value || '').trim(); + if (!raw) return ''; + try { + const parsed = new URL(raw, window.location.href); + if (parsed.protocol === 'http:') parsed.protocol = 'ws:'; + if (parsed.protocol === 'https:') parsed.protocol = 'wss:'; + if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') return ''; + parsed.hash = ''; + if (parsed.pathname === '/' || parsed.pathname === '') { + parsed.pathname = proxyPrefix; + } else { + parsed.pathname = parsed.pathname.replace(/\\/+$/, '') || '/'; + } + return parsed.toString(); + } catch { + return ''; + } + }; + const configuredGatewayUrl = normalizeGatewayUrl(baseWsUrl); + const defaultGatewayUrl = configuredGatewayUrl || portGatewayUrl || pageGatewayUrl; const settingsKey = 'openclaw.control.settings.v1'; const settingsPrefix = 'openclaw.control.settings.v1:'; const tokenKey = 'openclaw.control.token.v1'; const tokenPrefix = 'openclaw.control.token.v1:'; const hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash); - const gatewayUrl = (hashParams.get('gatewayUrl') || '').trim() || sidecarGatewayUrl; + const gatewayUrl = normalizeGatewayUrl(hashParams.get('gatewayUrl')) || defaultGatewayUrl; const token = (hashParams.get('token') || '').trim(); const storageScope = (value) => { try { @@ -180,7 +231,7 @@ function bootstrapScriptResponse(proxyPrefix: string) { } }; const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean))); - const gatewayScopes = uniqueScopes([gatewayUrl, sidecarGatewayUrl, pageGatewayUrl]); + const gatewayScopes = uniqueScopes([gatewayUrl, configuredGatewayUrl, portGatewayUrl, pageGatewayUrl]); const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope); const readSettings = () => { for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) { diff --git a/app/api/sandbox/[sandboxId]/health/route.ts b/app/api/sandbox/[sandboxId]/health/route.ts index 6299764..72e9f82 100644 --- a/app/api/sandbox/[sandboxId]/health/route.ts +++ b/app/api/sandbox/[sandboxId]/health/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from "next/server" import { execOpenShell, normalizeSandboxPhase, resolveSandboxRef } from "@/app/lib/openshellHost" import { listBackupCatalog } from "@/app/lib/backupCatalog" +import { getNemoClawDoctorReport } from "@/app/lib/nemoclawCli" function parseField(output: string, label: string) { const normalizedLabel = label.toLowerCase() @@ -23,6 +24,15 @@ export async function GET( const phase = normalizeSandboxPhase(parseField(resolved.details, "Phase")) const catalog = await listBackupCatalog() const relatedBackups = catalog.filter((backup) => backup.sandboxId === sandboxId || backup.sandboxName === resolved.name) + const nemoclawDoctor = await getNemoClawDoctorReport(resolved.name).catch((error) => ({ + available: false, + supported: false, + attempted: false, + version: null, + minimumVersion: "0.0.37", + report: null, + error: error instanceof Error ? error.message : "NemoClaw doctor check failed", + })) let sshConfig = "" let sshConfigError = "" @@ -60,6 +70,16 @@ export async function GET( ? `${relatedBackups.length} saved backup${relatedBackups.length === 1 ? "" : "s"} in catalog.` : "No saved catalog backups yet.", }, + { + key: "nemoclaw-doctor", + label: "NemoClaw doctor", + ok: !nemoclawDoctor.supported || Boolean(nemoclawDoctor.report && nemoclawDoctor.report.status !== "fail"), + detail: nemoclawDoctor.supported + ? nemoclawDoctor.report + ? `NemoClaw ${nemoclawDoctor.version || "unknown"} doctor reported ${nemoclawDoctor.report.status} (${nemoclawDoctor.report.failed} failed, ${nemoclawDoctor.report.warnings} warnings).` + : nemoclawDoctor.error || "NemoClaw doctor did not return a report." + : `Using OpenShell compatibility checks; NemoClaw doctor requires ${nemoclawDoctor.minimumVersion}+${nemoclawDoctor.version ? `, found ${nemoclawDoctor.version}` : ""}.`, + }, ] return NextResponse.json({ @@ -71,6 +91,19 @@ export async function GET( phase, }, checks, + nemoclaw: { + doctor: { + available: nemoclawDoctor.available, + supported: nemoclawDoctor.supported, + attempted: nemoclawDoctor.attempted, + version: nemoclawDoctor.version, + minimumVersion: nemoclawDoctor.minimumVersion, + status: nemoclawDoctor.report?.status ?? null, + failed: nemoclawDoctor.report?.failed ?? null, + warnings: nemoclawDoctor.report?.warnings ?? null, + error: nemoclawDoctor.error ?? null, + }, + }, backupCount: relatedBackups.length, durationMs: Date.now() - startedAt, checkedAt: new Date().toISOString(), diff --git a/app/api/sandbox/[sandboxId]/restart/route.ts b/app/api/sandbox/[sandboxId]/restart/route.ts index fae403c..ef1d4aa 100644 --- a/app/api/sandbox/[sandboxId]/restart/route.ts +++ b/app/api/sandbox/[sandboxId]/restart/route.ts @@ -2,6 +2,7 @@ import { NextResponse } from "next/server" import { execFile } from "node:child_process" import { promisify } from "node:util" import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands" +import { recoverSandboxWithNemoClaw } from "@/app/lib/nemoclawCli" import { inspectSandbox, resolveSandboxRef } from "@/app/lib/openshellHost" const execFileAsync = promisify(execFile) @@ -100,6 +101,21 @@ export async function POST( }, { status: 409 }) } + const nemoclawRecover = await recoverSandboxWithNemoClaw(sandboxName) + if (nemoclawRecover.attempted && nemoclawRecover.ok) { + return NextResponse.json({ + ok: true, + restarted: true, + restartMode: "nemoclaw-recover", + sandboxId: resolved.id, + sandboxName, + readiness, + nemoclawRecover, + elapsedMs: Date.now() - startedAt, + note: "NemoClaw recover completed. The sandbox runtime and dashboard forward were checked without deleting the sandbox.", + }) + } + const runtime = await runSandboxShell(sandboxName, restartOpenClawGatewayScript(), 45000) return NextResponse.json({ @@ -109,9 +125,12 @@ export async function POST( sandboxId: resolved.id, sandboxName, readiness, + nemoclawRecover, runtime, elapsedMs: Date.now() - startedAt, - note: "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.", + note: nemoclawRecover.attempted + ? "NemoClaw recover did not complete, so the dashboard fell back to restarting the in-sandbox OpenClaw runtime. The sandbox pod was not deleted." + : "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.", }) } catch (error) { const message = error instanceof Error ? error.message : "Failed to restart sandbox runtime" diff --git a/app/components/InferenceEndpointPanel.tsx b/app/components/InferenceEndpointPanel.tsx index 15cffdf..741c47b 100644 --- a/app/components/InferenceEndpointPanel.tsx +++ b/app/components/InferenceEndpointPanel.tsx @@ -40,6 +40,9 @@ const providerTypeOptions = [ { value: "generic", label: "Generic" }, ] +const OLLAMA_PROVIDER_NAME = "ollama-local" +const OLLAMA_BASE_URL = "http://host.docker.internal:11434/v1" + function emptyRoute(): InferenceRoute { return { configured: false, provider: null, model: null, version: null, timeout: null } } @@ -111,7 +114,7 @@ export default function InferenceEndpointPanel() { } const models = Array.isArray(data.models) ? data.models : [] setOllamaModels(models) - setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available.` : "Ollama is reachable but has no models installed.") + setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available. Click one to load the Ollama endpoint preset.` : "Ollama is reachable but has no models installed.") if (models[0]?.name) setModel((current) => current || models[0].name) } catch (error) { setOllamaModels([]) @@ -122,11 +125,22 @@ export default function InferenceEndpointPanel() { }, []) useEffect(() => { - if (!isOllamaEndpoint) return loadOllamaModels({ silent: true }) const interval = window.setInterval(() => loadOllamaModels({ silent: true }), 10000) return () => window.clearInterval(interval) - }, [isOllamaEndpoint, loadOllamaModels]) + }, [loadOllamaModels]) + + function applyOllamaModelPreset(modelName: string) { + setName(OLLAMA_PROVIDER_NAME) + setType("openai") + setModel(modelName) + setBaseUrl(OLLAMA_BASE_URL) + setCredentialKey("OPENAI_API_KEY") + setApiKey("") + setRoute("gateway") + setNoVerify(true) + setMessage(`Ollama preset loaded for ${modelName}. Save to route sandbox inference through local Ollama.`) + } function selectProvider(provider: ProviderSummary) { if (!provider.name) return @@ -134,7 +148,7 @@ export default function InferenceEndpointPanel() { setType(provider.type || "openai") setCredentialKey(provider.credentialKeys[0] || "OPENAI_API_KEY") if (provider.name.toLowerCase().includes("ollama")) { - setBaseUrl("http://host.docker.internal:11434/v1") + setBaseUrl(OLLAMA_BASE_URL) setApiKey("") } setMessage(`Loaded ${provider.name}. Enter a model and save to make it active.`) @@ -252,6 +266,32 @@ export default function InferenceEndpointPanel() {
+
+
+
+

Ollama Models

+

{ollamaMessage || "Polling local Ollama every 10 seconds."}

+
+ +
+ {ollamaModels.length > 0 ? ( +
+ {ollamaModels.map((item) => ( + + ))} +
+ ) : ( +

No local Ollama models reported.

+ )} +
+
Provider Name @@ -303,32 +343,6 @@ export default function InferenceEndpointPanel() { Skip provider verification while saving - {isOllamaEndpoint && ( -
-
-
-

Ollama Models

-

{ollamaMessage || "Polling local Ollama every 10 seconds."}

-
- -
- {ollamaModels.length > 0 && ( -
- {ollamaModels.map((item) => ( - - ))} -
- )} -
- )} -