diff --git a/src/lib/actions/gateway-drift-preflight.test.ts b/src/lib/actions/gateway-drift-preflight.test.ts index b0da0f52f06..de4706da207 100644 --- a/src/lib/actions/gateway-drift-preflight.test.ts +++ b/src/lib/actions/gateway-drift-preflight.test.ts @@ -173,7 +173,12 @@ describe("gateway drift preflight for maintenance actions", () => { await backupAll(); expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], }); expect(captureOpenshellSpy).toHaveBeenCalledTimes(2); expect(captureOpenshellSpy).toHaveBeenNthCalledWith(1, ["sandbox", "list"]); @@ -258,7 +263,12 @@ describe("gateway drift preflight for maintenance actions", () => { await upgradeSandboxes({ check: true }); expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], }); expect(captureOpenshellSpy).toHaveBeenCalledTimes(2); expect(classifyUpgradeableSandboxesSpy).toHaveBeenCalledWith( diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 874234b015a..3e1f83bc7a9 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -26,6 +26,8 @@ import { import { findReachableOllamaHost, probeLocalProviderHealth } from "../../inference/local"; import { ensureOllamaAuthProxy, probeOllamaAuthProxyHealth } from "../../inference/ollama/proxy"; import { LOCAL_INFERENCE_TIMEOUT_SECS } from "../../onboard/env"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { isWsl } from "../../platform"; import { ROOT } from "../../runner"; import * as sandboxVersion from "../../sandbox/version"; @@ -54,8 +56,6 @@ import { ensureLiveSandboxOrExit, printGatewayLifecycleHint } from "./gateway-st import { checkAndRecoverSandboxProcesses } from "./process-recovery"; import { applyOpenShellVmDnsMonkeypatch, shouldApplyVmDnsMonkeypatch } from "./vm-dns-monkeypatch"; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; - export type SandboxConnectOptions = { probeOnly?: boolean; }; @@ -253,7 +253,9 @@ function failConnectReadinessGatewayUnavailable(sandboxName: string, detailOutpu printGatewayLifecycleHint(detailOutput, sandboxName, console.error); } console.error(" Recovery:"); - console.error(" 1. Run: openshell gateway start --name nemoclaw"); + console.error( + ` 1. Run: openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}`, + ); console.error(` 2. If the gateway cannot be restarted, run: ${CLI_NAME} onboard`); console.error(` 3. Retry: ${CLI_NAME} ${sandboxName} connect`); process.exit(1); @@ -273,7 +275,8 @@ function failConnectReadinessDockerRuntimeDown(sandboxName: string): never { } function failIfGatewayBlocksConnectReadiness(sandboxName: string): void { - const lifecycle = getNamedGatewayLifecycleState(); + const sb = registry.getSandbox(sandboxName); + const lifecycle = getNamedGatewayLifecycleState(resolveSandboxGatewayName(sb)); if (isBlockingGatewayLifecycle(lifecycle)) { failConnectReadinessGatewayUnavailable( sandboxName, @@ -512,7 +515,7 @@ function repairSandboxInferenceRouteIfNeeded( reapplyVmInferenceRoute, repairLegacyDnsProxy: (name, isQuiet) => runSetupDnsProxy( - { gatewayName: NEMOCLAW_GATEWAY_NAME, sandboxName: name }, + { gatewayName: resolveSandboxGatewayName(sb), sandboxName: name }, { log: isQuiet ? () => undefined : console.log }, ), }, diff --git a/src/lib/actions/sandbox/destroy-gateway.ts b/src/lib/actions/sandbox/destroy-gateway.ts new file mode 100644 index 00000000000..acb9dd5de05 --- /dev/null +++ b/src/lib/actions/sandbox/destroy-gateway.ts @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import os from "node:os"; +import path from "node:path"; + +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { DASHBOARD_PORT } from "../../core/ports"; +import { + resolveGatewayPortFromName, + resolveGatewayStateDirName, +} from "../../onboard/gateway-binding"; +import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; +import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; + +export type DestroyRunOpenshell = ( + args: string[], + opts?: Record, +) => { status: number | null; stdout?: string; stderr?: string }; + +const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); + +// Compute the Docker-driver gateway state directory that belongs to +// `gatewayName`. `stopHostGatewayProcesses` defaults to the bare leaf +// `openshell-docker-gateway`, so without this override a destroy of a +// `nemoclaw-` sandbox would read the default instance's pid file and +// stop the wrong host gateway process. Returns null when the gateway name is +// outside the NemoClaw namespace (the caller then keeps the defaults). +function resolvePerGatewayStateDir(gatewayName: string): string | null { + const port = resolveGatewayPortFromName(gatewayName); + if (port === null) return null; + const configured = process.env.NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR; + if (configured && configured.trim()) { + return path.resolve(configured.trim()); + } + return path.join(os.homedir(), ".local", "state", "nemoclaw", resolveGatewayStateDirName(port)); +} + +export function selectGatewayForSandboxDestroy( + sandboxName: string, + gatewayName: string, + runOpenshell: DestroyRunOpenshell, +): void { + const result = runOpenshell(["gateway", "select", gatewayName], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + if (result.status === 0) return; + + const output = [result.stdout, result.stderr].filter(Boolean).join("\n").trim(); + if (output) { + console.error(` ${output}`); + } + console.error( + ` Failed to select gateway '${gatewayName}' before destroying sandbox '${sandboxName}'.`, + ); + process.exit(result.status || 1); +} + +export function cleanupGatewayAfterLastSandbox( + gatewayName: string, + runOpenshell?: DestroyRunOpenshell, +): void { + const openshell = + runOpenshell ?? + (require("../../adapters/openshell/runtime") as { runOpenshell: DestroyRunOpenshell }) + .runOpenshell; + const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as { + dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void; + }; + + openshell(["forward", "stop", DASHBOARD_FORWARD_PORT], { + ignoreError: true, + stdio: ["ignore", "ignore", "ignore"], + }); + // After the cooperative forward-stop, sweep the dashboard port range for + // stale host-side gateway-forward processes. The forward-stop above releases + // ports the live openshell tracks; this catches orphans whose openshell + // record was lost across upgrades or failed onboards. + stopStaleDashboardListeners(); + if (process.platform === "linux") { + // Sandbox destroy is conservative: only stop the host gateway whose PID + // file we wrote during onboard. Disable the pgrep sweep so a stray + // openshell-gateway under another user/project on the same host (rare but + // possible on shared hosts) is not torn down by a NemoClaw `destroy`. + // The uninstall path keeps the broader sweep on (run-plan.ts). The state + // dir is per-gateway-name so a destroy of `nemoclaw-` reads the + // per-port pid file rather than defaulting to the bare instance's. + const perGatewayStateDir = resolvePerGatewayStateDir(gatewayName); + const stopOptions: { usePgrepFallback: false; stateDir?: string; pidFile?: string } = { + usePgrepFallback: false, + }; + if (perGatewayStateDir) { + stopOptions.stateDir = perGatewayStateDir; + stopOptions.pidFile = path.join(perGatewayStateDir, "openshell-gateway.pid"); + } + stopHostGatewayProcesses({}, stopOptions); + const removeResult = openshell(["gateway", "remove", gatewayName], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }); + if (removeResult.status !== 0) { + openshell(["gateway", "destroy", "-g", gatewayName], { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + }); + } + } else { + openshell(["gateway", "destroy", "-g", gatewayName], { + ignoreError: true, + }); + } + dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, { + ignoreError: true, + }); +} diff --git a/src/lib/actions/sandbox/destroy.ts b/src/lib/actions/sandbox/destroy.ts index 89b591c2a9c..a593fc02b18 100644 --- a/src/lib/actions/sandbox/destroy.ts +++ b/src/lib/actions/sandbox/destroy.ts @@ -8,7 +8,6 @@ import { resolveOpenshell } from "../../adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { G, R, YW } from "../../cli/terminal-style"; -import { DASHBOARD_PORT } from "../../core/ports"; import { prompt as askPrompt } from "../../credentials/store"; import { type DestroySandboxOptions, @@ -19,8 +18,6 @@ import { shouldCleanupGatewayAfterDestroy, shouldStopHostServicesAfterDestroy, } from "../../domain/sandbox/destroy"; -import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; -import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { SANDBOX_PROVIDER_SUFFIXES, emitProviderDetachResidualHint, @@ -37,6 +34,12 @@ import { createSystemDeps as createSessionDeps, getActiveSandboxSessions, } from "../../state/sandbox-session"; +import { + cleanupGatewayAfterLastSandbox, + type DestroyRunOpenshell, + selectGatewayForSandboxDestroy, +} from "./destroy-gateway"; +import { getSandboxTargetGatewayName } from "./gateway-target"; type DockerRmi = (tag: string, opts?: { ignoreError?: boolean }) => { status: number | null }; @@ -76,53 +79,6 @@ type RemoveShieldsStateDeps = { warn?: (message: string) => void; }; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; -const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); - -function cleanupGatewayAfterLastSandbox(): void { - const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: (args: string[], opts?: Record) => { status: number | null }; - }; - const { dockerRemoveVolumesByPrefix } = require("../../adapters/docker") as { - dockerRemoveVolumesByPrefix: (prefix: string, opts?: { ignoreError?: boolean }) => void; - }; - - runOpenshell(["forward", "stop", DASHBOARD_FORWARD_PORT], { - ignoreError: true, - stdio: ["ignore", "ignore", "ignore"], - }); - // After the cooperative forward-stop, sweep the dashboard port range for - // stale host-side gateway-forward processes (#3397, #3398). The forward-stop - // above releases ports the live openshell tracks; this catches orphans whose - // openshell record was lost across upgrades or failed onboards. - stopStaleDashboardListeners(); - if (process.platform === "linux") { - // Sandbox destroy is conservative: only stop the host gateway whose PID - // file we wrote during onboard. Disable the pgrep sweep so a stray - // openshell-gateway under another user/project on the same host (rare but - // possible on shared hosts) is not torn down by a NemoClaw `destroy`. - // The uninstall path keeps the broader sweep on (run-plan.ts). - stopHostGatewayProcesses({}, { usePgrepFallback: false }); - const removeResult = runOpenshell(["gateway", "remove", NEMOCLAW_GATEWAY_NAME], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - if (removeResult.status !== 0) { - runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - }); - } - } else { - runOpenshell(["gateway", "destroy", "-g", NEMOCLAW_GATEWAY_NAME], { - ignoreError: true, - }); - } - dockerRemoveVolumesByPrefix(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, { - ignoreError: true, - }); -} - // Mirrors the body of `isNonInteractive()` in src/lib/onboard.ts. Duplicated // here to avoid an awkward sibling-action -> onboard import; the canonical // helper should be lifted to src/lib/core/ so this and the lazy requires in @@ -403,11 +359,13 @@ export async function destroySandbox( console.log(` Deleting sandbox '${sandboxName}'...`); const { runOpenshell } = require("../../adapters/openshell/runtime") as { - runOpenshell: ( - args: string[], - opts?: Record, - ) => { status: number | null; stdout?: string; stderr?: string }; + runOpenshell: DestroyRunOpenshell; }; + // Capture and select the sandbox's gateway before any destructive OpenShell + // operation. Provider cleanup and sandbox delete must address the gateway + // recorded for this sandbox, not whichever gateway happens to be active. + const cleanupGatewayName = getSandboxTargetGatewayName(sandboxName); + selectGatewayForSandboxDestroy(sandboxName, cleanupGatewayName, runOpenshell); const detachOutcome = runSandboxProviderPreDeleteCleanup(sandboxName, { runOpenshell, redact, @@ -437,6 +395,9 @@ export async function destroySandbox( stopHostServices: shouldStopHostServices, }); cleanupShieldsDestroyArtifacts(sandboxName); + // The sandbox's gateway was captured before the registry entry is removed — + // post-removal lookups return null and would collapse the cleanup target + // back to the default gateway. const removed = removeSandboxRegistryEntry(sandboxName); const session = onboardSession.loadSession(); if (session && session.sandboxName === sandboxName) { @@ -455,12 +416,12 @@ export async function destroySandbox( ) { const shouldCleanupGateway = await resolveCleanupGatewayDecision(normalized); if (shouldCleanupGateway) { - cleanupGatewayAfterLastSandbox(); + cleanupGatewayAfterLastSandbox(cleanupGatewayName, runOpenshell); } else { const gatewayRemovalHint = process.platform === "linux" - ? `openshell gateway remove ${NEMOCLAW_GATEWAY_NAME}` - : `openshell gateway destroy -g ${NEMOCLAW_GATEWAY_NAME}`; + ? `openshell gateway remove ${cleanupGatewayName}` + : `openshell gateway destroy -g ${cleanupGatewayName}`; console.log( ` Shared NemoClaw gateway preserved. Re-run '${gatewayRemovalHint}' to remove it,`, ); diff --git a/src/lib/actions/sandbox/doctor-gateway-fallback.ts b/src/lib/actions/sandbox/doctor-gateway-fallback.ts index 4e9a3253043..b053eafac82 100644 --- a/src/lib/actions/sandbox/doctor-gateway-fallback.ts +++ b/src/lib/actions/sandbox/doctor-gateway-fallback.ts @@ -8,6 +8,7 @@ import { captureHostCommand, type CommandCapture } from "./doctor-host-command"; export type GatewayInspectOptions = { namedGatewayConnected?: boolean; + gatewayName?: string; }; type LocalGatewayProbe = { diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index de4547b7bd5..8ca632056fe 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -18,6 +18,7 @@ import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action"; import { parseGatewayInference } from "../../inference/config"; import { type ProviderHealthStatus, probeProviderHealth } from "../../inference/health"; import { isLinuxDockerDriverGatewayEnabled } from "../../onboard/docker-driver-platform"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { executeSandboxCommandForVerification } from "../../onboard/sandbox-verification-exec"; import { ROOT } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; @@ -37,8 +38,6 @@ import { captureHostCommand } from "./doctor-host-command"; import { buildToolScopeChecks } from "./doctor-tool-scope"; import { probeSandboxInferenceGatewayHealth } from "./process-recovery"; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; - type DoctorStatus = "ok" | "warn" | "fail" | "info"; export type DoctorCheck = { @@ -193,7 +192,7 @@ function dockerInspectGateway( detail: `${containerName} ${running ? "running" : "stopped"} (${health}; ${image})`, hint: running ? undefined - : "restart the gateway with `openshell gateway start --name nemoclaw`", + : `restart the gateway with \`openshell gateway start --name ${options.gatewayName ?? "nemoclaw"}\``, }); const port = captureHostCommand("docker", ["port", containerName, "30051/tcp"], 5000); @@ -550,6 +549,7 @@ export async function runSandboxDoctor( } const sb = registry.getSandbox(sandboxName); + const gatewayName = sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); const checks: DoctorCheck[] = []; // Tracks whether the named sandbox is present-and-Ready, so live-only probes // (e.g. the #4616 dashboard tool-scope diagnostic) only run when they can @@ -594,7 +594,7 @@ export async function runSandboxDoctor( let openshellConnected = false; if (openshellBin) { - const recovery = await recoverNamedGatewayRuntime(); + const recovery = await recoverNamedGatewayRuntime({ gatewayName }); const lifecycle = recovery.after || recovery.before; const cleanStatus = stripAnsi(lifecycle?.status || ""); openshellConnected = lifecycle?.state === "healthy_named"; @@ -603,16 +603,19 @@ export async function runSandboxDoctor( label: "OpenShell status", status: openshellConnected ? "ok" : "fail", detail: openshellConnected - ? "connected to nemoclaw" - : oneLine(cleanStatus || lifecycle?.gatewayInfo || "not connected to nemoclaw"), - hint: openshellConnected ? undefined : "run `openshell gateway select nemoclaw` and retry", + ? `connected to ${gatewayName}` + : oneLine(cleanStatus || lifecycle?.gatewayInfo || `not connected to ${gatewayName}`), + hint: openshellConnected + ? undefined + : `run \`openshell gateway select ${gatewayName}\` and retry`, }); } if (shouldInspectLegacyGatewayContainer(sb)) { checks.push( - ...dockerInspectGateway(`openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`, { + ...dockerInspectGateway(`openshell-cluster-${gatewayName}`, { namedGatewayConnected: openshellConnected, + gatewayName, }), ); } diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index 8830dd1fa40..8bc9d0d027d 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -36,6 +36,8 @@ describe("sandbox gateway state drift guard", () => { let captureOpenshellForStatusSpy: MockInstance; let detectPreflightIssueSpy: MockInstance; let getNamedGatewayLifecycleStateSpy: MockInstance; + let getSandboxSpy: MockInstance; + let recoverNamedGatewayRuntimeSpy: MockInstance; let runOpenshellSpy: MockInstance; let removeSandboxSpy: MockInstance; @@ -49,6 +51,8 @@ describe("sandbox gateway state drift guard", () => { const gatewayRuntime = requireDist("../../../../dist/lib/gateway-runtime-action.js"); const registry = requireDist("../../../../dist/lib/state/registry.js"); + getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue(null); + captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") .mockReturnValue({ status: 0, output: "Sandbox:\n Name: alpha\n Phase: Ready" }); @@ -69,6 +73,11 @@ describe("sandbox gateway state drift guard", () => { state: "healthy_named", status: "", } as never); + recoverNamedGatewayRuntimeSpy = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ + recovered: false, + } as never); spies.push( detectPreflightIssueSpy, @@ -85,9 +94,8 @@ describe("sandbox gateway state drift guard", () => { runOpenshellSpy, vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false), getNamedGatewayLifecycleStateSpy, - vi.spyOn(gatewayRuntime, "recoverNamedGatewayRuntime").mockResolvedValue({ - recovered: false, - } as never), + getSandboxSpy, + recoverNamedGatewayRuntimeSpy, removeSandboxSpy, ); @@ -158,4 +166,32 @@ describe("sandbox gateway state drift guard", () => { ); expect(removeSandboxSpy).not.toHaveBeenCalled(); }); + + it("routes gateway-error recovery to the sandbox persisted gateway", async () => { + detectPreflightIssueSpy.mockReturnValue(null); + getSandboxSpy.mockReturnValue({ + name: "alpha", + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + }); + recoverNamedGatewayRuntimeSpy.mockResolvedValue({ + recovered: true, + via: "start", + }); + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "gateway_error", output: "transport error" }) + .mockResolvedValueOnce({ state: "present", output: "Sandbox:\n Name: alpha" }); + + const lookup = await gatewayState.getReconciledSandboxGatewayState("alpha", { getState }); + + expect(lookup).toEqual( + expect.objectContaining({ + state: "present", + recoveredGateway: true, + recoveryVia: "start", + }), + ); + expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ gatewayName: "nemoclaw-8090" }); + }); }); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index 080ee32bdb6..0ed1f416b57 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -11,6 +11,7 @@ import { recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; +import { gatewayNamePattern, getSandboxTargetGatewayName } from "./gateway-target"; const { pruneKnownHostsEntries } = require("../../onboard") as { pruneKnownHostsEntries: (contents: string) => string; @@ -227,9 +228,10 @@ export function reconcileMissingAgainstNamedGateway( sandboxName: string, missingLookup: SandboxGatewayState, ): SandboxGatewayState { - const lifecycle = getNamedGatewayLifecycleState(); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state === "connected_other") { - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", targetGatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); @@ -241,13 +243,23 @@ export function reconcileMissingAgainstNamedGateway( return retry; } if (retry.state === "missing") { - const after = getNamedGatewayLifecycleState(); + const after = getNamedGatewayLifecycleState(targetGatewayName); if (after.state === "healthy_named") { // Even with the right gateway selected, the sandbox is // still missing. Try Docker-side recovery before declaring // the sandbox truly absent. return tryRecoverDockerDriverSandbox(sandboxName, retry); } + // The select moved the active gateway off, but the target gateway is + // now missing or unreachable. Surface that post-select state so the + // caller emits restart guidance, rather than `wrong_gateway_active` + // pointing at the now-irrelevant pre-select active gateway. + if (after.state === "missing_named") { + return { state: "gateway_missing_after_restart", output: after.status }; + } + if (after.state === "named_unreachable" || after.state === "named_unhealthy") { + return { state: "gateway_unreachable_after_restart", output: after.status }; + } } return { state: "wrong_gateway_active", @@ -317,12 +329,14 @@ export function printWrongGatewayActiveGuidance( // guidance points back to the workflow the user actually invoked. retryCommand = "connect", ): void { - const other = activeGateway && activeGateway !== "nemoclaw" ? activeGateway : "another gateway"; + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const other = + activeGateway && activeGateway !== targetGatewayName ? activeGateway : "another gateway"; writer( - ` Sandbox '${sandboxName}' is registered against the ${CLI_DISPLAY_NAME} gateway, but the currently active OpenShell gateway is '${other}'. Your sandbox has NOT been removed.`, + ` Sandbox '${sandboxName}' is registered against the ${CLI_DISPLAY_NAME} gateway '${targetGatewayName}', but the currently active OpenShell gateway is '${other}'. Your sandbox has NOT been removed.`, ); writer(" Switch gateways and retry:"); - writer(" openshell gateway select nemoclaw"); + writer(` openshell gateway select ${targetGatewayName}`); writer(` Then re-run: ${CLI_NAME} ${sandboxName} ${retryCommand}`); } @@ -333,12 +347,13 @@ export function printGatewayLifecycleHint( writer: (message: string) => void = console.error, ): void { const cleanOutput = stripAnsi(output); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); if (/No gateway configured/i.test(cleanOutput)) { writer( ` The selected ${CLI_DISPLAY_NAME} gateway is no longer configured or its metadata/runtime has been lost.`, ); writer( - " Start the gateway again with `openshell gateway start --name nemoclaw` before expecting existing sandboxes to reconnect.", + ` Start the gateway again with \`openshell gateway start --name ${targetGatewayName}\` before expecting existing sandboxes to reconnect.`, ); writer( " If the gateway has to be rebuilt from scratch, recreate the affected sandbox afterward.", @@ -347,14 +362,14 @@ export function printGatewayLifecycleHint( } if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(cleanOutput) && - /Gateway:\s+nemoclaw/i.test(cleanOutput) + gatewayNamePattern(targetGatewayName).test(cleanOutput) ) { writer( " The selected NemoClaw gateway exists in metadata, but its API is refusing connections after restart.", ); writer(" This usually means the gateway runtime did not come back cleanly after the restart."); writer( - " Retry `openshell gateway start --name nemoclaw`; if it stays in this state, rebuild the gateway before expecting existing sandboxes to reconnect.", + ` Retry \`openshell gateway start --name ${targetGatewayName}\`; if it stays in this state, rebuild the gateway before expecting existing sandboxes to reconnect.`, ); return; } @@ -397,7 +412,8 @@ export async function getReconciledSandboxGatewayState( } if (lookup.state === "gateway_error") { - const recovery = await recoverNamedGatewayRuntime(); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); if (recovery.recovered) { const retried = await getState(sandboxName); if (retried.state === "present" || retried.state === "missing") { @@ -413,7 +429,7 @@ export async function getReconciledSandboxGatewayState( } return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } - const latestLifecycle = getNamedGatewayLifecycleState(); + const latestLifecycle = getNamedGatewayLifecycleState(targetGatewayName); const latestStatus = stripAnsi(latestLifecycle.status || ""); if (/No gateway configured/i.test(latestStatus)) { return { @@ -423,7 +439,7 @@ export async function getReconciledSandboxGatewayState( } if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(latestStatus) && - /Gateway:\s+nemoclaw/i.test(latestStatus) + gatewayNamePattern(targetGatewayName).test(latestStatus) ) { return { state: "gateway_unreachable_after_restart", @@ -478,7 +494,8 @@ export async function ensureLiveSandboxOrExit( process.exit(1); } if (lookup.state === "missing") { - const guard = getNamedGatewayLifecycleState(); + const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const guard = getNamedGatewayLifecycleState(targetGatewayName); if (guard.state !== "healthy_named") { if (guard.state === "connected_other") { printWrongGatewayActiveGuidance(sandboxName, guard.activeGateway, console.error); @@ -545,7 +562,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - " Retry `openshell gateway start --name nemoclaw` and verify `openshell status` is healthy before reconnecting.", + ` Retry \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, ); console.error( " If the gateway never becomes healthy, rebuild the gateway and then recreate the affected sandbox.", @@ -560,7 +577,7 @@ export async function ensureLiveSandboxOrExit( console.error(lookup.output); } console.error( - " Start the gateway again with `openshell gateway start --name nemoclaw` before retrying.", + ` Start the gateway again with \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` before retrying.`, ); console.error( " If the gateway had to be rebuilt from scratch, recreate the affected sandbox afterward.", diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts new file mode 100644 index 00000000000..d8232618920 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { GATEWAY_PORT } from "../../core/ports"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import * as registry from "../../state/registry"; + +export function getSandboxTargetGatewayName(sandboxName = ""): string { + const sb = sandboxName ? registry.getSandbox(sandboxName) : null; + return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); +} + +export function gatewayNamePattern(gatewayName: string): RegExp { + return new RegExp( + `Gateway:\\s+${gatewayName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=\\s|$)`, + "i", + ); +} diff --git a/src/lib/actions/sandbox/policy-channel-conflict.test.ts b/src/lib/actions/sandbox/policy-channel-conflict.test.ts index 45eb6fa40fd..78193ae6e5a 100644 --- a/src/lib/actions/sandbox/policy-channel-conflict.test.ts +++ b/src/lib/actions/sandbox/policy-channel-conflict.test.ts @@ -687,6 +687,44 @@ describe("addSandboxChannel cross-sandbox conflict check (#4305)", () => { expect(upsertMock).not.toHaveBeenCalled(); // aborted before registering }); + it("slack: a second sandbox on the SAME non-default gateway is blocked", async () => { + // Both sandboxes are bound to `nemoclaw-8090`. The credential axis would + // not flag distinct tokens, but the gateway axis must — without this case, + // `checkSlackSocketModeGatewayConflict` previously checked the default + // `nemoclaw` while the provider mutation ran against `nemoclaw-8090` and + // left a false negative for two Slack sandboxes sharing the same non- + // default gateway. + const slackBot = "xoxb-alpha-bot-token"; + const slackApp = "xapp-alpha-app-token"; + const alpha = { name: "alpha", gatewayName: "nemoclaw-8090", gatewayPort: 8090 } as never; + const bob = makePlanEntry("bob", "slack", [ + { + providerEnvKey: "SLACK_BOT_TOKEN", + credentialHash: hashCredential("xoxb-bob-bot") as string, + }, + { + providerEnvKey: "SLACK_APP_TOKEN", + credentialHash: hashCredential("xapp-bob-app") as string, + }, + ]); + (bob as { gatewayName?: string; gatewayPort?: number }).gatewayName = "nemoclaw-8090"; + (bob as { gatewayName?: string; gatewayPort?: number }).gatewayPort = 8090; + arrangeRegistry({ current: alpha, others: [bob] }); + getCredentialMock.mockImplementation((key: string) => + key === "SLACK_BOT_TOKEN" ? slackBot : key === "SLACK_APP_TOKEN" ? slackApp : null, + ); + promptMock.mockResolvedValue("n"); + + await addSandboxChannel("alpha", { channel: "slack" }); + + const text = loggedText(); + expect(text).toContain("Slack Socket Mode is already enabled for sandbox 'bob'"); + expect(text).not.toContain(slackBot); + expect(text).not.toContain(slackApp); + expect(conflictPromptShown()).toBe(true); + expect(upsertMock).not.toHaveBeenCalled(); + }); + it("slack: shared token on the same gateway reports the credential conflict first (#4953)", async () => { // The credential axis runs before the gateway axis, so a shared Slack token // surfaces the gateway-independent "same slack credential" warning (more diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index 026be1b4565..387439299ab 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -8,6 +8,7 @@ import { type AgentDefinition, loadAgent } from "../../agent/defs"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt, getCredential } from "../../credentials/store"; import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { type ChannelManifest, createBuiltInChannelManifestRegistry, @@ -456,14 +457,12 @@ async function checkSlackSocketModeGatewayConflict( let conflictMessages: string[] = []; try { const applier = require("../../messaging/applier") as typeof import("../../messaging/applier"); - const { BASE_GATEWAY_NAME } = - require("../../onboard/gateway-binding") as typeof import("../../onboard/gateway-binding"); - // `channels add` registers the Slack provider on the default `nemoclaw` + // `channels add` registers the Slack provider on the sandbox's target // gateway — applyChannelAddToGatewayAndRegistry → recoverNamedGatewayRuntime - // selects `nemoclaw` regardless of the sandbox's recorded gateway. Detect - // conflicts on the gateway the add actually mutates so the check matches the - // provider registration and cannot leave a false negative (#4953). - const gatewayName = BASE_GATEWAY_NAME; + // selects that same name. Detect conflicts on the gateway the add actually + // mutates so the check matches the provider registration and cannot leave a + // false negative for a sibling sandbox on the same non-default gateway. + const gatewayName = getSandboxTargetGatewayName(sandboxName); conflictMessages = applier .findSlackSocketModeGatewayConflicts( sandboxName, @@ -510,13 +509,14 @@ async function applyChannelAddToGatewayAndRegistry( token, })); if (tokenDefs.length > 0) { - const recovery = await recoverNamedGatewayRuntime(); + const gatewayName = getSandboxTargetGatewayName(sandboxName); + const recovery = await recoverNamedGatewayRuntime({ gatewayName }); if (!recovery.recovered) { console.error( ` Could not reach the ${CLI_DISPLAY_NAME} OpenShell gateway. Tokens were staged`, ); console.error(" in env for this run only — re-run after starting the gateway, or run"); - console.error(" 'openshell gateway start --name nemoclaw' manually."); + console.error(` 'openshell gateway start --name ${gatewayName}' manually.`); process.exit(1); } // upsertMessagingProviders handles create-or-update and process.exits on @@ -538,13 +538,14 @@ async function applyChannelRemoveToGatewayAndRegistry( let gatewayReachable = true; if (channelTokenKeys.length > 0) { - const recovery = await recoverNamedGatewayRuntime(); + const gatewayName = getSandboxTargetGatewayName(sandboxName); + const recovery = await recoverNamedGatewayRuntime({ gatewayName }); if (!recovery.recovered) { console.error( ` Could not reach the ${CLI_DISPLAY_NAME} OpenShell gateway to delete the bridge.`, ); console.error( - " Re-run after starting the gateway, or run 'openshell gateway start --name nemoclaw'.", + ` Re-run after starting the gateway, or run 'openshell gateway start --name ${gatewayName}'.`, ); if (!bestEffort) process.exit(1); gatewayReachable = false; diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 80052d07808..f3cb8d045f3 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -36,6 +36,7 @@ describe("rebuild gateway drift preflight", () => { let checkAgentVersionSpy: MockInstance; let detectPreflightIssueSpy: MockInstance; let captureOpenshellSpy: MockInstance; + let runOpenshellSpy: MockInstance; let printIssueSpy: MockInstance; let recoverNamedGatewayRuntimeSpy: MockInstance; @@ -66,6 +67,9 @@ describe("rebuild gateway drift preflight", () => { captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") .mockReturnValue({ status: 0, output: "alpha Ready" }); + runOpenshellSpy = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockReturnValue({ status: 0, output: "" } as never); recoverNamedGatewayRuntimeSpy = vi .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") .mockResolvedValue({ recovered: true }); @@ -74,6 +78,7 @@ describe("rebuild gateway drift preflight", () => { detectPreflightIssueSpy, vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), captureOpenshellSpy, + runOpenshellSpy, recoverNamedGatewayRuntimeSpy, printIssueSpy, vi.spyOn(registry, "getSandbox").mockReturnValue({ @@ -151,13 +156,9 @@ describe("rebuild gateway drift preflight", () => { // preserved registry metadata. Stub the destructive steps + recreate handoff // so the path stays hermetic, and assert the recreate failure surfaces the // stale-recovery message instead of "not running". - const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); const destroy = requireDist("../../../../dist/lib/actions/sandbox/destroy.js"); const onboardMod = requireDist("../../../../dist/lib/onboard.js"); spies.push( - vi - .spyOn(openshellRuntime, "runOpenshell") - .mockReturnValue({ status: 0, output: "" } as never), vi.spyOn(destroy, "removeSandboxRegistryEntry").mockImplementation(() => undefined), vi.spyOn(onboardMod, "onboard").mockRejectedValue(new Error("recreate-stub")), ); @@ -167,12 +168,127 @@ describe("rebuild gateway drift preflight", () => { ); expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], + gatewayName: "nemoclaw", + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], }); // The liveness query ran twice (initial failure + post-recovery retry). expect(listCalls).toBe(2); }); + it("recovers the persisted non-default gateway when the sandbox is bound to nemoclaw-", async () => { + detectPreflightIssueSpy.mockReturnValue(null); + // Reseed the sandbox lookup to expose a non-default gateway binding + // (gatewayPort=12345 → gateway name `nemoclaw-12345`). The stale-recovery + // path must address that gateway, not the default `nemoclaw`, otherwise a + // sandbox onboarded against `NEMOCLAW_GATEWAY_PORT=12345` would try to + // recover the wrong (and possibly nonexistent) default gateway. + for (const spy of spies) spy.mockRestore(); + spies.length = 0; + const gatewayDrift = requireDist("../../../../dist/lib/adapters/openshell/gateway-drift.js"); + const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); + const gatewayRuntime = requireDist("../../../../dist/lib/gateway-runtime-action.js"); + const registry = requireDist("../../../../dist/lib/state/registry.js"); + const resolve = requireDist("../../../../dist/lib/adapters/openshell/resolve.js"); + const sandboxSession = requireDist("../../../../dist/lib/state/sandbox-session.js"); + const onboardSession = requireDist("../../../../dist/lib/state/onboard-session.js"); + const sandboxVersion = requireDist("../../../../dist/lib/sandbox/version.js"); + const agentRuntime = requireDist("../../../../dist/lib/agent/runtime.js"); + + let listCalls = 0; + detectPreflightIssueSpy = vi + .spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue") + .mockReturnValue(null); + captureOpenshellSpy = vi.spyOn(openshellRuntime, "captureOpenshell").mockImplementation((( + args: string[], + ) => { + if (args[0] === "sandbox" && args[1] === "list") { + listCalls += 1; + return listCalls === 1 + ? { status: 1, output: "client error (Connect): Connection refused" } + : { status: 0, output: "beta Ready" }; + } + if (args[0] === "status") { + return { + status: 0, + output: "Server Status\n\n Gateway: nemoclaw-12345\n Status: Connected\n", + }; + } + if (args[0] === "gateway" && args[1] === "info") { + return { status: 0, output: "Gateway Info\n\nGateway: nemoclaw-12345\n" }; + } + if (args[0] === "sandbox" && args[1] === "get") { + return { status: 1, output: "Error: × Not Found: sandbox not found" }; + } + return { status: 0, output: "" }; + }) as never); + runOpenshellSpy = vi + .spyOn(openshellRuntime, "runOpenshell") + .mockReturnValue({ status: 0, output: "" } as never); + recoverNamedGatewayRuntimeSpy = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ recovered: true }); + checkAgentVersionSpy = vi + .spyOn(sandboxVersion, "checkAgentVersion") + .mockReturnValue({ expectedVersion: "0.1.0", sandboxVersion: "0.0.1" } as never); + printIssueSpy = vi + .spyOn(gatewayDrift, "printOpenShellStateRpcIssue") + .mockImplementation(() => undefined); + + const destroy = requireDist("../../../../dist/lib/actions/sandbox/destroy.js"); + const onboardMod = requireDist("../../../../dist/lib/onboard.js"); + spies.push( + detectPreflightIssueSpy, + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), + captureOpenshellSpy, + runOpenshellSpy, + recoverNamedGatewayRuntimeSpy, + printIssueSpy, + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + provider: "ollama-local", + model: "nvidia/nemotron", + policies: [], + nimContainer: null, + agent: null, + gatewayName: "nemoclaw-12345", + gatewayPort: 12345, + } as never), + vi.spyOn(resolve, "resolveOpenshell").mockReturnValue(null), + vi.spyOn(sandboxSession, "getActiveSandboxSessions").mockReturnValue({ + detected: false, + sessions: [], + }), + vi.spyOn(onboardSession, "loadSession").mockReturnValue(null), + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null), + vi.spyOn(agentRuntime, "getAgentDisplayName").mockReturnValue("OpenClaw"), + checkAgentVersionSpy, + vi.spyOn(destroy, "removeSandboxRegistryEntry").mockImplementation(() => undefined), + vi.spyOn(onboardMod, "onboard").mockRejectedValue(new Error("recreate-stub")), + ); + + ({ rebuildSandbox } = requireDist("../../../../dist/lib/actions/sandbox/rebuild.js")); + + await expect(rebuildSandbox("alpha", ["--yes"], { throwOnError: true })).rejects.toThrow( + /stale-sandbox recovery/, + ); + + expect(recoverNamedGatewayRuntimeSpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-12345", + recoverableStates: [ + "missing_named", + "named_unhealthy", + "named_unreachable", + "connected_other", + ], + }); + expect(listCalls).toBe(2); + }); + it("does not recover generic sandbox list failures", async () => { detectPreflightIssueSpy.mockReturnValue(null); captureOpenshellSpy.mockReturnValue({ status: 1, output: "unknown option: sandbox list" }); diff --git a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts index 4be4491c41f..a930884bd67 100644 --- a/src/lib/actions/sandbox/rebuild-shields-finally.test.ts +++ b/src/lib/actions/sandbox/rebuild-shields-finally.test.ts @@ -17,6 +17,7 @@ describe("rebuild shields relock guard", () => { let errorSpy: MockInstance; let logSpy: MockInstance; let relockSpy: MockInstance; + let sandboxListRecoverySpy: MockInstance; const rebuildWindow = { relocked: false, wasLocked: true }; beforeEach(() => { @@ -47,13 +48,15 @@ describe("rebuild shields relock guard", () => { return true; }); + sandboxListRecoverySpy = vi.spyOn(sandboxList, "captureSandboxListWithGatewayRecovery"); + spies.push( vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null), vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null), vi .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") .mockResolvedValue({ recovered: false }), - vi.spyOn(sandboxList, "captureSandboxListWithGatewayRecovery").mockResolvedValue({ + sandboxListRecoverySpy.mockResolvedValue({ result: { status: 0, output: "alpha Ready" }, }), vi.spyOn(resolve, "resolveOpenshell").mockReturnValue(null), @@ -67,6 +70,8 @@ describe("rebuild shields relock guard", () => { policies: [], agent: null, nimContainer: null, + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, } as never), vi.spyOn(sandboxSession, "getActiveSandboxSessions").mockReturnValue({ detected: false, @@ -99,6 +104,7 @@ describe("rebuild shields relock guard", () => { ); expect(relockSpy).toHaveBeenCalledWith("alpha", rebuildWindow, true, expect.any(String)); + expect(sandboxListRecoverySpy).toHaveBeenCalledWith({ gatewayName: "nemoclaw-8090" }); expect(rebuildWindow.relocked).toBe(true); }); }); diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index e2c1daaeff2..4261122a752 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -3,6 +3,7 @@ import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import { normalizeRebuildSandboxOptions, type RebuildSandboxOptions, @@ -543,8 +544,11 @@ export async function rebuildSandbox( } // Step 1: Ensure sandbox is live for backup - log("Checking sandbox liveness: openshell sandbox list"); - const liveRecovery = await captureSandboxListWithGatewayRecovery(); + const recordedGateway = resolveSandboxGatewayName(sb); + log(`Checking sandbox liveness on ${recordedGateway}: openshell sandbox list`); + const liveRecovery = await captureSandboxListWithGatewayRecovery({ + gatewayName: recordedGateway, + }); const isLive = liveRecovery.result; log( `openshell sandbox list exit=${isLive.status}, output=${(isLive.output || "").substring(0, 200)}`, @@ -581,49 +585,9 @@ export async function rebuildSandbox( // customPolicies, every field) is silently dropped or mutated (#4497). let staleRegistrySnapshot: ReturnType | null = null; if (!liveNames.has(sandboxName)) { - // The default-gateway liveness checks below can only authoritatively reason - // about the default `nemoclaw` gateway. A sandbox created on a non-default - // per-port gateway (#4645, e.g. `nemoclaw-9000`) that is simply not the - // active gateway would look absent here, and recreating-from-scratch would - // orphan its live workspace. Refuse the destructive path in that case and - // point the operator at the sandbox's own gateway. (If that gateway were - // active, the sandbox would have appeared in the list above.) - const recordedGateway = - typeof sb.gatewayName === "string" && sb.gatewayName ? sb.gatewayName : "nemoclaw"; - if (recordedGateway !== "nemoclaw") { - console.error( - ` Sandbox '${sandboxName}' is registered on the '${recordedGateway}' OpenShell gateway, which is not the active gateway.`, - ); - console.error( - " Its live state could not be confirmed — your local registry entry has been preserved.", - ); - console.error(" Select that gateway and retry:"); - console.error(` openshell gateway select ${recordedGateway}`); - console.error(` Then re-run: ${CLI_NAME} ${sandboxName} rebuild --yes`); - bail( - `Sandbox '${sandboxName}' is on the non-default gateway '${recordedGateway}'; select it before rebuilding.`, - ); - return; - } - - // The active-gateway `sandbox list` does not show this sandbox. That alone - // is NOT proof it is gone: a different active gateway (multi-gateway setups, - // #4645) would hide a live NemoClaw sandbox, and `sandbox list` can omit a - // sandbox that `sandbox get` still resolves. Recreating on that false - // signal would destroy live workspace state. So confirm authoritatively - // against the NAMED NemoClaw gateway: getReconciledSandboxGatewayState runs - // `sandbox get`, re-selecting/recovering nemoclaw as needed, and only - // reports "missing" once the named gateway is confirmed healthy and the - // sandbox is genuinely absent. const reconciled = await getReconciledSandboxGatewayState(sandboxName); if (reconciled.state === "present") { - // `sandbox get` resolved the sandbox, but that query ran against whatever - // gateway is currently active. Only trust it as live when the named - // nemoclaw gateway is the active healthy one — otherwise a foreign active - // gateway with a same-named sandbox (or a list/get inconsistency) could - // send the destructive backup/delete below at the wrong sandbox. If a - // foreign gateway is active, abort with guidance instead. - const lifecycle = getNamedGatewayLifecycleState(); + const lifecycle = getNamedGatewayLifecycleState(recordedGateway); if (lifecycle.state !== "healthy_named") { printWrongGatewayActiveGuidance( sandboxName, @@ -632,7 +596,7 @@ export async function rebuildSandbox( "rebuild --yes", ); bail( - `Could not confirm '${sandboxName}' against the NemoClaw gateway (gateway '${lifecycle.activeGateway ?? "unknown"}' is active).`, + `Could not confirm '${sandboxName}' against gateway '${recordedGateway}' (gateway '${lifecycle.activeGateway ?? "unknown"}' is active).`, ); return; } @@ -671,7 +635,7 @@ export async function rebuildSandbox( ); } else { console.error( - ` Sandbox '${sandboxName}' is not visible on the NemoClaw gateway and its live state could not be confirmed.`, + ` Sandbox '${sandboxName}' is not visible on gateway '${recordedGateway}' and its live state could not be confirmed.`, ); console.error(" Your local registry entry has been preserved — nothing was removed."); printGatewayLifecycleHint(reconciled.output || "", sandboxName, console.error); diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts new file mode 100644 index 00000000000..0fead878689 --- /dev/null +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.test.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; + +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +const requireDist = createRequire(import.meta.url); + +type RoutingModule = typeof import("../../../../dist/lib/actions/sandbox/sandbox-gateway-routing"); + +describe("sandbox gateway routing helpers", () => { + let routing: RoutingModule; + let spies: MockInstance[]; + let getSandboxSpy: MockInstance; + let captureOpenshellSpy: MockInstance; + let runOpenshellSpy: MockInstance; + + beforeEach(() => { + const openshellRuntime = requireDist("../../../../dist/lib/adapters/openshell/runtime.js"); + const registry = requireDist("../../../../dist/lib/state/registry.js"); + + spies = []; + getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "alpha", + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + openshellDriver: "vm", + }); + captureOpenshellSpy = vi + .spyOn(openshellRuntime, "captureOpenshell") + .mockImplementation((args: unknown) => { + const argv = Array.isArray(args) ? args : []; + return { + status: 0, + output: + argv[0] === "status" + ? "Server Status\n\nGateway: nemoclaw-8090\nStatus: Connected\n" + : "Gateway Info\n\nGateway: nemoclaw-8090\nGateway endpoint: https://127.0.0.1:8090/\n", + } as never; + }); + runOpenshellSpy = vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ + status: 0, + } as never); + spies.push(getSandboxSpy, captureOpenshellSpy, runOpenshellSpy); + + routing = requireDist("../../../../dist/lib/actions/sandbox/sandbox-gateway-routing.js"); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + }); + + it("uses the persisted gateway name for metadata health probes", () => { + expect(routing.probeGatewayRunning("alpha")).toBe(true); + + expect(captureOpenshellSpy).toHaveBeenCalledWith( + ["gateway", "info", "-g", "nemoclaw-8090"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("selects the persisted gateway before sandbox-scoped OpenShell commands", () => { + routing.selectSandboxGatewayIfRegistered("alpha"); + + expect(runOpenshellSpy).toHaveBeenCalledWith( + ["gateway", "select", "nemoclaw-8090"], + expect.objectContaining({ ignoreError: true }), + ); + }); +}); diff --git a/src/lib/actions/sandbox/sandbox-gateway-routing.ts b/src/lib/actions/sandbox/sandbox-gateway-routing.ts new file mode 100644 index 00000000000..22bf2b3f683 --- /dev/null +++ b/src/lib/actions/sandbox/sandbox-gateway-routing.ts @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** + * Sandbox-scoped gateway routing helpers shared across sandbox lifecycle + * commands (snapshot, restore, ...) so the snapshot monolith does not have to + * carry them. Each helper resolves the OpenShell gateway from the sandbox's + * persisted registry entry — never the process-level `NEMOCLAW_GATEWAY_PORT` + * — so a sandbox registered on a non-default per-port gateway is addressed + * correctly. + */ + +import { dockerInspect } from "../../adapters/docker"; +import { captureOpenshell, runOpenshell } from "../../adapters/openshell/runtime"; +import { + OPENSHELL_OPERATION_TIMEOUT_MS, + OPENSHELL_PROBE_TIMEOUT_MS, +} from "../../adapters/openshell/timeouts"; +import { GATEWAY_PORT } from "../../core/ports"; +import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; +import { isGatewayHealthy } from "../../state/gateway"; +import * as registry from "../../state/registry"; + +/** + * Docker/VM-driver sandboxes do not expose the legacy cluster container, so + * verify gateway health through OpenShell metadata instead. + */ +export function probeGatewayMetadataHealth(gatewayName: string): boolean { + const status = captureOpenshell(["status"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + const activeGatewayInfo = captureOpenshell(["gateway", "info"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + return isGatewayHealthy( + status.output || "", + namedGatewayInfo.output || "", + activeGatewayInfo.output || "", + gatewayName, + ); +} + +export function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { + return driver === "docker" || driver === "vm"; +} + +/** + * Probe whether the OpenShell gateway the named sandbox lives on is running. + * Resolves the gateway from the sandbox's persisted registry entry — never + * the process-level `GATEWAY_PORT` — so the probe targets the gateway the + * sandbox was actually onboarded against. + */ +export function probeGatewayRunning(sandboxName?: string): boolean { + const entry = sandboxName ? registry.getSandbox(sandboxName) : null; + const gatewayName = entry ? resolveSandboxGatewayName(entry) : resolveGatewayName(GATEWAY_PORT); + if (usesGatewayMetadataProbe(entry?.openshellDriver)) { + return probeGatewayMetadataHealth(gatewayName); + } + const container = `openshell-cluster-${gatewayName}`; + const result = dockerInspect( + ["--type", "container", "--format", "{{.State.Running}}", container], + { ignoreError: true, suppressOutput: true }, + ); + return result.status === 0 && String(result.stdout || "").trim() === "true"; +} + +/** + * Switch the active OpenShell gateway to the one this sandbox is registered on + * so downstream unscoped `sandbox list` / `sandbox get` queries target the + * right gateway. + */ +export function selectSandboxGatewayIfRegistered(sandboxName: string): boolean { + const entry = registry.getSandbox(sandboxName); + if (!entry) return true; + const target = resolveSandboxGatewayName(entry); + const result = runOpenshell(["gateway", "select", target], { + ignoreError: true, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + return result.status === 0; +} diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index a00813212c4..6a1c3931215 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -3,7 +3,7 @@ import fs from "node:fs"; import path from "node:path"; -import { dockerCapture, dockerInspect } from "../../adapters/docker"; +import { dockerCapture } from "../../adapters/docker"; import { captureOpenshell, getOpenshellBinary, @@ -12,15 +12,20 @@ import { import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; +import { resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as policies from "../../policy"; import { ROOT, run, shellQuote, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import * as shields from "../../shields"; -import { isGatewayHealthy } from "../../state/gateway"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import * as sandboxState from "../../state/sandbox"; import { cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntry } from "./destroy"; +import { + probeGatewayRunning, + selectSandboxGatewayIfRegistered, + usesGatewayMetadataProbe, +} from "./sandbox-gateway-routing"; const useColor = !process.env.NO_COLOR && !!process.stdout.isTTY; const trueColor = @@ -30,8 +35,6 @@ const B = useColor ? "\x1b[1m" : ""; const D = useColor ? "\x1b[2m" : ""; const R = useColor ? "\x1b[0m" : ""; -const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; - export type SnapshotRequest = | { kind: "help" } | { kind: "create"; name?: string } @@ -116,7 +119,10 @@ function resolveSrcPodImage( return registeredImage ?? null; } - const gatewayContainer = `openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`; + const srcGatewayName = resolveSandboxGatewayName( + srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, + ); + const gatewayContainer = `openshell-cluster-${srcGatewayName}`; try { const output = dockerCapture( [ @@ -207,7 +213,10 @@ async function autoCreateSandboxFromSource( const dnsScript = path.join(ROOT, "scripts", "setup-dns-proxy.sh"); const srcDriver = (srcEntry as { openshellDriver?: string | null }).openshellDriver; if (srcDriver === "kubernetes" && fs.existsSync(dnsScript)) { - run(["bash", dnsScript, NEMOCLAW_GATEWAY_NAME, dstName], { ignoreError: true }); + const srcGatewayName = resolveSandboxGatewayName( + srcEntry as { gatewayName?: string | null; gatewayPort?: number | null }, + ); + run(["bash", dnsScript, srcGatewayName, dstName], { ignoreError: true }); } // Register dst in the NemoClaw registry, cloning most fields from src. @@ -292,40 +301,35 @@ function deleteSandboxForRestore(name: string): void { console.log(` ${G}\u2713${R} '${name}' deleted`); } -// Docker/VM-driver sandboxes do not expose the legacy cluster container, so -// verify gateway health through OpenShell metadata instead. -function probeGatewayMetadataHealth(): boolean { - const status = captureOpenshell(["status"], { ignoreError: true, timeout: 10000 }); - const namedGatewayInfo = captureOpenshell(["gateway", "info", "-g", NEMOCLAW_GATEWAY_NAME], { - ignoreError: true, - timeout: 10000, - }); - const activeGatewayInfo = captureOpenshell(["gateway", "info"], { - ignoreError: true, - timeout: 10000, - }); - return isGatewayHealthy( - status.output || "", - namedGatewayInfo.output || "", - activeGatewayInfo.output || "", - ); +function listLiveSandboxesOnSandboxGateway(sandboxName: string): Set | null { + if (!selectSandboxGatewayIfRegistered(sandboxName)) return null; + if (!probeGatewayRunning(sandboxName)) return null; + const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); + if (isLive.status !== 0) return null; + return parseLiveSandboxNames(isLive.output || ""); } -function usesGatewayMetadataProbe(driver: string | null | undefined): boolean { - return driver === "docker" || driver === "vm"; +function requireLiveSandboxesOnSandboxGateway(sandboxName: string, error: string): Set { + const liveNames = listLiveSandboxesOnSandboxGateway(sandboxName); + if (!liveNames) { + console.error(error); + snapshotExit(1); + } + return liveNames; } -function probeGatewayRunning(sandboxName?: string): boolean { - const entry = sandboxName ? registry.getSandbox(sandboxName) : null; - if (usesGatewayMetadataProbe(entry?.openshellDriver)) { - return probeGatewayMetadataHealth(); - } - const container = `openshell-cluster-${NEMOCLAW_GATEWAY_NAME}`; - const result = dockerInspect( - ["--type", "container", "--format", "{{.State.Running}}", container], - { ignoreError: true, suppressOutput: true }, +function verifyRestoreDestinationOnOwnGateway(targetSandbox: string): void { + const liveNames = requireLiveSandboxesOnSandboxGateway( + targetSandbox, + ` Cannot verify destination sandbox '${targetSandbox}' on its registered gateway. Aborting restore.`, ); - return result.status === 0 && String(result.stdout || "").trim() === "true"; + if (!liveNames.has(targetSandbox)) { + console.error( + ` Destination sandbox '${targetSandbox}' is registered locally, but is not present on its registered gateway.`, + ); + console.error(" Aborting restore before deleting or overwriting local sandbox metadata."); + snapshotExit(1); + } } function isSnapshotCreationAllowedByShields(sandboxName: string): boolean { @@ -346,12 +350,15 @@ export async function runSandboxSnapshot( ) { switch (request.kind) { case "create": { - if (!probeGatewayRunning(sandboxName)) { - console.error(" Failed to query live sandbox state from OpenShell."); - snapshotExit(1); - } - const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); - const liveNames = parseLiveSandboxNames(isLive.output || ""); + // Select the sandbox's gateway before the health probe and `sandbox list` + // — Docker/VM-driver health and the sandbox listing both require the + // sandbox's gateway to be the active one, otherwise a sandbox registered + // on a non-default `NEMOCLAW_GATEWAY_PORT` fails health-check before the + // subsequent list ever runs. + const liveNames = requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to query live sandbox state from OpenShell.", + ); if (!liveNames.has(sandboxName)) { console.error(` Sandbox '${sandboxName}' is not running. Cannot create snapshot.`); snapshotExit(1); @@ -412,14 +419,13 @@ export async function runSandboxSnapshot( const target = request.to ?? sandboxName; const targetSandbox = target === sandboxName ? sandboxName : validateName(target, "target sandbox name"); - if (!probeGatewayRunning(sandboxName)) { - console.error(" Failed to query live sandbox state from OpenShell."); - snapshotExit(1); - } - const isLive = captureOpenshell(["sandbox", "list"], { ignoreError: true }); - const liveNames = parseLiveSandboxNames(isLive.output || ""); + const sourceLiveNames = requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to query live sandbox state from OpenShell.", + ); const isCrossSandboxRestore = targetSandbox !== sandboxName; - const targetExists = liveNames.has(targetSandbox); + const targetEntry = isCrossSandboxRestore ? registry.getSandbox(targetSandbox) : null; + const targetExists = sourceLiveNames.has(targetSandbox) || Boolean(targetEntry); // #3756 P1 preflight: resolve the snapshot selector AND the source pod // image before any destructive action. A bad selector, missing snapshot, @@ -482,7 +488,7 @@ export async function runSandboxSnapshot( // we must be able to clone the source's running pod image. Resolve it // upfront so a missing source / unresolvable image cannot delete the // destination first (#3756 P1). - if (!liveNames.has(sandboxName)) { + if (!sourceLiveNames.has(sandboxName)) { if (targetExists) { console.error( ` Cannot recreate '${targetSandbox}' from snapshot: source '${sandboxName}' not found.`, @@ -520,7 +526,14 @@ export async function runSandboxSnapshot( snapshotExit(1); } } + if (targetEntry) { + verifyRestoreDestinationOnOwnGateway(targetSandbox); + } deleteSandboxForRestore(targetSandbox); + requireLiveSandboxesOnSandboxGateway( + sandboxName, + " Failed to re-select source sandbox gateway after deleting destination.", + ); } await autoCreateSandboxFromSource(sandboxName, targetSandbox, srcEntry); } diff --git a/src/lib/actions/sandbox/status.ts b/src/lib/actions/sandbox/status.ts index 9d056ebaa52..124f7dde50a 100644 --- a/src/lib/actions/sandbox/status.ts +++ b/src/lib/actions/sandbox/status.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { printOpenShellStateRpcIssue } from "../../adapters/openshell/gateway-drift"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { resolveOpenshell } from "../../adapters/openshell/resolve"; import * as agentRuntime from "../../agent/runtime"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; @@ -384,7 +385,7 @@ export async function showSandboxStatus(sandboxName: string): Promise { console.log(lookup.output); } console.log( - " Retry `openshell gateway start --name nemoclaw` and verify `openshell status` is healthy before reconnecting.", + ` Retry \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` and verify \`openshell status\` is healthy before reconnecting.`, ); console.log( " If the gateway never becomes healthy, rebuild the gateway and then recreate the affected sandbox.", @@ -400,7 +401,7 @@ export async function showSandboxStatus(sandboxName: string): Promise { console.log(lookup.output); } console.log( - " Start the gateway again with `openshell gateway start --name nemoclaw` before retrying.", + ` Start the gateway again with \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` before retrying.`, ); console.log( " If the gateway had to be rebuilt from scratch, recreate the affected sandbox afterward.", diff --git a/src/lib/adapters/docker/index.test.ts b/src/lib/adapters/docker/index.test.ts index 4f64186a14c..6753a5c4916 100644 --- a/src/lib/adapters/docker/index.test.ts +++ b/src/lib/adapters/docker/index.test.ts @@ -154,6 +154,7 @@ describe("docker helpers", () => { "openshell-cluster-nemoclaw", "openshell-cluster-nemoclaw-cache", "openshell-cluster-nemoclaw-2", + "openshell-cluster-nemoclaw2", "not-a-match", "", ].join("\n"), @@ -168,6 +169,23 @@ describe("docker helpers", () => { ]); }); + it("does not match a longer per-port gateway name with the same prefix", () => { + runCaptureMock.mockReturnValue( + [ + "openshell-cluster-nemoclaw-8081", + "openshell-cluster-nemoclaw-8081-cache", + "openshell-cluster-nemoclaw-80810", + ].join("\n"), + ); + + const names = dockerListVolumesByPrefix("openshell-cluster-nemoclaw-8081"); + + expect(names).toEqual([ + "openshell-cluster-nemoclaw-8081", + "openshell-cluster-nemoclaw-8081-cache", + ]); + }); + it("removes only volumes returned by the prefix probe", () => { runCaptureMock.mockReturnValue( "openshell-cluster-nemoclaw\nopenshell-cluster-nemoclaw-cache\n", diff --git a/src/lib/adapters/docker/volume.ts b/src/lib/adapters/docker/volume.ts index f1e51dac248..aa9ee9fbe57 100644 --- a/src/lib/adapters/docker/volume.ts +++ b/src/lib/adapters/docker/volume.ts @@ -33,7 +33,9 @@ export function dockerListVolumesByPrefix( ignoreError: true, ...opts, }); - return splitNonEmptyLines(output).filter((name) => name.startsWith(normalized)); + return splitNonEmptyLines(output).filter( + (name) => name === normalized || name.startsWith(`${normalized}-`), + ); } export function dockerRemoveVolumes( diff --git a/src/lib/gateway-runtime-action.test.ts b/src/lib/gateway-runtime-action.test.ts new file mode 100644 index 00000000000..933e8016865 --- /dev/null +++ b/src/lib/gateway-runtime-action.test.ts @@ -0,0 +1,156 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createRequire } from "node:module"; + +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +type GatewayRuntimeModule = typeof import("../../dist/lib/gateway-runtime-action"); + +const requireDist = createRequire(import.meta.url); +const gatewayRuntimeModulePath = "../../dist/lib/gateway-runtime-action.js"; + +describe("gateway-runtime-action per-sandbox gateway routing", () => { + let gatewayRuntime: GatewayRuntimeModule; + let captureSpy: MockInstance; + let runSpy: MockInstance; + let startGatewaySpy: MockInstance; + let spies: MockInstance[]; + + beforeEach(() => { + spies = []; + delete require.cache[requireDist.resolve(gatewayRuntimeModulePath)]; + const openshellRuntime = requireDist("../../dist/lib/adapters/openshell/runtime.js"); + captureSpy = vi.spyOn(openshellRuntime, "captureOpenshell"); + runSpy = vi.spyOn(openshellRuntime, "runOpenshell"); + spies.push(captureSpy, runSpy); + + // The recovery path also pokes onboard.startGatewayForRecovery via lazy + // require(); stub it so the tests do not pull onboard's runtime in. + const onboard = requireDist("../../dist/lib/onboard.js"); + startGatewaySpy = vi + .spyOn(onboard, "startGatewayForRecovery") + .mockResolvedValue(undefined as never); + spies.push(startGatewaySpy); + + gatewayRuntime = requireDist(gatewayRuntimeModulePath); + }); + + afterEach(() => { + for (const spy of spies) spy.mockRestore(); + delete process.env.OPENSHELL_GATEWAY; + delete require.cache[requireDist.resolve(gatewayRuntimeModulePath)]; + }); + + describe("getNamedGatewayLifecycleState", () => { + it("queries the bare 'nemoclaw' name by default", () => { + captureSpy.mockReturnValue({ status: 0, output: "Status: Connected\nGateway: nemoclaw\n" }); + + gatewayRuntime.getNamedGatewayLifecycleState(); + + const calls = captureSpy.mock.calls.map(([args]) => args); + expect(calls).toContainEqual(["gateway", "info", "-g", "nemoclaw"]); + }); + + it("queries the per-port gateway when a name is supplied", () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }); + + const result = gatewayRuntime.getNamedGatewayLifecycleState("nemoclaw-8090"); + + const calls = captureSpy.mock.calls.map(([args]) => args); + expect(calls).toContainEqual(["gateway", "info", "-g", "nemoclaw-8090"]); + expect(result.state).toBe("healthy_named"); + expect(result.activeGateway).toBe("nemoclaw-8090"); + }); + + it("treats a non-default gateway as 'connected_other' when the active gateway differs", () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw\n", + }); + + const result = gatewayRuntime.getNamedGatewayLifecycleState("nemoclaw-8090"); + + expect(result.state).toBe("connected_other"); + expect(result.activeGateway).toBe("nemoclaw"); + }); + }); + + describe("recoverNamedGatewayRuntime", () => { + it("selects the supplied gateway name on the recovery path", async () => { + captureSpy + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }) + .mockReturnValueOnce({ + status: 0, + output: "Gateway: nemoclaw-8090\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw-8090", + }); + + const selectCalls = runSpy.mock.calls + .map(([args]) => args) + .filter((args: string[]) => args[0] === "gateway" && args[1] === "select"); + expect(selectCalls).toContainEqual(["gateway", "select", "nemoclaw-8090"]); + expect(selectCalls.every((args: string[]) => args[2] === "nemoclaw-8090")).toBe(true); + expect(result.recovered).toBe(true); + expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw-8090"); + }); + + it("never selects the bare default gateway when a per-port name is supplied", async () => { + captureSpy.mockReturnValue({ + status: 0, + output: "Status: Disconnected\nGateway: other\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + await gatewayRuntime.recoverNamedGatewayRuntime({ gatewayName: "nemoclaw-8090" }); + + const selectCalls = runSpy.mock.calls + .map(([args]) => args) + .filter((args: string[]) => args[0] === "gateway" && args[1] === "select"); + for (const args of selectCalls) { + expect(args[2]).toBe("nemoclaw-8090"); + } + }); + + it("starts recovery with the supplied gateway name and derived port", async () => { + captureSpy + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ status: 0, output: "Status: Disconnected\nGateway: nemoclaw\n" }) + .mockReturnValueOnce({ status: 0, output: "" }) + .mockReturnValueOnce({ + status: 0, + output: "Status: Connected\nGateway: nemoclaw-8090\n", + }) + .mockReturnValueOnce({ + status: 0, + output: "Gateway: nemoclaw-8090\n", + }); + runSpy.mockReturnValue({ status: 0 } as never); + + const result = await gatewayRuntime.recoverNamedGatewayRuntime({ + gatewayName: "nemoclaw-8090", + }); + + expect(startGatewaySpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + }); + expect(result.recovered).toBe(true); + expect(result.via).toBe("start"); + expect(process.env.OPENSHELL_GATEWAY).toBe("nemoclaw-8090"); + }); + }); +}); diff --git a/src/lib/gateway-runtime-action.ts b/src/lib/gateway-runtime-action.ts index 257888436f0..d6d34615abe 100644 --- a/src/lib/gateway-runtime-action.ts +++ b/src/lib/gateway-runtime-action.ts @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 const { startGatewayForRecovery } = require("./onboard") as { - startGatewayForRecovery: () => Promise; + startGatewayForRecovery: (options?: { + gatewayName?: string; + gatewayPort?: number; + }) => Promise; }; import { OPENSHELL_OPERATION_TIMEOUT_MS, @@ -10,9 +13,11 @@ import { } from "./adapters/openshell/timeouts"; import { stripAnsi } from "./adapters/openshell/client"; import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; +import { resolveGatewayName, resolveGatewayPortFromName } from "./onboard/gateway-binding"; +import { GATEWAY_PORT } from "./core/ports"; -function hasNamedGateway(output = ""): boolean { - return stripAnsi(output).includes("Gateway: nemoclaw"); +function hasNamedGateway(output = "", gatewayName = "nemoclaw"): boolean { + return stripAnsi(output).includes(`Gateway: ${gatewayName}`); } function getActiveGatewayName(output = ""): string | null { @@ -20,19 +25,21 @@ function getActiveGatewayName(output = ""): string | null { return match ? match[1].trim() : null; } -export function getNamedGatewayLifecycleState() { +export function getNamedGatewayLifecycleState( + gatewayName: string = resolveGatewayName(GATEWAY_PORT), +) { const status = captureOpenshell(["status"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }); - const gatewayInfo = captureOpenshell(["gateway", "info", "-g", "nemoclaw"], { + const gatewayInfo = captureOpenshell(["gateway", "info", "-g", gatewayName], { timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); const cleanStatus = stripAnsi(status.output); const activeGateway = getActiveGatewayName(status.output); const connected = /^\s*Status:\s*Connected\b/im.test(cleanStatus); - const named = hasNamedGateway(gatewayInfo.output); + const named = hasNamedGateway(gatewayInfo.output, gatewayName); const refusing = /Connection refused|client error \(Connect\)|tcp connect error/i.test( cleanStatus, ); - if (connected && activeGateway === "nemoclaw" && named) { + if (connected && activeGateway === gatewayName && named) { return { state: "healthy_named", status: status.output, @@ -40,7 +47,7 @@ export function getNamedGatewayLifecycleState() { activeGateway, }; } - if (activeGateway === "nemoclaw" && named && refusing) { + if (activeGateway === gatewayName && named && refusing) { return { state: "named_unreachable", status: status.output, @@ -48,7 +55,7 @@ export function getNamedGatewayLifecycleState() { activeGateway, }; } - if (activeGateway === "nemoclaw" && named) { + if (activeGateway === gatewayName && named) { return { state: "named_unhealthy", status: status.output, @@ -76,10 +83,12 @@ type NamedGatewayLifecycleStateName = ReturnType( options.recoverableStates ?? [ "missing_named", @@ -88,7 +97,7 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun "connected_other", ], ); - const before = getNamedGatewayLifecycleState(); + const before = getNamedGatewayLifecycleState(gatewayName); if (before.state === "healthy_named") { return { recovered: true, before, after: before, attempted: false }; } @@ -96,13 +105,13 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun return { recovered: false, before, after: before, attempted: false }; } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - let after = getNamedGatewayLifecycleState(); + let after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "select" }; } @@ -114,18 +123,21 @@ export async function recoverNamedGatewayRuntime(options: RecoverNamedGatewayRun if (shouldStartGateway) { try { - await startGatewayForRecovery(); + await startGatewayForRecovery({ + gatewayName, + gatewayPort: resolveGatewayPortFromName(gatewayName) ?? undefined, + }); } catch { // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. } - runOpenshell(["gateway", "select", "nemoclaw"], { + runOpenshell(["gateway", "select", gatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - after = getNamedGatewayLifecycleState(); + after = getNamedGatewayLifecycleState(gatewayName); if (after.state === "healthy_named") { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.OPENSHELL_GATEWAY = gatewayName; return { recovered: true, before, after, attempted: true, via: "start" }; } } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 6fad74407e8..3ad2da4e3a1 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2326,8 +2326,14 @@ async function startGateway( return startGatewayWithOptions(_gpu, { exitOnFailure: true, gpuPassthrough }); } -async function startGatewayForRecovery(_gpu: ReturnType): Promise { - return startGatewayWithOptions(_gpu, { exitOnFailure: false }); +async function startGatewayForRecovery(options = {}): Promise { + return require("./onboard/gateway-recovery").startGatewayForRecovery(options, { + getGatewayStartEnv, + runCaptureOpenshell, + runOpenshell, + startGatewayWithOptions, + isLinuxDockerDriverGatewayEnabled, + }); } function getGatewayStartEnv(): Record { @@ -2347,17 +2353,7 @@ function getGatewayStartEnv(): Record { return gatewayEnv; } -/** - * Memoizes `applyOverlayfsAutoFix` per upstream image for the lifetime of - * the process. The expensive work (host assessment + image inspect / pull / - * build) only needs to happen once per onboard invocation; both - * `startGatewayWithOptions` and `recoverGatewayRuntime` go through - * `getGatewayStartEnv()`, and without this cache the recovery path would - * re-run the full assessment. - * - * Reset on a per-process basis only — env-var changes mid-process are - * not modelled here and shouldn't happen in the CLI's normal flow. - */ +/** Cache the overlayfs auto-fix result per upstream image for this onboard process. */ const overlayFixResultCache = new Map(); /** diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index 3833cde0516..4fd125c9469 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -20,7 +20,9 @@ import { BASE_GATEWAY_STATE_DIR_NAME, resolveGatewayCompatContainerName, resolveGatewayName, + resolveGatewayPortFromName, resolveGatewayStateDirName, + resolveSandboxGatewayName, } from "../../../dist/lib/onboard/gateway-binding"; describe("gateway-binding resolver (#4422)", () => { @@ -34,10 +36,18 @@ describe("gateway-binding resolver (#4422)", () => { it("suffixes the name, state dir, and compat container for a non-default port", () => { expect(resolveGatewayName(8081)).toBe("nemoclaw-8081"); + expect(resolveGatewayPortFromName("nemoclaw-8081")).toBe(8081); expect(resolveGatewayStateDirName(8081)).toBe("openshell-docker-gateway-8081"); expect(resolveGatewayCompatContainerName(8081)).toBe("nemoclaw-openshell-gateway-8081"); }); + it("rejects malformed gateway names when resolving a port", () => { + expect(resolveGatewayPortFromName("nemoclaw")).toBe(DEFAULT_GATEWAY_PORT); + expect(resolveGatewayPortFromName("nemoclaw-0")).toBeNull(); + expect(resolveGatewayPortFromName("nemoclaw-65536")).toBeNull(); + expect(resolveGatewayPortFromName("other-8081")).toBeNull(); + }); + it("derives distinct bindings for two different gateway ports", () => { const a = 8080; const b = 8081; @@ -47,6 +57,103 @@ describe("gateway-binding resolver (#4422)", () => { }); }); +describe("resolveSandboxGatewayName", () => { + it("returns the persisted gatewayName when present", () => { + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 9090 })).toBe( + "nemoclaw-9090", + ); + }); + + it("derives from gatewayPort when a valid persisted gatewayName conflicts", () => { + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw-9090", gatewayPort: 8081 })).toBe( + "nemoclaw-8081", + ); + }); + + it("derives the gateway name from gatewayPort when gatewayName is absent", () => { + expect(resolveSandboxGatewayName({ gatewayPort: 8081 })).toBe("nemoclaw-8081"); + expect(resolveSandboxGatewayName({ gatewayPort: 8080 })).toBe(BASE_GATEWAY_NAME); + }); + + it("falls back to the bare base name for legacy sandbox entries with neither field set", () => { + expect(resolveSandboxGatewayName({})).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName(null)).toBe(BASE_GATEWAY_NAME); + expect(resolveSandboxGatewayName(undefined)).toBe(BASE_GATEWAY_NAME); + }); + + it("ignores null persisted values and falls back through the resolution chain", () => { + expect(resolveSandboxGatewayName({ gatewayName: null, gatewayPort: 8081 })).toBe( + "nemoclaw-8081", + ); + expect(resolveSandboxGatewayName({ gatewayName: null, gatewayPort: null })).toBe( + BASE_GATEWAY_NAME, + ); + }); + + it("returns distinct names for sandboxes on different non-default ports", () => { + expect(resolveSandboxGatewayName({ gatewayPort: 8081 })).not.toBe( + resolveSandboxGatewayName({ gatewayPort: 8090 }), + ); + }); + + it("falls through to a valid port when only the persisted gatewayName is out-of-namespace", () => { + // A tampered name with a still-valid port resolves from the port so the + // operation lands on a real NemoClaw gateway rather than the tampered string. + expect(resolveSandboxGatewayName({ gatewayName: "rogue-gateway", gatewayPort: 8081 })).toBe( + "nemoclaw-8081", + ); + }); + + it("throws on an invalid persisted gatewayName when no valid port is present", () => { + // Refuse to silently rewrite destroy/snapshot to the default gateway when + // the persisted binding is present but unusable. + expect(() => resolveSandboxGatewayName({ gatewayName: "../etc/passwd" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw evil" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-0" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-65536" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + }); + + it("throws on an out-of-range or non-integer persisted gatewayPort", () => { + expect(() => resolveSandboxGatewayName({ gatewayPort: 0 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: -1 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: 65536 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: 8081.5 })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + expect(() => resolveSandboxGatewayName({ gatewayPort: Number.NaN })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + }); + + it("accepts the canonical bare base gateway name", () => { + expect(resolveSandboxGatewayName({ gatewayName: "nemoclaw" })).toBe(BASE_GATEWAY_NAME); + }); + + it("rejects the non-canonical default-port suffix form", () => { + // `nemoclaw-8080` matches the namespace regex but is not what + // resolveGatewayName(8080) emits (it emits the bare `nemoclaw`). A + // sandbox registered against the non-canonical form would target a + // gateway name that does not exist. + expect(() => resolveSandboxGatewayName({ gatewayName: "nemoclaw-8080" })).toThrow( + /Invalid persisted sandbox gateway binding/, + ); + }); +}); + describe("docker-driver compat container is gateway-port scoped (#4422)", () => { function withTempState( fn: (paths: { gatewayBin: string; sandboxBin: string; stateDir: string }) => T, diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index d726947b61d..016fc29d11c 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -10,7 +10,7 @@ * different `NEMOCLAW_GATEWAY_PORT` therefore reused the same named gateway, * the same runtime-marker state dir, and the same compat container — so * creating the second sandbox recreated/killed the first sandbox's gateway and - * overwrote its runtime marker (#4422). + * overwrote its runtime marker. * * These pure resolvers derive a stable per-port binding. The default port * keeps the original `nemoclaw` names verbatim so existing single-sandbox @@ -43,6 +43,104 @@ export function resolveGatewayName(port: number): string { return isDefaultGatewayPort(port) ? BASE_GATEWAY_NAME : `${BASE_GATEWAY_NAME}-${port}`; } +/** Resolve the gateway port encoded by a canonical NemoClaw gateway name. */ +export function resolveGatewayPortFromName(gatewayName: string): number | null { + if (gatewayName === BASE_GATEWAY_NAME) { + return DEFAULT_GATEWAY_PORT; + } + const match = gatewayName.match(new RegExp(`^${BASE_GATEWAY_NAME}-(\\d+)$`)); + if (!match) { + return null; + } + const port = Number(match[1]); + return isValidPersistedGatewayPort(port) && resolveGatewayName(port) === gatewayName + ? port + : null; +} + +/** + * Sandbox registry shape this resolver depends on. Kept structural to avoid + * a hard import from `state/registry` (which would pull in the whole + * registry module just to read two optional fields). + */ +export interface SandboxGatewayBinding { + gatewayName?: string | null; + gatewayPort?: number | null; +} + +/** + * Recognises a NemoClaw-namespaced gateway name. The persisted form is either + * the bare `nemoclaw` or the per-port `nemoclaw-` derivation — anything + * outside that namespace must not be trusted, since + * `resolveSandboxGatewayName` drives gateway select/info/recover/remove/ + * destroy and Docker volume targeting from the value. + */ +const VALID_GATEWAY_NAME_RE = + /^nemoclaw(-(?:[1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]))?$/; + +function isValidPersistedGatewayName(value: string): boolean { + if (!VALID_GATEWAY_NAME_RE.test(value)) return false; + // The regex permits `nemoclaw-` but that form is not the + // canonical name for the default port (the bare `BASE_GATEWAY_NAME` is). + // Reject it so a persisted `nemoclaw-8080` cannot drive lifecycle commands + // against a gateway name that does not actually exist in the registry. + return resolveGatewayPortFromName(value) !== null; +} + +function isValidPersistedGatewayPort(value: number): boolean { + return Number.isInteger(value) && value >= 1 && value <= 65535; +} + +/** + * Resolve the OpenShell gateway name a given sandbox should be addressed by. + * Sandbox-scoped lifecycle commands (`connect`, `destroy`, `doctor`, + * `snapshot`, gateway-state probes) must call this rather than hardcoding + * the bare `nemoclaw` literal — a sandbox onboarded with a non-default + * `NEMOCLAW_GATEWAY_PORT` is registered against `nemoclaw-`, and any + * command that talks to the literal default gateway operates on the wrong + * gateway and fails with `sandbox has no spec`. + * + * Resolution order: + * 1. If `gatewayPort` is valid, derive the canonical gateway name from the + * port. When a persisted `gatewayName` is also present it must match that + * derivation; otherwise the port wins so tampered registry state cannot + * redirect destructive operations to a different valid NemoClaw gateway. + * 2. A name-only legacy entry may use a persisted `gatewayName`, validated + * against the NemoClaw namespace (`nemoclaw` or `nemoclaw-`). + * 3. The bare `BASE_GATEWAY_NAME` for older entries that pre-date the + * per-port migration entirely (neither field present). + * + * Fail closed when either field is present but invalid. Silently falling + * back to the default gateway would let a corrupted or tampered registry + * row redirect destroy/snapshot/cleanup to the wrong (or default) gateway. + */ +export function resolveSandboxGatewayName( + sandbox: SandboxGatewayBinding | null | undefined, +): string { + if ( + typeof sandbox?.gatewayPort === "number" && + isValidPersistedGatewayPort(sandbox.gatewayPort) + ) { + return resolveGatewayName(sandbox.gatewayPort); + } + if ( + sandbox?.gatewayName && + typeof sandbox.gatewayName === "string" && + isValidPersistedGatewayName(sandbox.gatewayName) + ) { + return sandbox.gatewayName; + } + const portPresent = sandbox?.gatewayPort !== undefined && sandbox?.gatewayPort !== null; + const namePresent = sandbox?.gatewayName !== undefined && sandbox?.gatewayName !== null; + if (!portPresent && !namePresent) { + return BASE_GATEWAY_NAME; + } + const detail: string[] = []; + if (portPresent) detail.push(`gatewayPort=${JSON.stringify(sandbox?.gatewayPort)}`); + if (namePresent) detail.push(`gatewayName=${JSON.stringify(sandbox?.gatewayName)}`); + throw new Error(`Invalid persisted sandbox gateway binding (${detail.join(", ")})`); +} + /** * Resolve the Docker-driver gateway state directory leaf name for a gateway * port. The state dir holds the gateway pid file and runtime marker, so a @@ -87,7 +185,7 @@ export interface GatewayNameBoundClassifiers { * Bind the gateway-name-aware health/reuse classifiers to a resolved gateway * name so a non-default NEMOCLAW_GATEWAY_PORT (gateway `nemoclaw-`) is * recognized as its own gateway rather than matched against the `nemoclaw` - * singleton (#4422). Kept out of onboard.ts to avoid growing that file. + * singleton. Kept out of onboard.ts to avoid growing that file. */ export function createGatewayNameBoundClassifiers( state: typeof import("../state/gateway"), diff --git a/src/lib/onboard/gateway-recovery.test.ts b/src/lib/onboard/gateway-recovery.test.ts new file mode 100644 index 00000000000..1d2971657ca --- /dev/null +++ b/src/lib/onboard/gateway-recovery.test.ts @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + type GatewayRecoveryDeps, + startGatewayForRecovery, +} from "../../../dist/lib/onboard/gateway-recovery"; + +function createDeps(overrides: Partial = {}): GatewayRecoveryDeps { + return { + getGatewayClusterContainerState: () => "missing", + getGatewayStartEnv: () => ({ OPENSHELL_DRIVERS: "docker" }), + runCaptureOpenshell: vi.fn(() => "Disconnected"), + runOpenshell: vi.fn(() => ({ status: 0 })), + startGatewayWithOptions: vi.fn( + async () => undefined, + ) as GatewayRecoveryDeps["startGatewayWithOptions"], + // Tests assert the plain-CLI fallback path by default; the Linux + // Docker-driver branch is opted into explicitly per case. + isLinuxDockerDriverGatewayEnabled: () => false, + ...overrides, + }; +} + +describe("gateway recovery", () => { + afterEach(() => { + vi.unstubAllEnvs(); + delete process.env.OPENSHELL_GATEWAY; + }); + + it("uses the default gateway starter when no explicit target is supplied", async () => { + const deps = createDeps(); + + await startGatewayForRecovery({}, deps); + + expect(deps.startGatewayWithOptions).toHaveBeenCalledWith(undefined, { + exitOnFailure: false, + }); + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("starts and selects the named gateway using the port encoded in its name", async () => { + vi.stubEnv("NEMOCLAW_HEALTH_POLL_COUNT", "1"); + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-8090" }, deps)).rejects.toThrow( + "Gateway 'nemoclaw-8090' failed to start", + ); + + expect(deps.startGatewayWithOptions).not.toHaveBeenCalled(); + expect(deps.runOpenshell).toHaveBeenNthCalledWith( + 1, + ["gateway", "start", "--name", "nemoclaw-8090", "--port", "8090"], + { + ignoreError: true, + env: { + OPENSHELL_DRIVERS: "docker", + OPENSHELL_SERVER_PORT: "8090", + OPENSHELL_SSH_GATEWAY_PORT: "8090", + }, + suppressOutput: true, + }, + ); + expect(deps.runOpenshell).toHaveBeenNthCalledWith(2, ["gateway", "select", "nemoclaw-8090"], { + ignoreError: true, + }); + }); + + it("derives the canonical gateway name when only a non-default port is supplied", async () => { + vi.stubEnv("NEMOCLAW_HEALTH_POLL_COUNT", "1"); + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayPort: 8091 }, deps)).rejects.toThrow( + "Gateway 'nemoclaw-8091' failed to start", + ); + + expect(deps.runOpenshell).toHaveBeenNthCalledWith( + 1, + ["gateway", "start", "--name", "nemoclaw-8091", "--port", "8091"], + expect.objectContaining({ + env: expect.objectContaining({ + OPENSHELL_SERVER_PORT: "8091", + OPENSHELL_SSH_GATEWAY_PORT: "8091", + }), + }), + ); + }); + + it("rejects non-canonical gateway recovery names before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "other-gateway" }, deps)).rejects.toThrow( + "Invalid NemoClaw gateway name 'other-gateway'", + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("rejects a gateway name and port mismatch before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect( + startGatewayForRecovery({ gatewayName: "nemoclaw-8090", gatewayPort: 8091 }, deps), + ).rejects.toThrow("Gateway 'nemoclaw-8090' does not match port 8091"); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("rejects privileged recovery ports before invoking OpenShell", async () => { + const deps = createDeps(); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-80" }, deps)).rejects.toThrow( + "Invalid gateway recovery port 80", + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + }); + + it("fails closed on cross-port recovery when the Linux Docker-driver gateway is enabled", async () => { + const deps = createDeps({ isLinuxDockerDriverGatewayEnabled: () => true }); + + await expect(startGatewayForRecovery({ gatewayName: "nemoclaw-8090" }, deps)).rejects.toThrow( + /Cross-port recovery for Linux Docker-driver gateway 'nemoclaw-8090' is not safe/, + ); + + expect(deps.runOpenshell).not.toHaveBeenCalled(); + expect(deps.startGatewayWithOptions).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/gateway-recovery.ts b/src/lib/onboard/gateway-recovery.ts new file mode 100644 index 00000000000..d5e80295f74 --- /dev/null +++ b/src/lib/onboard/gateway-recovery.ts @@ -0,0 +1,222 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import { dockerContainerInspectFormat } from "../adapters/docker"; +import { getGatewayClusterContainerName } from "../adapters/openshell/gateway-drift"; +import { getGatewayHttpEndpoint } from "../core/gateway-address"; +import { + BEDROCK_RUNTIME_ADAPTER_PORT, + DASHBOARD_PORT, + DASHBOARD_PORT_RANGE_END, + DASHBOARD_PORT_RANGE_START, + GATEWAY_PORT, + OLLAMA_PORT, + OLLAMA_PROXY_PORT, + validateGatewayPort, + VLLM_PORT, +} from "../core/ports"; +import { sleepSeconds } from "../core/wait"; +import { shouldPatchCoredns } from "../platform"; +import { run, SCRIPTS } from "../runner"; +import { isGatewayHealthy } from "../state/gateway"; +import { envInt } from "./env"; +import { resolveGatewayName, resolveGatewayPortFromName } from "./gateway-binding"; +import { isGatewayHttpReady } from "./gateway-http-readiness"; +import { getContainerRuntime } from "./local-inference-topology"; +import { isLinuxDockerDriverGatewayEnabled } from "./docker-driver-platform"; + +export type StartGatewayForRecoveryOptions = { + gatewayName?: string; + gatewayPort?: number; +}; + +type RunOpenshellOptions = { + ignoreError?: boolean; + env?: Record; + suppressOutput?: boolean; +}; + +type RunCaptureOpenshellOptions = { + ignoreError?: boolean; +}; + +type GatewayStartResult = { + status?: number | null; +}; + +export type GatewayRecoveryDeps = { + getGatewayClusterContainerState?(gatewayName: string): string; + getGatewayStartEnv(): Record; + runCaptureOpenshell(args: string[], opts?: RunCaptureOpenshellOptions): string; + runOpenshell(args: string[], opts?: RunOpenshellOptions): GatewayStartResult; + startGatewayWithOptions(gpu: never, options: { exitOnFailure: false }): Promise; + isLinuxDockerDriverGatewayEnabled?(): boolean; +}; + +function isValidGatewayRecoveryPort(port: number | null | undefined): port is number { + return Number.isInteger(port) && Number(port) >= 1024 && Number(port) <= 65535; +} + +function resolveDefaultGatewayName(): string { + return resolveGatewayName(GATEWAY_PORT); +} + +function resolveGatewayRecoveryTarget(options: StartGatewayForRecoveryOptions = {}) { + const gatewayName = + options.gatewayName || + (isValidGatewayRecoveryPort(options.gatewayPort) + ? resolveGatewayName(options.gatewayPort) + : resolveDefaultGatewayName()); + const portFromName = resolveGatewayPortFromName(gatewayName); + if (portFromName === null) { + throw new Error(`Invalid NemoClaw gateway name '${gatewayName}'`); + } + const gatewayPort = options.gatewayPort ?? portFromName; + if (gatewayPort !== portFromName) { + throw new Error(`Gateway '${gatewayName}' does not match port ${gatewayPort}`); + } + if (!isValidGatewayRecoveryPort(gatewayPort)) { + throw new Error(`Invalid gateway recovery port ${gatewayPort}`); + } + validateGatewayPort("NEMOCLAW_GATEWAY_PORT", gatewayPort, { + dashboardPort: DASHBOARD_PORT, + dashboardRangeStart: DASHBOARD_PORT_RANGE_START, + dashboardRangeEnd: DASHBOARD_PORT_RANGE_END, + vllmPort: VLLM_PORT, + ollamaPort: OLLAMA_PORT, + ollamaProxyPort: OLLAMA_PROXY_PORT, + bedrockRuntimeAdapterPort: BEDROCK_RUNTIME_ADAPTER_PORT, + }); + return { gatewayName, gatewayPort }; +} + +function getGatewayStartEnvForPort( + gatewayPort: number, + getGatewayStartEnv: GatewayRecoveryDeps["getGatewayStartEnv"], +): Record { + return { + ...getGatewayStartEnv(), + OPENSHELL_SERVER_PORT: String(gatewayPort), + OPENSHELL_SSH_GATEWAY_PORT: String(gatewayPort), + }; +} + +function getDefaultGatewayClusterContainerState(gatewayName: string): string { + const state = dockerContainerInspectFormat( + "{{.State.Status}}{{if .State.Health}} {{.State.Health.Status}}{{end}}", + getGatewayClusterContainerName(gatewayName), + { ignoreError: true }, + ) + .trim() + .toLowerCase(); + return state || "missing"; +} + +function getGatewayHealthWaitConfig(_startStatus = 0, containerState = "") { + const isArm64 = process.arch === "arm64"; + const standardCount = envInt("NEMOCLAW_HEALTH_POLL_COUNT", isArm64 ? 30 : 12); + const standardInterval = envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", isArm64 ? 10 : 5); + const extendedCount = envInt("NEMOCLAW_GATEWAY_START_POLL_COUNT", standardCount); + const extendedInterval = envInt("NEMOCLAW_GATEWAY_START_POLL_INTERVAL", standardInterval); + const normalizedState = String(containerState || "") + .trim() + .toLowerCase(); + const normalizedContainerState = normalizedState || "missing"; + const useExtendedWait = normalizedContainerState !== "missing"; + + return { + count: useExtendedWait ? extendedCount : standardCount, + interval: useExtendedWait ? extendedInterval : standardInterval, + extended: useExtendedWait, + containerState: normalizedContainerState, + }; +} + +async function startTargetGatewayForRecovery( + { gatewayName, gatewayPort }: { gatewayName: string; gatewayPort: number }, + deps: GatewayRecoveryDeps, +): Promise { + const gatewayPortArg = String(gatewayPort); + const startResult = deps.runOpenshell( + ["gateway", "start", "--name", gatewayName, "--port", gatewayPortArg], + { + ignoreError: true, + env: getGatewayStartEnvForPort(gatewayPort, deps.getGatewayStartEnv), + suppressOutput: true, + }, + ); + deps.runOpenshell(["gateway", "select", gatewayName], { ignoreError: true }); + + const recoveryWait = getGatewayHealthWaitConfig( + startResult.status ?? 0, + (deps.getGatewayClusterContainerState ?? getDefaultGatewayClusterContainerState)(gatewayName), + ); + const recoveryPollCount = recoveryWait.extended + ? recoveryWait.count + : envInt("NEMOCLAW_HEALTH_POLL_COUNT", 10); + const recoveryPollInterval = recoveryWait.extended + ? recoveryWait.interval + : envInt("NEMOCLAW_HEALTH_POLL_INTERVAL", 2); + const targetGatewayUrl = `${getGatewayHttpEndpoint(gatewayPort)}/`; + for (let i = 0; i < recoveryPollCount; i++) { + const status = deps.runCaptureOpenshell(["status"], { ignoreError: true }); + const namedInfo = deps.runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { + ignoreError: true, + }); + const currentInfo = deps.runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); + if ( + status.includes("Connected") && + isGatewayHealthy(status, namedInfo, currentInfo, gatewayName) && + (await isGatewayHttpReady(undefined, targetGatewayUrl)) + ) { + process.env.OPENSHELL_GATEWAY = gatewayName; + const runtime = getContainerRuntime(); + if (shouldPatchCoredns(runtime)) { + run(["bash", path.join(SCRIPTS, "fix-coredns.sh"), gatewayName], { + ignoreError: true, + }); + } + return; + } + if (i < recoveryPollCount - 1) sleepSeconds(recoveryPollInterval); + } + + throw new Error(`Gateway '${gatewayName}' failed to start`); +} + +export async function startGatewayForRecovery( + options: StartGatewayForRecoveryOptions, + deps: GatewayRecoveryDeps, +): Promise { + const target = resolveGatewayRecoveryTarget(options); + const linuxDockerDriverEnabled = ( + deps.isLinuxDockerDriverGatewayEnabled ?? isLinuxDockerDriverGatewayEnabled + )(); + // The Docker-driver Linux startup path (startGatewayWithOptions → + // startDockerDriverGateway) restores the runtime-marker, package-managed + // registration, and sandbox-bridge reachability — none of which a plain + // `openshell gateway start` produces. Route through it whenever the + // recovery target matches the current process's GATEWAY_PORT (the common + // case where the user re-runs with the same NEMOCLAW_GATEWAY_PORT). + if (target.gatewayPort === GATEWAY_PORT) { + if (target.gatewayName === resolveDefaultGatewayName() || linuxDockerDriverEnabled) { + return deps.startGatewayWithOptions(undefined as never, { exitOnFailure: false }); + } + } + // Cross-port recovery on a Linux Docker-driver gateway cannot share this + // process's module-globals: startDockerDriverGateway captures the port at + // load time, so a plain `openshell gateway start` would skip the + // runtime-marker / package registration / sandbox-bridge setup and leave + // the host in a half-recovered state. Fail closed instead and direct the + // operator to re-run with the matching NEMOCLAW_GATEWAY_PORT so the + // docker-driver path re-stamps the per-port artefacts. + if (linuxDockerDriverEnabled && target.gatewayPort !== GATEWAY_PORT) { + throw new Error( + `Cross-port recovery for Linux Docker-driver gateway '${target.gatewayName}' is not safe from a process bound to port ${GATEWAY_PORT}. ` + + `Re-run with NEMOCLAW_GATEWAY_PORT=${target.gatewayPort} so the docker-driver setup can restamp the runtime marker, registration, and sandbox bridge.`, + ); + } + return startTargetGatewayForRecovery(target, deps); +} diff --git a/src/lib/openshell-sandbox-list.ts b/src/lib/openshell-sandbox-list.ts index 2d909f6809c..7f32363a505 100644 --- a/src/lib/openshell-sandbox-list.ts +++ b/src/lib/openshell-sandbox-list.ts @@ -3,7 +3,7 @@ import { detectOpenShellStateRpcResultIssue } from "./adapters/openshell/gateway-drift"; import { stripAnsi } from "./adapters/openshell/client"; -import { captureOpenshell } from "./adapters/openshell/runtime"; +import { captureOpenshell, runOpenshell } from "./adapters/openshell/runtime"; import { recoverNamedGatewayRuntime } from "./gateway-runtime-action"; type SandboxListResult = ReturnType; @@ -14,6 +14,10 @@ export type SandboxListRecoveryResult = { recoverySucceeded: boolean; }; +export type CaptureSandboxListWithGatewayRecoveryOptions = { + gatewayName?: string; +}; + export function isRecoverableSandboxListGatewayFailure(result: SandboxListResult): boolean { if (result.status === 0 || detectOpenShellStateRpcResultIssue(result)) { return false; @@ -24,15 +28,24 @@ export function isRecoverableSandboxListGatewayFailure(result: SandboxListResult ); } -export async function captureSandboxListWithGatewayRecovery(): Promise { +export async function captureSandboxListWithGatewayRecovery( + options: CaptureSandboxListWithGatewayRecoveryOptions = {}, +): Promise { + if (options.gatewayName) { + runOpenshell(["gateway", "select", options.gatewayName], { ignoreError: true }); + } const initial = captureOpenshell(["sandbox", "list"]); if (!isRecoverableSandboxListGatewayFailure(initial)) { return { result: initial, recoveryAttempted: false, recoverySucceeded: false }; } - const recovery = await recoverNamedGatewayRuntime({ - recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable"], - }); + const recoveryOptions: Parameters[0] = { + recoverableStates: ["missing_named", "named_unhealthy", "named_unreachable", "connected_other"], + }; + if (options.gatewayName) { + recoveryOptions.gatewayName = options.gatewayName; + } + const recovery = await recoverNamedGatewayRuntime(recoveryOptions); if (!recovery.recovered) { return { result: initial, recoveryAttempted: true, recoverySucceeded: false }; } diff --git a/src/lib/status-command-deps.ts b/src/lib/status-command-deps.ts index 8f3adb36156..1ce6270098c 100644 --- a/src/lib/status-command-deps.ts +++ b/src/lib/status-command-deps.ts @@ -6,7 +6,9 @@ import type { CaptureOpenshellResult } from "./adapters/openshell/client"; import { captureOpenshellCommand } from "./adapters/openshell/client"; import { resolveOpenshell } from "./adapters/openshell/resolve"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "./adapters/openshell/timeouts"; +import { GATEWAY_PORT } from "./core/ports"; import { getNamedGatewayLifecycleState } from "./gateway-runtime-action"; +import { resolveGatewayName } from "./onboard/gateway-binding"; import { getLiveGatewayInference } from "./inference/live"; import type { GatewayHealth, MessagingBridgeHealth, ShowStatusCommandDeps } from "./inventory"; import { detectAllSlackSocketModeGatewayOverlaps, findAllOverlaps } from "./messaging/applier"; @@ -111,14 +113,15 @@ function readGatewayLog(rootDir: string, sandboxName: string): string | null { function probeGatewayHealth(): GatewayHealth { try { - const lifecycle = getNamedGatewayLifecycleState(); + const expectedGateway = resolveGatewayName(GATEWAY_PORT); + const lifecycle = getNamedGatewayLifecycleState(expectedGateway); if (lifecycle.state === "healthy_named") { return { healthy: true, state: lifecycle.state }; } const reasonByState: Record = { named_unreachable: "host port held or container not running", named_unhealthy: "named gateway present but not Connected", - connected_other: `connected to '${lifecycle.activeGateway ?? "unknown"}', not 'nemoclaw'`, + connected_other: `connected to '${lifecycle.activeGateway ?? "unknown"}', not '${expectedGateway}'`, missing_named: "named gateway not configured", }; return { diff --git a/test/cli/destroy-gateway-cleanup.test.ts b/test/cli/destroy-gateway-cleanup.test.ts index f24dcce47ac..f8c66fc978f 100644 --- a/test/cli/destroy-gateway-cleanup.test.ts +++ b/test/cli/destroy-gateway-cleanup.test.ts @@ -97,6 +97,8 @@ describe("CLI dispatch", () => { provider: "nvidia-prod", gpuEnabled: false, policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, }, }, defaultSandbox: "alpha", @@ -144,9 +146,13 @@ describe("CLI dispatch", () => { expect(openshellOutput).toContain("sandbox delete alpha"); expect(openshellOutput).toContain("forward stop 18789"); expect(openshellOutput).toContain( - process.platform === "linux" ? "gateway remove nemoclaw" : "gateway destroy -g nemoclaw", + process.platform === "linux" + ? "gateway remove nemoclaw-8081" + : "gateway destroy -g nemoclaw-8081", + ); + expect(fs.readFileSync(bashLog, "utf8")).toContain( + "volume ls -q --filter name=openshell-cluster-nemoclaw-8081", ); - expect(fs.readFileSync(bashLog, "utf8")).toContain("volume ls -q --filter"); }, ); @@ -223,6 +229,83 @@ describe("CLI dispatch", () => { }, ); + it.runIf(process.platform === "linux")( + "clears only the per-port host gateway PID file when destroying nemoclaw-", + testTimeoutOptions(30_000), + () => { + // A `nemoclaw-8081` sandbox's destroy must read and clear its own + // `openshell-docker-gateway-8081/openshell-gateway.pid`, NOT the default + // instance's `openshell-docker-gateway/openshell-gateway.pid`. Otherwise + // destroying a non-default sandbox tears down the default instance's + // tracked host gateway process. + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-perport-pid-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const defaultStateDir = path.join(home, ".local/state/nemoclaw/openshell-docker-gateway"); + const perPortStateDir = path.join( + home, + ".local/state/nemoclaw/openshell-docker-gateway-8081", + ); + const defaultPidFile = path.join(defaultStateDir, "openshell-gateway.pid"); + const perPortPidFile = path.join(perPortStateDir, "openshell-gateway.pid"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.mkdirSync(defaultStateDir, { recursive: true }); + fs.mkdirSync(perPortStateDir, { recursive: true }); + // PIDs that are guaranteed to be dead so stopHostGatewayProcesses takes + // the clearRuntimeFiles branch without trying to kill anything. + fs.writeFileSync(defaultPidFile, "999998\n"); + fs.writeFileSync(perPortPidFile, "999999\n"); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/bin/sh", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + ' printf "NAME STATUS\\n"', + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(localBin, "docker"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + fs.writeFileSync(path.join(localBin, "pgrep"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + fs.writeFileSync(path.join(localBin, "lsof"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + + const r = runWithEnv( + "alpha destroy -y --cleanup-gateway", + { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }, + 30_000, + ); + + expect(r.code, r.out).toBe(0); + expect(fs.existsSync(perPortPidFile)).toBe(false); + expect(fs.existsSync(defaultPidFile)).toBe(true); + expect(fs.readFileSync(defaultPidFile, "utf8").trim()).toBe("999998"); + }, + ); + it("keeps the gateway runtime when other sandboxes still exist", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-shared-")); const localBin = path.join(home, "bin"); @@ -241,6 +324,8 @@ describe("CLI dispatch", () => { provider: "nvidia-prod", gpuEnabled: false, policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, }, beta: { name: "beta", @@ -361,6 +446,81 @@ describe("CLI dispatch", () => { } }); + it("selects the sandbox persisted gateway before provider cleanup and delete", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-select-gateway-")); + const localBin = path.join(home, "bin"); + const registryDir = path.join(home, ".nemoclaw"); + const openshellLog = path.join(home, "openshell.log"); + const activeGateway = path.join(home, "active-gateway"); + fs.mkdirSync(localBin, { recursive: true }); + fs.mkdirSync(registryDir, { recursive: true }); + fs.writeFileSync(activeGateway, "other-gateway\n"); + fs.writeFileSync( + path.join(registryDir, "sandboxes.json"), + JSON.stringify({ + sandboxes: { + alpha: { + name: "alpha", + model: "test-model", + provider: "nvidia-prod", + gpuEnabled: false, + policies: [], + gatewayName: "nemoclaw-8081", + gatewayPort: 8081, + }, + }, + defaultSandbox: "alpha", + }), + { mode: 0o600 }, + ); + fs.writeFileSync( + path.join(localBin, "openshell"), + [ + "#!/bin/sh", + `log_file=${JSON.stringify(openshellLog)}`, + `active_gateway=${JSON.stringify(activeGateway)}`, + 'printf \'%s\\n\' "$*" >> "$log_file"', + 'if [ "$1" = "gateway" ] && [ "$2" = "select" ]; then', + ' printf "%s\\n" "$3" > "$active_gateway"', + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "delete" ]; then', + ' active="$(cat "$active_gateway")"', + ' if [ "$active" != "nemoclaw-8081" ]; then', + ' printf "wrong gateway: %s\\n" "$active" >&2', + " exit 42", + " fi", + " exit 0", + "fi", + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + ' active="$(cat "$active_gateway")"', + ' if [ "$active" != "nemoclaw-8081" ]; then', + ' printf "wrong list gateway: %s\\n" "$active" >&2', + " exit 43", + " fi", + ' printf "NAME STATUS\\n"', + " exit 0", + "fi", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(localBin, "docker"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + + const r = runWithEnv("alpha destroy --yes", { + HOME: home, + PATH: `${localBin}:${process.env.PATH || ""}`, + }); + + expect(r.code, r.out).toBe(0); + const lines = fs.readFileSync(openshellLog, "utf8").trim().split("\n"); + const selectIndex = lines.indexOf("gateway select nemoclaw-8081"); + const deleteIndex = lines.indexOf("sandbox delete alpha"); + expect(selectIndex).toBeGreaterThanOrEqual(0); + expect(deleteIndex).toBeGreaterThan(selectIndex); + expect(lines.slice(deleteIndex + 1)).toContain("sandbox list"); + }); + it("fails destroy when openshell sandbox delete returns a real error", () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-destroy-failure-")); const localBin = path.join(home, "bin"); diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 94ba686edb8..d0dbba2ee30 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -184,6 +184,40 @@ describe("CLI dispatch", () => { expect(r.code).toBe(0); }); + it("doctor checks the sandbox persisted non-default gateway", () => { + const setup = createDoctorTestSetup("nemoclaw-cli-doctor-named-gateway-", [ + 'case "$*" in', + ' "status") printf "Server Status\\n\\n Gateway: nemoclaw-8090\\n Status: Connected\\n"; exit 0 ;;', + ' "gateway info -g nemoclaw-8090") printf "Gateway: nemoclaw-8090\\n"; exit 0 ;;', + ' "sandbox list") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', + ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + "esac", + ]); + writeSandboxRegistry(setup.home, "alpha", { + gatewayName: "nemoclaw-8090", + gatewayPort: 8090, + openshellDriver: "docker", + }); + writeHealthyCurlStub(setup); + + const r = setup.runDoctor("alpha doctor --json"); + + expect(r.code).toBe(0); + const report = JSON.parse(r.out) as { + checks: Array<{ group: string; label: string; status: string; detail: string }>; + }; + expect(report.checks.find((check) => check.label === "OpenShell status")).toEqual( + expect.objectContaining({ + group: "Gateway", + status: "ok", + detail: "connected to nemoclaw-8090", + }), + ); + const calls = setup.readCalls(); + expect(calls).toContain("gateway info -g nemoclaw-8090"); + expect(calls).not.toContain("gateway info -g nemoclaw"); + }); + it("doctor still inspects the legacy k3s gateway container for the kubernetes driver", () => { const setup = createDoctorTestSetup("nemoclaw-cli-doctor-k8s-driver-", [ 'case "$*" in', diff --git a/test/e2e/test-double-onboard.sh b/test/e2e/test-double-onboard.sh index d0a5269bb17..4a67e3b5fb6 100755 --- a/test/e2e/test-double-onboard.sh +++ b/test/e2e/test-double-onboard.sh @@ -63,6 +63,10 @@ phase_elapsed() { dump_diagnostics() { local phase_label="${1:-unknown}" info "=== Diagnostics for ${phase_label} ===" + if [ -n "${RUN_ONBOARD_OUTPUT:-}" ]; then + info "Captured nemoclaw onboard stdout/stderr (exit=${RUN_ONBOARD_EXIT:-?}):" + printf '%s\n' "$RUN_ONBOARD_OUTPUT" | sed 's/^/ /' + fi info "openshell status:" openshell status 2>&1 | sed 's/^/ /' || true info "openshell sandbox list:" diff --git a/test/e2e/test-onboard-repair.sh b/test/e2e/test-onboard-repair.sh index 039d5ebf074..958bd68beae 100755 --- a/test/e2e/test-onboard-repair.sh +++ b/test/e2e/test-onboard-repair.sh @@ -198,12 +198,16 @@ if echo "$first_output" | grep -q "\[e2e\] Forced onboarding failure at step 'po pass "First run failed at policy setup as intended" else fail "First run did not fail at the expected policy step" + info "Captured first-onboard stdout/stderr (exit=$first_exit):" + printf '%s\n' "$first_output" | sed 's/^/ /' fi if openshell sandbox get "$SANDBOX_NAME" >/dev/null 2>&1; then pass "Sandbox '$SANDBOX_NAME' exists after interrupted run" else fail "Sandbox '$SANDBOX_NAME' not found after interrupted run" + info "Captured first-onboard stdout/stderr (exit=$first_exit):" + printf '%s\n' "$first_output" | sed 's/^/ /' fi # ══════════════════════════════════════════════════════════════════ diff --git a/test/snapshot-restore-existing-dest.test.ts b/test/snapshot-restore-existing-dest.test.ts index 3a18384311e..938642594cd 100644 --- a/test/snapshot-restore-existing-dest.test.ts +++ b/test/snapshot-restore-existing-dest.test.ts @@ -58,6 +58,14 @@ interface MakeEnvOptions { withSnapshot?: boolean; /** When false, fake docker exec returns an empty image string. */ withSourceImage?: boolean; + /** Put dst on a registered non-default gateway and hide it from src's gateway list. */ + destinationGatewayPort?: number; + /** When false, selecting the destination's persisted gateway fails. */ + destinationGatewaySelectSucceeds?: boolean; + /** When false, the destination gateway probe fails before --force can delete it. */ + destinationGatewayRunning?: boolean; + /** Let the currently-active source gateway also report a same-named destination. */ + foreignActiveGatewayListsDestination?: boolean; } /** @@ -82,6 +90,9 @@ function makeExistingDestEnv( const home = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); + const destinationGatewayName = opts.destinationGatewayPort + ? `nemoclaw-${opts.destinationGatewayPort}` + : null; const registryDir = path.join(home, ".nemoclaw"); fs.mkdirSync(registryDir, { recursive: true }); @@ -102,6 +113,12 @@ function makeExistingDestEnv( provider: "nvidia-prod", gpuEnabled: false, policies: [], + ...(destinationGatewayName + ? { + gatewayName: destinationGatewayName, + gatewayPort: opts.destinationGatewayPort, + } + : {}), }, }, defaultSandbox: "src", @@ -132,13 +149,24 @@ function makeExistingDestEnv( } const osLog = path.join(home, "openshell.log"); + const activeGateway = path.join(home, "active-gateway"); fs.writeFileSync( path.join(localBin, "openshell"), [ "#!/bin/sh", `printf '%s\\n' "$*" >> ${JSON.stringify(osLog)}`, + `ACTIVE_GATEWAY=${JSON.stringify(activeGateway)}`, + 'if [ "$1" = "gateway" ] && [ "$2" = "select" ]; then', + destinationGatewayName && opts.destinationGatewaySelectSucceeds === false + ? ` if [ "$3" = ${JSON.stringify(destinationGatewayName)} ]; then echo "select failed" >&2; exit 17; fi` + : " :", + ' printf "%s\\n" "$3" > "$ACTIVE_GATEWAY"', + " exit 0", + "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', - ' printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"', + destinationGatewayName + ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" = ${JSON.stringify(destinationGatewayName)} ]; then printf "NAME STATUS\\ndst Ready\\n"; else ${opts.foreignActiveGatewayListsDestination ? 'printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"' : 'printf "NAME STATUS\\nsrc Ready\\n"'}; fi` + : ' printf "NAME STATUS\\nsrc Ready\\ndst Ready\\n"', " exit 0", "fi", 'if [ "$1" = "status" ]; then', @@ -146,6 +174,9 @@ function makeExistingDestEnv( " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "delete" ]; then', + destinationGatewayName + ? ` active="$(cat "$ACTIVE_GATEWAY" 2>/dev/null || printf '%s' nemoclaw)"; if [ "$active" != ${JSON.stringify(destinationGatewayName)} ]; then echo "delete on wrong gateway: $active" >&2; exit 42; fi` + : " :", " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "create" ]; then', @@ -166,6 +197,9 @@ function makeExistingDestEnv( [ "#!/bin/sh", 'if [ "$1" = "inspect" ]; then', + destinationGatewayName && opts.destinationGatewayRunning === false + ? ` case "$*" in *openshell-cluster-${destinationGatewayName}*) echo "false"; exit 0 ;; esac` + : " :", ' echo "true"', " exit 0", "fi", @@ -197,6 +231,17 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).not.toMatch(/sandbox delete dst/); }); + it("refuses by default when the destination is registered on another gateway", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-refuse-", { + destinationGatewayPort: 8090, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Destination sandbox 'dst' already exists/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).not.toMatch(/sandbox delete dst/); + }); + it("refuses by default before running source-image preflight (Codex #3796 P2)", () => { // Existing destination + unresolvable source image. The user must see the // precise "destination exists" error, not the "cannot resolve image" @@ -221,6 +266,45 @@ describe("snapshot restore --to existing destination (#3756)", () => { expect(log).toMatch(/sandbox delete dst/); }); + it("deletes a registered cross-gateway destination on its own gateway before recreating", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-force-", { + destinationGatewayPort: 8090, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.out).toMatch(/Deleting existing destination 'dst'/); + const lines = fs.readFileSync(osLog, "utf-8").trim().split("\n"); + const deleteIndex = lines.indexOf("sandbox delete dst"); + expect(deleteIndex).toBeGreaterThan(0); + expect(lines.slice(0, deleteIndex)).toContain("gateway select nemoclaw-8090"); + expect(lines.slice(deleteIndex + 1)).toContain("gateway select nemoclaw"); + }); + + it("aborts before deleting when a registered destination gateway cannot be verified", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-unverified-", { + destinationGatewayPort: 8090, + destinationGatewayRunning: false, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Cannot verify destination sandbox 'dst'/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).not.toMatch(/sandbox delete dst/); + }); + + it("aborts before deleting when destination gateway select fails even if the active gateway lists dst", () => { + const { env, osLog } = makeExistingDestEnv("nemoclaw-snap-restore-cross-select-fails-", { + destinationGatewayPort: 8090, + destinationGatewaySelectSucceeds: false, + foreignActiveGatewayListsDestination: true, + }); + const r = runCli(["src", "snapshot", "restore", "--to", "dst", "--force", "--yes"], env); + expect(r.code).toBe(1); + expect(r.out).toMatch(/Cannot verify destination sandbox 'dst'/); + const log = fs.existsSync(osLog) ? fs.readFileSync(osLog, "utf-8") : ""; + expect(log).toMatch(/gateway select nemoclaw-8090/); + expect(log).not.toMatch(/sandbox delete dst/); + }); + it("skips the prompt under NEMOCLAW_NON_INTERACTIVE=1 even without --yes", () => { const base = makeExistingDestEnv("nemoclaw-snap-restore-noninteractive-"); const env = { ...base.env, NEMOCLAW_NON_INTERACTIVE: "1" };