diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index cfbe1eab2a2..2dea8ec118e 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -80,6 +80,19 @@ 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. +`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. +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 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` 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/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..64bbe6f0b1b --- /dev/null +++ b/src/lib/actions/sandbox/connect-probe-observe.test.ts @@ -0,0 +1,123 @@ +// 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("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, + wasRunning: true, + recovered: false, + forwardRecovered: true, + }, + }); + + 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).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; + 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("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( + "process.exit(1)", + ); + + 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(); + }); +}); diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index 9f816f801b5..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( @@ -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-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/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index ed71dae1cb9..6b8c97c336d 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -926,6 +926,129 @@ function exitWithConnectSpawnResult(sandboxName: string, result: SpawnLikeResult process.exit(spawnExitCode(result)); } +type WaitForSandboxReadyOptions = { + defaultTimeoutSec?: number; + retryCommand?: string; + successLogs?: readonly string[]; +}; + +function waitForSandboxReadyOrExit( + sandboxName: string, + { + defaultTimeoutSec = 120, + retryCommand = "connect", + 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 gatewayName = getSandboxTargetGatewayName(sandboxName); + const elapsedSec = () => Math.floor((Date.now() - startedAt) / 1000); + const remainingMs = () => Math.max(1, deadline - Date.now()); + const runSandboxList = (): SandboxListProbe => { + // 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(), + }); + 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) { + 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=${suggestedTimeout} ${CLI_NAME} ${sandboxName} ${retryCommand}`, + ); + 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 +1073,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 +1097,14 @@ export async function connectSandbox( } if (probeOnly) { + 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); } @@ -1016,119 +1150,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.`, 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/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/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", () => { diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index 63b4ef79edf..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,12 +130,19 @@ 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) => { 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: + listOutputs.shift() ?? + options.listOutput ?? + `${options.registryEntry?.name ?? "alpha"} Ready`, + }; } if (argv[0] === "inference" && argv[1] === "get") { return {