From 22f846acb9f423c72f74230849118bd69f3f05e9 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sun, 19 Jul 2026 07:40:43 +0000 Subject: [PATCH 1/9] fix(sandbox): observe host gateway on probe-only and wait for readiness before probing Sandbox-scoped commands (`recover`, `start`, `connect --probe-only`) now run reconciliation in `observe` mode, so a transient host gateway RPC error surfaces with explicit guidance instead of implicitly reaping and replacing the shared host OpenShell gateway. Probe-only also waits for the target sandbox to reach `Ready`/`Running` (default 300s, still honouring `NEMOCLAW_CONNECT_TIMEOUT`) before inspecting in-sandbox processes or host forwards, so a cold ~two-minute Hermes boot succeeds on the first invocation. Fixes #7173 Signed-off-by: Tinson Lai --- .../recover-rebuild-sandboxes.mdx | 9 + .../sandbox/connect-probe-observe.test.ts | 85 +++++++ .../sandbox/connect-route-containment.test.ts | 6 +- src/lib/actions/sandbox/connect.ts | 235 +++++++++--------- .../gateway-state-observe-mode.test.ts | 100 ++++++++ src/lib/actions/sandbox/gateway-state.ts | 30 ++- 6 files changed, 346 insertions(+), 119 deletions(-) create mode 100644 src/lib/actions/sandbox/connect-probe-observe.test.ts create mode 100644 src/lib/actions/sandbox/gateway-state-observe-mode.test.ts diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index cfbe1eab2a2..9b727120579 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -80,6 +80,15 @@ Use `nemo-deepagents status`, `logs`, `connect`, and `rebuild` fo If the terminal runtime reports degraded health, rebuild the sandbox instead of using `recover` or `gateway restart`. +### Host OpenShell Gateway Versus In-Sandbox Agent Recovery + +`recover` and `start` repair the in-sandbox agent gateway and the host-side port forwards for one named sandbox. +They do not restart, replace, or reap the shared host OpenShell gateway process. +If the host gateway RPC returns an error while these sandbox-scoped commands run, they surface the error with explicit next-step guidance and exit rather than swapping the shared gateway out from under other sandboxes. + +To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `nemoclaw onboard` again. +Only the onboarding path and `nemoclaw gateway restart` are permitted to reap or replace the shared host gateway. + ## Rebuild While Preserving State diff --git a/src/lib/actions/sandbox/connect-probe-observe.test.ts b/src/lib/actions/sandbox/connect-probe-observe.test.ts new file mode 100644 index 00000000000..5b0fb15e6fc --- /dev/null +++ b/src/lib/actions/sandbox/connect-probe-observe.test.ts @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; + +import { + connectModulePath, + createConnectHarness, + requireDist, +} from "../../../../test/support/connect-flow-test-harness"; + +describe("connectSandbox probe-only observe mode", () => { + let exitSpy: MockInstance; + + beforeEach(() => { + process.env.NEMOCLAW_TEST_NO_SLEEP = "1"; + exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { + throw new Error(`process.exit(${code ?? 0})`); + }) as never); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + delete process.env.NEMOCLAW_TEST_NO_SLEEP; + delete process.env.NEMOCLAW_CONNECT_TIMEOUT; + delete require.cache[requireDist.resolve(connectModulePath)]; + }); + + it("passes gatewayRecovery=observe to ensureLiveSandboxOrExit on probeOnly", async () => { + const harness = createConnectHarness(); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); + + expect(harness.ensureLiveSandboxSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ allowNonReadyPhase: true, gatewayRecovery: "observe" }), + ); + expect(exitSpy).not.toHaveBeenCalled(); + }); + + it("uses gatewayRecovery=recover on the full connect path", async () => { + const harness = createConnectHarness(); + + await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(0)"); + + expect(harness.ensureLiveSandboxSpy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ allowNonReadyPhase: true, gatewayRecovery: "recover" }), + ); + }); + + it("polls sandbox readiness before running in-sandbox process recovery on probeOnly", async () => { + const harness = createConnectHarness(); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); + + const listInvocations = harness.captureOpenshellSpy.mock.invocationCallOrder.filter( + (_, index) => { + const call = harness.captureOpenshellSpy.mock.calls[index]; + return ( + Array.isArray(call?.[0]) && + (call[0] as string[])[0] === "sandbox" && + (call[0] as string[])[1] === "list" + ); + }, + ); + expect(listInvocations.length).toBeGreaterThan(0); + const recoveryOrder = harness.checkAndRecoverSpy.mock.invocationCallOrder; + expect(recoveryOrder.length).toBeGreaterThan(0); + expect(listInvocations[0]).toBeLessThan(recoveryOrder[0]); + }); + + it("exits on timeout when sandbox never reports Ready on probeOnly", async () => { + process.env.NEMOCLAW_CONNECT_TIMEOUT = "1"; + const harness = createConnectHarness({ listOutput: "alpha Starting" }); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( + "process.exit(1)", + ); + + const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"); + expect(errors).toContain("Timed out after 1s waiting for sandbox 'alpha'"); + }); +}); diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index 9f816f801b5..830e449ebd3 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -275,7 +275,11 @@ describe("connect route containment", () => { releaseLock(); await expect(connect).rejects.toThrow("process.exit(1)"); - expect(harness.captureOpenshellSpy).not.toHaveBeenCalled(); + const routeReadCalls = harness.captureOpenshellSpy.mock.calls.filter((call) => { + const argv = Array.isArray(call?.[0]) ? (call[0] as string[]) : []; + return argv[0] === "sandbox" && argv[1] !== "list"; + }); + expect(routeReadCalls).toHaveLength(0); expect(harness.runOpenshellSpy).not.toHaveBeenCalled(); expect(harness.applyVmDnsMonkeypatchSpy).not.toHaveBeenCalled(); expect(harness.runSetupDnsProxySpy).not.toHaveBeenCalled(); diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index ed71dae1cb9..36d05dd4a98 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -926,6 +926,119 @@ function exitWithConnectSpawnResult(sandboxName: string, result: SpawnLikeResult process.exit(spawnExitCode(result)); } +type WaitForSandboxReadyOptions = { + defaultTimeoutSec?: number; + successLogs?: readonly string[]; +}; + +function waitForSandboxReadyOrExit( + sandboxName: string, + { defaultTimeoutSec = 120, successLogs = [] }: WaitForSandboxReadyOptions = {}, +): void { + const rawTimeout = process.env.NEMOCLAW_CONNECT_TIMEOUT; + let timeout = defaultTimeoutSec; + if (rawTimeout !== undefined) { + const parsed = parseInt(rawTimeout, 10); + if (Number.isNaN(parsed) || parsed <= 0) { + console.warn( + ` Warning: invalid NEMOCLAW_CONNECT_TIMEOUT="${rawTimeout}", using default ${defaultTimeoutSec}s`, + ); + } else { + timeout = parsed; + } + } + const interval = 3; + const startedAt = Date.now(); + const deadline = startedAt + timeout * 1000; + const elapsedSec = () => Math.floor((Date.now() - startedAt) / 1000); + const remainingMs = () => Math.max(1, deadline - Date.now()); + const runSandboxList = (): SandboxListProbe => { + const result = captureOpenshell(["sandbox", "list"], { + ignoreError: true, + timeout: remainingMs(), + }); + return { status: result.status, output: result.output }; + }; + + const listProbe = runSandboxList(); + const listCommandFailed = listProbe.status !== 0; + if (listCommandFailed && outputShowsGatewayUnavailable(listProbe.output)) { + failConnectReadinessGatewayUnavailable(sandboxName, listProbe.output); + } + const list = listProbe.output; + if (isSandboxReady(list, sandboxName)) return; + + const status = parseSandboxStatus(list, sandboxName); + if (!listCommandFailed && status && /^unknown$/i.test(status)) { + failIfGatewayBlocksConnectReadiness(sandboxName); + } + if (status && TERMINAL_SANDBOX_PHASES.has(status)) { + console.error(""); + console.error(` Sandbox '${sandboxName}' is in '${status}' state.`); + console.error(` Run: ${CLI_NAME} ${sandboxName} logs --follow`); + console.error(` Run: ${CLI_NAME} ${sandboxName} status`); + process.exit(1); + } + if (isDockerRuntimeDown(sandboxName)) { + failConnectReadinessDockerRuntimeDown(sandboxName); + } + + console.log(` Waiting for sandbox '${sandboxName}' to be ready...`); + let ready = false; + let everSeen = status !== null; + while (Date.now() < deadline) { + const sleepFor = Math.min(interval, remainingMs() / 1000); + if (sleepFor <= 0) break; + spawnSync("sleep", [String(sleepFor)]); + const pollProbe = runSandboxList(); + const pollCommandFailed = pollProbe.status !== 0; + if (pollCommandFailed && outputShowsGatewayUnavailable(pollProbe.output)) { + failConnectReadinessGatewayUnavailable(sandboxName, pollProbe.output); + } + const poll = pollProbe.output; + const elapsed = elapsedSec(); + if (isSandboxReady(poll, sandboxName)) { + ready = true; + break; + } + const parsedCur = parseSandboxStatus(poll, sandboxName); + const cur = parsedCur || "unknown"; + if (!pollCommandFailed && parsedCur && /^unknown$/i.test(parsedCur)) { + failIfGatewayBlocksConnectReadiness(sandboxName); + } + if (cur !== "unknown") everSeen = true; + if (TERMINAL_SANDBOX_PHASES.has(cur)) { + console.error(""); + console.error(` Sandbox '${sandboxName}' entered '${cur}' state.`); + console.error(` Run: ${CLI_NAME} ${sandboxName} logs --follow`); + console.error(` Run: ${CLI_NAME} ${sandboxName} status`); + process.exit(1); + } + if (isDockerRuntimeDown(sandboxName)) { + failConnectReadinessDockerRuntimeDown(sandboxName); + } + if (!everSeen && elapsed >= 30) { + console.error(""); + console.error(` Sandbox '${sandboxName}' not found after ${elapsed}s.`); + console.error(" Check: openshell sandbox list"); + process.exit(1); + } + process.stdout.write(`\r Status: ${cur.padEnd(20)} (${elapsed}s elapsed)`); + } + + if (!ready) { + console.error(""); + console.error(` Timed out after ${timeout}s waiting for sandbox '${sandboxName}'.`); + console.error(" Check: openshell sandbox list"); + console.error( + ` Override timeout: NEMOCLAW_CONNECT_TIMEOUT=300 ${CLI_NAME} ${sandboxName} connect`, + ); + process.exit(1); + } + console.log(`\r Status: ${"Ready".padEnd(20)} (${elapsedSec()}s elapsed)`); + for (const line of successLogs) console.log(line); +} + export async function connectSandbox( sandboxName: string, { probeOnly = false }: SandboxConnectOptions = {}, @@ -950,7 +1063,10 @@ export async function connectSandbox( // express-vLLM model preflight for them (it only steers the install path // and would otherwise hard-exit a recovery on a stale NEMOCLAW_VLLM_MODEL). if (!probeOnly) preflightVllmModelEnvOrExit(); - const live = await ensureLiveSandboxOrExit(sandboxName, { allowNonReadyPhase: true }); + const live = await ensureLiveSandboxOrExit(sandboxName, { + allowNonReadyPhase: true, + gatewayRecovery: probeOnly ? "observe" : "recover", + }); // Fast-fail on a Docker daemon outage before the probe-only health check and // the session/recovery probes below (each can spawn 15s `openshell sandbox @@ -971,6 +1087,7 @@ export async function connectSandbox( } if (probeOnly) { + waitForSandboxReadyOrExit(sandboxName, { defaultTimeoutSec: 300 }); return await runSandboxConnectProbe(sandboxName); } @@ -1016,119 +1133,9 @@ export async function connectSandbox( let sb: SandboxEntry | null = null; - const rawTimeout = process.env.NEMOCLAW_CONNECT_TIMEOUT; - let timeout = 120; - if (rawTimeout !== undefined) { - const parsed = parseInt(rawTimeout, 10); - if (Number.isNaN(parsed) || parsed <= 0) { - console.warn( - ` Warning: invalid NEMOCLAW_CONNECT_TIMEOUT="${rawTimeout}", using default 120s`, - ); - } else { - timeout = parsed; - } - } - const interval = 3; - const startedAt = Date.now(); - const deadline = startedAt + timeout * 1000; - const elapsedSec = () => Math.floor((Date.now() - startedAt) / 1000); - const remainingMs = () => Math.max(1, deadline - Date.now()); - const runSandboxList = (): SandboxListProbe => { - const result = captureOpenshell(["sandbox", "list"], { - ignoreError: true, - timeout: remainingMs(), - }); - return { status: result.status, output: result.output }; - }; - - const listProbe = runSandboxList(); - const listCommandFailed = listProbe.status !== 0; - if (listCommandFailed) { - if (outputShowsGatewayUnavailable(listProbe.output)) { - failConnectReadinessGatewayUnavailable(sandboxName, listProbe.output); - } - } - const list = listProbe.output; - if (!isSandboxReady(list, sandboxName)) { - const status = parseSandboxStatus(list, sandboxName); - if (!listCommandFailed && status && /^unknown$/i.test(status)) { - failIfGatewayBlocksConnectReadiness(sandboxName); - } - if (status && TERMINAL_SANDBOX_PHASES.has(status)) { - console.error(""); - console.error(` Sandbox '${sandboxName}' is in '${status}' state.`); - console.error(` Run: ${CLI_NAME} ${sandboxName} logs --follow`); - console.error(` Run: ${CLI_NAME} ${sandboxName} status`); - process.exit(1); - } - - // Probe-disagreement safety net: `sandbox get` may have reported Ready/no - // phase (so the early guard was skipped) while `sandbox list` shows a - // non-terminal status. Status is non-terminal here, so re-check Docker and - // fail fast rather than entering the readiness loop (#4428). - if (isDockerRuntimeDown(sandboxName)) { - failConnectReadinessDockerRuntimeDown(sandboxName); - } - - console.log(` Waiting for sandbox '${sandboxName}' to be ready...`); - let ready = false; - let everSeen = status !== null; - while (Date.now() < deadline) { - const sleepFor = Math.min(interval, remainingMs() / 1000); - if (sleepFor <= 0) break; - spawnSync("sleep", [String(sleepFor)]); - const pollProbe = runSandboxList(); - const pollCommandFailed = pollProbe.status !== 0; - if (pollCommandFailed) { - if (outputShowsGatewayUnavailable(pollProbe.output)) { - failConnectReadinessGatewayUnavailable(sandboxName, pollProbe.output); - } - } - const poll = pollProbe.output; - const elapsed = elapsedSec(); - if (isSandboxReady(poll, sandboxName)) { - ready = true; - break; - } - const parsedCur = parseSandboxStatus(poll, sandboxName); - const cur = parsedCur || "unknown"; - if (!pollCommandFailed && parsedCur && /^unknown$/i.test(parsedCur)) { - failIfGatewayBlocksConnectReadiness(sandboxName); - } - if (cur !== "unknown") everSeen = true; - if (TERMINAL_SANDBOX_PHASES.has(cur)) { - console.error(""); - console.error(` Sandbox '${sandboxName}' entered '${cur}' state.`); - console.error(` Run: ${CLI_NAME} ${sandboxName} logs --follow`); - console.error(` Run: ${CLI_NAME} ${sandboxName} status`); - process.exit(1); - } - // Catch a Docker daemon that dies mid-wait so we stop polling instead of - // running out the full readiness timeout (#4428). - if (isDockerRuntimeDown(sandboxName)) { - failConnectReadinessDockerRuntimeDown(sandboxName); - } - if (!everSeen && elapsed >= 30) { - console.error(""); - console.error(` Sandbox '${sandboxName}' not found after ${elapsed}s.`); - console.error(" Check: openshell sandbox list"); - process.exit(1); - } - process.stdout.write(`\r Status: ${cur.padEnd(20)} (${elapsed}s elapsed)`); - } - - if (!ready) { - console.error(""); - console.error(` Timed out after ${timeout}s waiting for sandbox '${sandboxName}'.`); - console.error(" Check: openshell sandbox list"); - console.error( - ` Override timeout: NEMOCLAW_CONNECT_TIMEOUT=300 ${CLI_NAME} ${sandboxName} connect`, - ); - process.exit(1); - } - console.log(`\r Status: ${"Ready".padEnd(20)} (${elapsedSec()}s elapsed)`); - console.log(" Sandbox is ready. Connecting..."); - } + waitForSandboxReadyOrExit(sandboxName, { + successLogs: [" Sandbox is ready. Connecting..."], + }); // ── Inference route swap (#1248, #3390) ─────────────────────────── // When the user has multiple sandboxes with different providers, the diff --git a/src/lib/actions/sandbox/gateway-state-observe-mode.test.ts b/src/lib/actions/sandbox/gateway-state-observe-mode.test.ts new file mode 100644 index 00000000000..297218e42fa --- /dev/null +++ b/src/lib/actions/sandbox/gateway-state-observe-mode.test.ts @@ -0,0 +1,100 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import * as gatewayRuntime from "../../gateway-runtime-action"; +import * as registry from "../../state/registry"; +import * as gatewaySelect from "./gateway-select"; +import { getReconciledSandboxGatewayState } from "./gateway-state"; + +describe("getReconciledSandboxGatewayState observe mode", () => { + beforeEach(() => { + vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8091", + }); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "healthy_named", + activeGateway: "nemoclaw-8091", + status: "Gateway: nemoclaw-8091\nStatus: Connected", + } as never); + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("returns gateway_error verbatim without invoking host gateway recovery", async () => { + const recover = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ recovered: true } as never); + const getState = vi + .fn() + .mockResolvedValue({ state: "gateway_error", output: "transport error" }); + + const result = await getReconciledSandboxGatewayState("beta", { + getState, + gatewayRecovery: "observe", + }); + + expect(getState).toHaveBeenCalledOnce(); + expect(recover).not.toHaveBeenCalled(); + expect(result).toMatchObject({ state: "gateway_error", output: "transport error" }); + expect(result.recoveredGateway).toBeUndefined(); + }); + + it("still invokes recovery when caller opts into recover mode explicitly", async () => { + const recover = vi.spyOn(gatewayRuntime, "recoverNamedGatewayRuntime").mockResolvedValue({ + recovered: true, + via: "start", + } as never); + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "gateway_error", output: "transport error" }) + .mockResolvedValueOnce({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { + getState, + gatewayRecovery: "recover", + }); + + expect(recover).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ + state: "present", + output: "Phase: Ready", + recoveredGateway: true, + recoveryVia: "start", + }); + }); + + it("defaults to recover mode when no option is supplied", async () => { + const recover = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ recovered: true } as never); + const getState = vi + .fn() + .mockResolvedValueOnce({ state: "gateway_error", output: "transport error" }) + .mockResolvedValueOnce({ state: "present", output: "Phase: Ready" }); + + await getReconciledSandboxGatewayState("beta", { getState }); + + expect(recover).toHaveBeenCalledOnce(); + }); + + it("does not touch recovery for non-error states in observe mode", async () => { + const recover = vi + .spyOn(gatewayRuntime, "recoverNamedGatewayRuntime") + .mockResolvedValue({ recovered: true } as never); + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { + getState, + gatewayRecovery: "observe", + }); + + expect(recover).not.toHaveBeenCalled(); + expect(result).toMatchObject({ state: "present" }); + }); +}); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index d6a52a1d91f..22f04fe31dd 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -471,11 +471,14 @@ export function printGatewayLifecycleHint( } } +export type GatewayRecoveryMode = "observe" | "recover"; + export async function getReconciledSandboxGatewayState( sandboxName: string, - opts: { getState?: SandboxGatewayStateLookup } = {}, + opts: { getState?: SandboxGatewayStateLookup; gatewayRecovery?: GatewayRecoveryMode } = {}, ): Promise { const getState = opts.getState ?? getSandboxGatewayState; + const gatewayRecovery: GatewayRecoveryMode = opts.gatewayRecovery ?? "recover"; let targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName) ?? undefined; const endpointOverride = gatewayEndpointOverrideState(); if (endpointOverride) return endpointOverride; @@ -509,6 +512,9 @@ export async function getReconciledSandboxGatewayState( } if (lookup.state === "gateway_error") { + if (gatewayRecovery === "observe") { + return lookup; + } const recoveryGatewayName = targetGatewayName ?? getSandboxTargetGatewayName(); const recovery = await recoverNamedGatewayRuntime({ gatewayName: recoveryGatewayName }); if (recovery.recovered) { @@ -560,9 +566,12 @@ export async function getReconciledSandboxGatewayState( export async function ensureLiveSandboxOrExit( sandboxName: string, - { allowNonReadyPhase = false }: { allowNonReadyPhase?: boolean } = {}, + { + allowNonReadyPhase = false, + gatewayRecovery = "recover", + }: { allowNonReadyPhase?: boolean; gatewayRecovery?: GatewayRecoveryMode } = {}, ): Promise { - const lookup = await getReconciledSandboxGatewayState(sandboxName); + const lookup = await getReconciledSandboxGatewayState(sandboxName, { gatewayRecovery }); if (lookup.state === "present") { const phase = parseSandboxPhase(lookup.output || ""); if (!allowNonReadyPhase && phase && phase !== "Ready" && phase !== "Running") { @@ -635,7 +644,7 @@ export async function ensureLiveSandboxOrExit( } catch { /* best-effort cleanup */ } - const retry = await getReconciledSandboxGatewayState(sandboxName); + const retry = await getReconciledSandboxGatewayState(sandboxName, { gatewayRecovery }); if (retry.state === "present") { console.error(" ✓ Reconnected after clearing stale SSH host keys."); return retry; @@ -666,6 +675,19 @@ export async function ensureLiveSandboxOrExit( ); process.exit(1); } + if (lookup.state === "gateway_error" && gatewayRecovery === "observe") { + console.error( + ` Sandbox '${sandboxName}' cannot be verified: the OpenShell gateway RPC returned an error.`, + ); + if (lookup.output) { + console.error(lookup.output); + } + printGatewayLifecycleHint(lookup.output, sandboxName); + console.error( + ` This sandbox-scoped command will not restart the shared host gateway. Run \`openshell status\` and \`openshell gateway start --name ${getSandboxTargetGatewayName(sandboxName)}\` before retrying.`, + ); + process.exit(1); + } if (lookup.state === "gateway_missing_after_restart") { console.error( ` Sandbox '${sandboxName}' may still exist locally, but the ${CLI_DISPLAY_NAME} gateway is no longer configured after restart/rebuild.`, From 5142c390a465d9f35bb955afb0392b83a1688d09 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sun, 19 Jul 2026 08:28:45 +0000 Subject: [PATCH 2/9] test(cli): update sandbox fixtures for probe-only readiness wait Probe-only connect now waits for sandbox readiness via `openshell sandbox list` before probing. Several pre-existing fake openshell scripts and the shared connect-flow harness only stubbed `sandbox get`, so the new wait hung until timeout. Add matching `sandbox list` stubs, and derive the harness's default list output from the registry entry name instead of hardcoding 'alpha'. The drift-recovery quoting test used a sandbox name containing a literal space, which the whitespace-column `sandbox list` parser can never match; swap it for a hyphen while keeping the apostrophe that the test actually exercises. Signed-off-by: Tinson Lai --- src/lib/actions/sandbox/connect-route-lifecycle.test.ts | 4 ++-- test/cli/connect-recovery-settle.test.ts | 4 ++++ test/cli/connect-recovery.test.ts | 3 +++ test/cli/connect-terminal-agent.test.ts | 4 ++++ test/support/connect-flow-test-harness.ts | 5 ++++- 5 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts index 5c03518db13..da5cd4f7fa6 100644 --- a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts +++ b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts @@ -85,7 +85,7 @@ describe("connectSandbox route lifecycle", () => { }); it("shell-quotes hostile route values in drift recovery commands (#3726)", async () => { - const sandboxName = "alpha's box"; + const sandboxName = "alpha's-box"; const harness = createConnectHarness({ inferenceGetOutput: "Gateway inference:\n Provider: openai; touch /tmp/pwn\n Model: $(id) model\n", @@ -100,7 +100,7 @@ describe("connectSandbox route lifecycle", () => { const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain( - "nemoclaw inference set --provider 'openai; touch /tmp/pwn' --model '$(id) model' --sandbox 'alpha'\\''s box'", + "nemoclaw inference set --provider 'openai; touch /tmp/pwn' --model '$(id) model' --sandbox 'alpha'\\''s-box'", ); }); diff --git a/test/cli/connect-recovery-settle.test.ts b/test/cli/connect-recovery-settle.test.ts index baebe94f1dc..8d5dc369647 100644 --- a/test/cli/connect-recovery-settle.test.ts +++ b/test/cli/connect-recovery-settle.test.ts @@ -39,6 +39,10 @@ describe("CLI dispatch", () => { `state_file=${JSON.stringify(stateFile)}`, `ready_count_file=${JSON.stringify(readyCountFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + " echo 'alpha Ready'", + " exit 0", + "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', " echo 'Sandbox:'", " echo", diff --git a/test/cli/connect-recovery.test.ts b/test/cli/connect-recovery.test.ts index e59d15a3800..09094c2c390 100644 --- a/test/cli/connect-recovery.test.ts +++ b/test/cli/connect-recovery.test.ts @@ -175,6 +175,7 @@ describe("CLI connect recovery process contracts", () => { `marker_file=${JSON.stringify(markerFile)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then echo "alpha Ready"; exit 0; fi', 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", @@ -248,6 +249,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then echo "alpha Ready"; exit 0; fi', 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", @@ -317,6 +319,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then echo "alpha Ready"; exit 0; fi', 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 0172eec8da2..f5490da33fc 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -25,6 +25,10 @@ describe("CLI dispatch for terminal agents", () => { "#!/usr/bin/env bash", `marker_file=${JSON.stringify(markerFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', + 'if [ "$1" = "sandbox" ] && [ "$2" = "list" ]; then', + " echo 'alpha Ready'", + " exit 0", + "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 63b4ef79edf..2ab9188b453 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -134,7 +134,10 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne .mockImplementation((args: unknown) => { const argv = Array.isArray(args) ? args : []; if (argv[0] === "sandbox" && argv[1] === "list") { - return { status: 0, output: options.listOutput ?? "alpha Ready" }; + return { + status: 0, + output: options.listOutput ?? `${options.registryEntry?.name ?? "alpha"} Ready`, + }; } if (argv[0] === "inference" && argv[1] === "get") { return { From 813f3486892ca73c302594a38f7b520ee96ad4d4 Mon Sep 17 00:00:00 2001 From: Tinson Lai Date: Sun, 19 Jul 2026 08:34:49 +0000 Subject: [PATCH 3/9] docs(sandbox): scope host-gateway recovery guidance to openclaw/hermes The host-vs-in-sandbox gateway recovery section referenced an in-sandbox agent gateway unconditionally, but Deep Agents sandboxes have no such gateway. Wrap it in an AgentOnly block and use the variant-aware $$nemoclaw placeholder for the onboarding command. Signed-off-by: Tinson Lai --- docs/manage-sandboxes/recover-rebuild-sandboxes.mdx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 9b727120579..6cb178712cd 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -80,14 +80,16 @@ Use `nemo-deepagents status`, `logs`, `connect`, and `rebuild` fo If the terminal runtime reports degraded health, rebuild the sandbox instead of using `recover` or `gateway restart`. + ### Host OpenShell Gateway Versus In-Sandbox Agent Recovery `recover` and `start` repair the in-sandbox agent gateway and the host-side port forwards for one named sandbox. They do not restart, replace, or reap the shared host OpenShell gateway process. If the host gateway RPC returns an error while these sandbox-scoped commands run, they surface the error with explicit next-step guidance and exit rather than swapping the shared gateway out from under other sandboxes. -To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `nemoclaw onboard` again. +To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `$$nemoclaw onboard` again. Only the onboarding path and `nemoclaw gateway restart` are permitted to reap or replace the shared host gateway. + ## Rebuild While Preserving State From 7b81e32a0c450e442591924d6184a01a730b68a7 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 01:47:41 -0700 Subject: [PATCH 4/9] fix(sandbox): recheck probe target after readiness Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- .../recover-rebuild-sandboxes.mdx | 2 +- .../sandbox/connect-probe-observe.test.ts | 35 ++++++++++++++++--- .../sandbox/connect-route-containment.test.ts | 2 +- src/lib/actions/sandbox/connect.ts | 4 +++ test/support/connect-flow-test-harness.ts | 7 +++- 5 files changed, 42 insertions(+), 8 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 6cb178712cd..68e365845d3 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -88,7 +88,7 @@ They do not restart, replace, or reap the shared host OpenShell gateway process. If the host gateway RPC returns an error while these sandbox-scoped commands run, they surface the error with explicit next-step guidance and exit rather than swapping the shared gateway out from under other sandboxes. To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `$$nemoclaw onboard` again. -Only the onboarding path and `nemoclaw gateway restart` are permitted to reap or replace the shared host gateway. +Only the onboarding path and `$$nemoclaw gateway restart` are permitted to reap or replace the shared host gateway. ## Rebuild While Preserving State diff --git a/src/lib/actions/sandbox/connect-probe-observe.test.ts b/src/lib/actions/sandbox/connect-probe-observe.test.ts index 5b0fb15e6fc..dc23932a94e 100644 --- a/src/lib/actions/sandbox/connect-probe-observe.test.ts +++ b/src/lib/actions/sandbox/connect-probe-observe.test.ts @@ -50,8 +50,16 @@ describe("connectSandbox probe-only observe mode", () => { ); }); - it("polls sandbox readiness before running in-sandbox process recovery on probeOnly", async () => { - const harness = createConnectHarness(); + it("re-observes the live sandbox after delayed readiness before process or forward recovery (#7173)", async () => { + const harness = createConnectHarness({ + listOutputs: ["alpha Starting", "alpha Ready"], + processCheck: { + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: true, + }, + }); await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); @@ -65,10 +73,27 @@ describe("connectSandbox probe-only observe mode", () => { ); }, ); - expect(listInvocations.length).toBeGreaterThan(0); + expect(listInvocations).toHaveLength(2); + const liveLookupOrder = harness.ensureLiveSandboxSpy.mock.invocationCallOrder; + expect(liveLookupOrder).toHaveLength(2); const recoveryOrder = harness.checkAndRecoverSpy.mock.invocationCallOrder; - expect(recoveryOrder.length).toBeGreaterThan(0); - expect(listInvocations[0]).toBeLessThan(recoveryOrder[0]); + expect(recoveryOrder).toHaveLength(1); + expect(listInvocations[1]).toBeLessThan(liveLookupOrder[1]); + expect(liveLookupOrder[1]).toBeLessThan(recoveryOrder[0]); + expect(harness.logSpy).toHaveBeenCalledWith( + expect.stringContaining("restored dashboard port forward"), + ); + }); + + it("does not run process or forward recovery for a terminal sandbox phase (#7173)", async () => { + const harness = createConnectHarness({ listOutput: "alpha Error" }); + + await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( + "process.exit(1)", + ); + + expect(harness.ensureLiveSandboxSpy).toHaveBeenCalledOnce(); + expect(harness.checkAndRecoverSpy).not.toHaveBeenCalled(); }); it("exits on timeout when sandbox never reports Ready on probeOnly", async () => { diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index 830e449ebd3..87521d8f031 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -102,7 +102,7 @@ describe("connect route containment", () => { await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); - expect(harness.ensureLiveSandboxSpy).toHaveBeenCalledOnce(); + expect(harness.ensureLiveSandboxSpy).toHaveBeenCalledTimes(2); expect(harness.checkAndRecoverSpy).toHaveBeenCalled(); expect(harness.captureOpenshellSpy).toHaveBeenCalled(); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 36d05dd4a98..9d800c289a9 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -1088,6 +1088,10 @@ export async function connectSandbox( if (probeOnly) { waitForSandboxReadyOrExit(sandboxName, { defaultTimeoutSec: 300 }); + // `sandbox list` uses OpenShell's process-global gateway selection. Re-pin + // and re-observe the owning gateway after a potentially long wait before + // any in-sandbox process or host-forward mutation. + await ensureLiveSandboxOrExit(sandboxName, { gatewayRecovery: "observe" }); return await runSandboxConnectProbe(sandboxName); } diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 2ab9188b453..c7fac4ffbdc 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -54,6 +54,7 @@ export type ConnectHarnessOptions = { registryEntries?: Array & Pick>; sessionAgent?: unknown; listOutput?: string; + listOutputs?: string[]; processCheck?: { checked: boolean; wasRunning?: boolean; @@ -129,6 +130,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne }); vi.spyOn(gatewayFailureClassifier, "isDockerRuntimeDown").mockReturnValue(false); const inferenceProbeResponses = [...(options.inferenceProbeResponses ?? [])]; + const listOutputs = [...(options.listOutputs ?? [])]; const captureOpenshellSpy = vi .spyOn(runtime, "captureOpenshell") .mockImplementation((args: unknown) => { @@ -136,7 +138,10 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne if (argv[0] === "sandbox" && argv[1] === "list") { return { status: 0, - output: options.listOutput ?? `${options.registryEntry?.name ?? "alpha"} Ready`, + output: + listOutputs.shift() ?? + options.listOutput ?? + `${options.registryEntry?.name ?? "alpha"} Ready`, }; } if (argv[0] === "inference" && argv[1] === "get") { From 5fd4f7928db3072deb6f58a0afa1de613a33bd75 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 02:09:41 -0700 Subject: [PATCH 5/9] docs(sandbox): document probe readiness boundary Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- docs/manage-sandboxes/recover-rebuild-sandboxes.mdx | 3 ++- docs/reference/commands.mdx | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 68e365845d3..1f4040c3042 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -84,7 +84,8 @@ If the terminal runtime reports degraded health, rebuild the sandbox instead of ### Host OpenShell Gateway Versus In-Sandbox Agent Recovery `recover` and `start` repair the in-sandbox agent gateway and the host-side port forwards for one named sandbox. -They do not restart, replace, or reap the shared host OpenShell gateway process. +`connect --probe-only` waits for that sandbox to become ready, rechecks it on its recorded gateway, and then verifies or repairs the same sandbox-scoped processes and forwards. +These commands do not restart, replace, or reap the shared host OpenShell gateway process. If the host gateway RPC returns an error while these sandbox-scoped commands run, they surface the error with explicit next-step guidance and exit rather than swapping the shared gateway out from under other sandboxes. To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `$$nemoclaw onboard` again. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0e8c3fed80f..0ab334c8aa1 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -821,7 +821,7 @@ If only pending registrations remain, the command exits non-zero and tells you t If the registry remains empty after recovery, it tells you to run `$$nemoclaw onboard`. A registered sandbox literally named `connect` keeps the name-first reading. If the sandbox is not yet in the `Ready` phase, `connect` polls `openshell sandbox list` every few seconds and prints the current phase. This gives you progress output right after onboarding, when the 2.4 GB image is still pulling, instead of a silent hang. -Control the wait budget with `NEMOCLAW_CONNECT_TIMEOUT` (integer seconds, default `120`). When the deadline expires, `connect` exits non-zero with the last-seen phase. +Control the wait budget with `NEMOCLAW_CONNECT_TIMEOUT` in integer seconds. An interactive connection defaults to `120` seconds, while `--probe-only` defaults to `300` seconds so a scripted health check can wait through a cold sandbox start. When the deadline expires, `connect` exits non-zero with the last-seen phase. On a TTY, a one-shot hint prints before dropping into the sandbox shell. The hint is agent-aware. It names the correct TUI command for the sandbox's agent and reminds you to use `/exit` to leave the chat before `exit` returns you to the host shell. @@ -853,7 +853,8 @@ $$nemoclaw my-assistant connect [--probe-only] $$nemoclaw connect ``` -The `--probe-only` flag verifies the sandbox is reachable over SSH and exits without opening a shell. +The `--probe-only` flag waits for the sandbox to become ready, verifies or repairs its in-sandbox agent process and host-side forward, and exits without opening a shell. +It rechecks the sandbox on its recorded OpenShell gateway after the readiness wait and never restarts the shared host gateway. Use it for health checks and scripted readiness probes. ### `$$nemoclaw exec` From 67ebc872b10a633e4eca190d3ce7b74ec9d6f7f2 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 05:00:15 -0700 Subject: [PATCH 6/9] fix(sandbox): pin readiness polls to owning gateway Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- .../sandbox/connect-probe-observe.test.ts | 18 ++++++++++--- src/lib/actions/sandbox/connect.ts | 27 ++++++++++++++----- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/lib/actions/sandbox/connect-probe-observe.test.ts b/src/lib/actions/sandbox/connect-probe-observe.test.ts index dc23932a94e..ab9ad99642d 100644 --- a/src/lib/actions/sandbox/connect-probe-observe.test.ts +++ b/src/lib/actions/sandbox/connect-probe-observe.test.ts @@ -52,6 +52,7 @@ describe("connectSandbox probe-only observe mode", () => { it("re-observes the live sandbox after delayed readiness before process or forward recovery (#7173)", async () => { const harness = createConnectHarness({ + registryEntry: { gatewayPort: 8091 }, listOutputs: ["alpha Starting", "alpha Ready"], processCheck: { checked: true, @@ -74,6 +75,16 @@ describe("connectSandbox probe-only observe mode", () => { }, ); expect(listInvocations).toHaveLength(2); + const listArgs = harness.captureOpenshellSpy.mock.calls + .map((call) => call[0]) + .filter( + (args): args is string[] => + Array.isArray(args) && args[0] === "sandbox" && args[1] === "list", + ); + expect(listArgs).toEqual([ + ["sandbox", "list", "-g", "nemoclaw-8091"], + ["sandbox", "list", "-g", "nemoclaw-8091"], + ]); const liveLookupOrder = harness.ensureLiveSandboxSpy.mock.invocationCallOrder; expect(liveLookupOrder).toHaveLength(2); const recoveryOrder = harness.checkAndRecoverSpy.mock.invocationCallOrder; @@ -96,8 +107,8 @@ describe("connectSandbox probe-only observe mode", () => { expect(harness.checkAndRecoverSpy).not.toHaveBeenCalled(); }); - it("exits on timeout when sandbox never reports Ready on probeOnly", async () => { - process.env.NEMOCLAW_CONNECT_TIMEOUT = "1"; + it("suggests a longer equivalent retry when probe-only readiness times out", async () => { + vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValue(300_001); const harness = createConnectHarness({ listOutput: "alpha Starting" }); await expect(harness.connectSandbox("alpha", { probeOnly: true })).rejects.toThrow( @@ -105,6 +116,7 @@ describe("connectSandbox probe-only observe mode", () => { ); const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"); - expect(errors).toContain("Timed out after 1s waiting for sandbox 'alpha'"); + expect(errors).toContain("Timed out after 300s waiting for sandbox 'alpha'"); + expect(errors).toContain("NEMOCLAW_CONNECT_TIMEOUT=600 nemoclaw alpha connect --probe-only"); }); }); diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 9d800c289a9..6b8c97c336d 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -928,12 +928,17 @@ function exitWithConnectSpawnResult(sandboxName: string, result: SpawnLikeResult type WaitForSandboxReadyOptions = { defaultTimeoutSec?: number; + retryCommand?: string; successLogs?: readonly string[]; }; function waitForSandboxReadyOrExit( sandboxName: string, - { defaultTimeoutSec = 120, successLogs = [] }: WaitForSandboxReadyOptions = {}, + { + defaultTimeoutSec = 120, + retryCommand = "connect", + successLogs = [], + }: WaitForSandboxReadyOptions = {}, ): void { const rawTimeout = process.env.NEMOCLAW_CONNECT_TIMEOUT; let timeout = defaultTimeoutSec; @@ -950,10 +955,14 @@ function waitForSandboxReadyOrExit( const interval = 3; const startedAt = Date.now(); const deadline = startedAt + timeout * 1000; + const gatewayName = getSandboxTargetGatewayName(sandboxName); const elapsedSec = () => Math.floor((Date.now() - startedAt) / 1000); const remainingMs = () => Math.max(1, deadline - Date.now()); const runSandboxList = (): SandboxListProbe => { - const result = captureOpenshell(["sandbox", "list"], { + // Gateway selection is process-global and another CLI can change it while + // this command waits. Pin each poll to the registry-recorded owner so a + // same-named sandbox on a sibling gateway cannot satisfy readiness. + const result = captureOpenshell(["sandbox", "list", "-g", gatewayName], { ignoreError: true, timeout: remainingMs(), }); @@ -1027,11 +1036,12 @@ function waitForSandboxReadyOrExit( } if (!ready) { + const suggestedTimeout = Math.max(300, timeout * 2); console.error(""); console.error(` Timed out after ${timeout}s waiting for sandbox '${sandboxName}'.`); console.error(" Check: openshell sandbox list"); console.error( - ` Override timeout: NEMOCLAW_CONNECT_TIMEOUT=300 ${CLI_NAME} ${sandboxName} connect`, + ` Override timeout: NEMOCLAW_CONNECT_TIMEOUT=${suggestedTimeout} ${CLI_NAME} ${sandboxName} ${retryCommand}`, ); process.exit(1); } @@ -1087,10 +1097,13 @@ export async function connectSandbox( } if (probeOnly) { - waitForSandboxReadyOrExit(sandboxName, { defaultTimeoutSec: 300 }); - // `sandbox list` uses OpenShell's process-global gateway selection. Re-pin - // and re-observe the owning gateway after a potentially long wait before - // any in-sandbox process or host-forward mutation. + waitForSandboxReadyOrExit(sandboxName, { + defaultTimeoutSec: 300, + retryCommand: "connect --probe-only", + }); + // Re-pin and re-observe the owning gateway after a potentially long wait + // before any in-sandbox process or host-forward mutation. The readiness + // polls are already owner-scoped; this also catches registry changes. await ensureLiveSandboxOrExit(sandboxName, { gatewayRecovery: "observe" }); return await runSandboxConnectProbe(sandboxName); } From 9e4bf99bf8c52d1874084ed633811285a161580c Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 05:05:54 -0700 Subject: [PATCH 7/9] docs(sandbox): clarify host gateway recovery boundary Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- docs/manage-sandboxes/recover-rebuild-sandboxes.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 1f4040c3042..2dea8ec118e 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -89,7 +89,8 @@ These commands do not restart, replace, or reap the shared host OpenShell gatewa If the host gateway RPC returns an error while these sandbox-scoped commands run, they surface the error with explicit next-step guidance and exit rather than swapping the shared gateway out from under other sandboxes. To repair the host gateway itself, use `openshell status`, `openshell gateway start --name `, or run `$$nemoclaw onboard` again. -Only the onboarding path and `$$nemoclaw gateway restart` are permitted to reap or replace the shared host gateway. +Other workflows, including onboarding, rebuild, and `doctor --fix`, can explicitly recover the named host gateway when their operation requires it. +`$$nemoclaw gateway restart` instead restarts only the supported agent gateway inside the named sandbox. ## Rebuild While Preserving State From 9b47d01428b3a623eec3f1e21ea54ecd4870d83a Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 05:09:30 -0700 Subject: [PATCH 8/9] test(sandbox): assert timeout avoids recovery Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- src/lib/actions/sandbox/connect-probe-observe.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/actions/sandbox/connect-probe-observe.test.ts b/src/lib/actions/sandbox/connect-probe-observe.test.ts index ab9ad99642d..64bbe6f0b1b 100644 --- a/src/lib/actions/sandbox/connect-probe-observe.test.ts +++ b/src/lib/actions/sandbox/connect-probe-observe.test.ts @@ -118,5 +118,6 @@ describe("connectSandbox probe-only observe mode", () => { const errors = harness.errorSpy.mock.calls.map((call) => String(call[0])).join("\n"); expect(errors).toContain("Timed out after 300s waiting for sandbox 'alpha'"); expect(errors).toContain("NEMOCLAW_CONNECT_TIMEOUT=600 nemoclaw alpha connect --probe-only"); + expect(harness.checkAndRecoverSpy).not.toHaveBeenCalled(); }); }); From 74700b280747d8fc4eff9e778a252674cf140ab8 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 19 Jul 2026 05:37:33 -0700 Subject: [PATCH 9/9] test(sandbox): cover gateway-scoped readiness polls Co-authored-by: Tinson Lai Signed-off-by: Apurv Kumaria --- src/lib/actions/sandbox/connect-flow.test.ts | 2 +- test/cli/connect-readiness.test.ts | 6 ++++-- test/cli/dispatch-basics.test.ts | 5 ++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index d159758bf8e..630fa515308 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -54,7 +54,7 @@ describe("connectSandbox flow", () => { await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(0)"); expect(harness.captureOpenshellSpy).toHaveBeenCalledWith( - ["sandbox", "list"], + ["sandbox", "list", "-g", "nemoclaw"], expect.objectContaining({ ignoreError: true }), ); expect(harness.checkAndRecoverSpy).toHaveBeenCalledWith("alpha"); diff --git a/test/cli/connect-readiness.test.ts b/test/cli/connect-readiness.test.ts index 3cb523c8e98..27c981f9513 100644 --- a/test/cli/connect-readiness.test.ts +++ b/test/cli/connect-readiness.test.ts @@ -98,7 +98,9 @@ describe("CLI connect readiness", () => { expect(r.out.includes("Sandbox is ready. Connecting")).toBeTruthy(); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); expect(calls).toContain("sandbox get alpha"); - expect(calls.filter((call) => call === "sandbox list").length).toBeGreaterThanOrEqual(2); + expect( + calls.filter((call) => call === "sandbox list -g nemoclaw").length, + ).toBeGreaterThanOrEqual(2); expect(calls).toContain("sandbox connect alpha"); }); @@ -252,7 +254,7 @@ describe("CLI connect readiness", () => { expect(r.out.includes("nemoclaw alpha status")).toBeTruthy(); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); expect(calls).toContain("sandbox get alpha"); - expect(calls).toContain("sandbox list"); + expect(calls).toContain("sandbox list -g nemoclaw"); expect(calls).not.toContain("should-not-connect"); }); }); diff --git a/test/cli/dispatch-basics.test.ts b/test/cli/dispatch-basics.test.ts index 4959e57ab00..28a09777b39 100644 --- a/test/cli/dispatch-basics.test.ts +++ b/test/cli/dispatch-basics.test.ts @@ -412,7 +412,7 @@ describe("CLI dispatch", () => { 'case "$*" in', ' "status") printf "Status: Connected\\nGateway: nemoclaw\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', - ' "sandbox list") echo "liost Ready"; exit 0 ;;', + ' "sandbox list"*) echo "liost Ready"; exit 0 ;;', ' "sandbox get liost") printf "Name: liost\\nPhase: Ready\\nPolicy:\\n"; exit 0 ;;', ' "policy get --full liost") exit 1 ;;', ' "inference get") exit 1 ;;', @@ -432,6 +432,9 @@ describe("CLI dispatch", () => { expect(r.code).toBe(0); expect(r.out).toContain("CONNECTED_LIOST"); expect(r.out).not.toContain("Unknown command: liost"); + const calls = fs.readFileSync(path.join(home, "openshell-calls.log"), "utf8").split("\n"); + expect(calls).toContain("sandbox list"); + expect(calls).toContain("sandbox list -g nemoclaw"); }); it("fails fast on gated NEMOCLAW_VLLM_MODEL without HF token before sandbox side effects", () => {