diff --git a/src/lib/actions/sandbox/exec-gateway-target.test.ts b/src/lib/actions/sandbox/exec-gateway-target.test.ts new file mode 100644 index 00000000000..5d0a88c58f8 --- /dev/null +++ b/src/lib/actions/sandbox/exec-gateway-target.test.ts @@ -0,0 +1,255 @@ +// 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 { execSandbox, type SandboxExecCleanupDeps } from "./exec"; + +const cleanupSkipped: SandboxExecCleanupDeps = { + getSandbox: () => null, + inspectMutableConfigPerms: (() => { + throw new Error("cleanup should be skipped"); + }) as unknown as SandboxExecCleanupDeps["inspectMutableConfigPerms"], + repairMutableConfigPerms: (() => { + throw new Error("cleanup should be skipped"); + }) as unknown as SandboxExecCleanupDeps["repairMutableConfigPerms"], +}; + +describe("execSandbox gateway targeting", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it("selects the sandbox's owning gateway before dispatching the exec", async () => { + const order: string[] = []; + const selectGateway = vi.fn((name: string) => { + order.push(`select:${name}`); + return { outcome: "selected" as const, gatewayName: name }; + }); + const run = vi.fn(async (_binary: string, _args: readonly string[]) => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + {}, + { + resolveBinary: () => "openshell", + selectGateway, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + }, + ), + ).rejects.toThrow("__exit_0__"); + + expect(selectGateway).toHaveBeenCalledWith("beta"); + expect(run).toHaveBeenCalled(); + const execArgs = run.mock.calls[0]?.[1] ?? []; + expect(execArgs.slice(0, 7)).toEqual(["sandbox", "exec", "--name", "beta", "-g", "beta", "--"]); + expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); + expect(execArgs.at(-1)).toBe("hostname"); + expect(order.indexOf("select:beta")).toBeGreaterThanOrEqual(0); + expect(order.indexOf("select:beta")).toBeLessThan(order.indexOf("run")); + }); + + it("selects the owning gateway before the workdir probe when a workdir is set", async () => { + const order: string[] = []; + vi.stubEnv("OPENSHELL_GATEWAY", "ambient-sibling"); + const selectGateway = vi.fn((name: string) => { + order.push(`select:${name}`); + process.env.OPENSHELL_GATEWAY = "drifted-sibling"; + return { outcome: "selected" as const, gatewayName: "nemoclaw-8091" }; + }); + const probeWorkdir = vi.fn((_binary: string, _args: readonly string[]) => { + order.push("probe"); + return { status: 0, error: undefined }; + }); + const run = vi.fn(async (_binary: string, _args: readonly string[]) => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + probeLogs: () => "", + enableAudit: () => {}, + sleep: async () => {}, + attempts: 1, + writeStderr: () => {}, + }, + }, + ), + ).rejects.toThrow("__exit_0__"); + + expect(order).toEqual(["select:beta", "probe", "run"]); + expect(process.env.OPENSHELL_GATEWAY).toBe("drifted-sibling"); + expect(probeWorkdir.mock.calls[0]?.[1]).toEqual([ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--", + "test", + "-d", + "/work", + ]); + const execArgs = run.mock.calls[0]?.[1] ?? []; + expect(execArgs.slice(0, 9)).toEqual([ + "sandbox", + "exec", + "--name", + "beta", + "-g", + "nemoclaw-8091", + "--workdir", + "/work", + "--", + ]); + expect(execArgs.at(-2)).toBe("nemoclaw-runtime-env"); + expect(execArgs.at(-1)).toBe("hostname"); + }); + + it("rejects a direct endpoint override before selecting, probing, or dispatching", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); + const resolveBinary = vi.fn(() => "openshell"); + const selectGateway = vi.fn(); + const probeWorkdir = vi.fn(); + const run = vi.fn(); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { resolveBinary, selectGateway, probeWorkdir, run }, + ), + ).rejects.toThrow("__exit_1__"); + + expect(console.error).toHaveBeenCalledWith( + expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), + ); + expect(resolveBinary).not.toHaveBeenCalled(); + expect(selectGateway).not.toHaveBeenCalled(); + expect(probeWorkdir).not.toHaveBeenCalled(); + expect(run).not.toHaveBeenCalled(); + }); + + it("keeps post-exec policy probes pinned after ambient gateway selection drifts", async () => { + vi.stubEnv("OPENSHELL_GATEWAY", "ambient-sibling"); + const enableAudit = vi.fn(); + const probeLogs = vi.fn(() => ""); + const selectGateway = vi.fn(() => { + process.env.OPENSHELL_GATEWAY = "drifted-sibling"; + return { outcome: "selected" as const, gatewayName: "nemoclaw-8091" }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["curl", "https://example.invalid"], + {}, + { + resolveBinary: () => "openshell", + selectGateway, + run: async () => ({ status: 56 }), + cleanupDeps: cleanupSkipped, + policyHint: { + now: () => 0, + env: {}, + enableAudit, + probeLogs, + attempts: 1, + sleep: async () => {}, + writeStderr: () => {}, + }, + }, + ), + ).rejects.toThrow("__exit_56__"); + + expect(process.env.OPENSHELL_GATEWAY).toBe("drifted-sibling"); + expect(enableAudit).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(probeLogs).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + }); + + it("aborts before the workdir probe and exec when gateway selection fails", async () => { + const order: string[] = []; + const selectGateway = vi.fn(() => { + order.push("select"); + return { outcome: "failed" as const, gatewayName: "nemoclaw-8091" }; + }); + const probeWorkdir = vi.fn(() => { + order.push("probe"); + return { status: 0, error: undefined }; + }); + const run = vi.fn(async () => { + order.push("run"); + return { status: 0 }; + }); + vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`__exit_${code ?? 0}__`); + }) as never); + vi.spyOn(console, "error").mockImplementation(() => undefined); + + await expect( + execSandbox( + "beta", + ["hostname"], + { workdir: "/work" }, + { + resolveBinary: () => "openshell", + selectGateway, + probeWorkdir, + run, + cleanupDeps: cleanupSkipped, + }, + ), + ).rejects.toThrow("__exit_1__"); + + expect(order).toEqual(["select"]); + expect(probeWorkdir).not.toHaveBeenCalled(); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/actions/sandbox/exec-policy-hint-emission.ts b/src/lib/actions/sandbox/exec-policy-hint-emission.ts index d1e2d0944d2..e795fa3df38 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-emission.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-emission.ts @@ -20,8 +20,8 @@ export const POLICY_HINT_PROBE_ATTEMPTS = 3; export const POLICY_HINT_PROBE_RETRY_MS = 120; export const POLICY_HINT_MAX_RUNTIME_TIMEOUT_MS = 1_000; -export type PolicyDenialLogProbe = (sandboxName: string) => string; -export type PolicyDenialAuditEnabler = (sandboxName: string) => void; +export type PolicyDenialLogProbe = (sandboxName: string, gatewayName?: string) => string; +export type PolicyDenialAuditEnabler = (sandboxName: string, gatewayName?: string) => void; export type PolicyDenialHintDeps = { probeLogs?: PolicyDenialLogProbe; @@ -45,8 +45,8 @@ function runtimeTimeoutMs(): number { return Math.min(getLogsProbeTimeoutMs(), POLICY_HINT_MAX_RUNTIME_TIMEOUT_MS); } -function defaultEnableAudit(sandboxName: string): void { - const result = captureOpenshell(buildEnableSandboxAuditLogsArgs(sandboxName), { +function defaultEnableAudit(sandboxName: string, gatewayName?: string): void { + const result = captureOpenshell(buildEnableSandboxAuditLogsArgs(sandboxName, gatewayName), { ignoreError: true, includeStderr: true, timeout: runtimeTimeoutMs(), @@ -56,13 +56,13 @@ function defaultEnableAudit(sandboxName: string): void { } } -function defaultProbeLogs(sandboxName: string): string { +function defaultProbeLogs(sandboxName: string, gatewayName?: string): string { const options: SandboxLogsOptions = { follow: false, lines: String(POLICY_HINT_TAIL_LINES), since: null, }; - const result = captureOpenshell(buildSandboxLogsArgs(sandboxName, options), { + const result = captureOpenshell(buildSandboxLogsArgs(sandboxName, options, gatewayName), { ignoreError: true, includeStderr: true, timeout: runtimeTimeoutMs(), @@ -90,6 +90,7 @@ export async function maybeEmitPolicyDenialHint( hadInvocationError: boolean, commandStartedAtMs: number, deps: PolicyDenialHintDeps = {}, + gatewayName?: string, ): Promise { const env = deps.env ?? process.env; if (!shouldProbePolicyDenial(commandCode, hadInvocationError, env)) return null; @@ -101,7 +102,7 @@ export async function maybeEmitPolicyDenialHint( const retryDelayMs = deps.retryDelayMs ?? POLICY_HINT_PROBE_RETRY_MS; try { - enableAudit(sandboxName); + enableAudit(sandboxName, gatewayName); } catch { // Deliberately silent: audit setup is optional and retained logs may still // contain the denial. Printing this diagnostic, even under a new debug @@ -112,7 +113,7 @@ export async function maybeEmitPolicyDenialHint( for (let attempt = 1; attempt <= attempts; attempt += 1) { let logOutput: string; try { - logOutput = probeLogs(sandboxName); + logOutput = probeLogs(sandboxName, gatewayName); } catch { // Deliberately silent for the same output-preservation boundary: a failed // optional probe must not append host diagnostics to the child's error. diff --git a/src/lib/actions/sandbox/exec-policy-hint-integration.ts b/src/lib/actions/sandbox/exec-policy-hint-integration.ts index 7f0d913bee3..f8ffb256707 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-integration.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-integration.ts @@ -21,6 +21,7 @@ export function preparePolicyHint( cliName: string, sandboxName: string, deps: ExecPolicyHintDeps = {}, + gatewayName?: string, ): (completion: ExecPolicyDenialHintCompletion) => Promise { const { now = Date.now, ...hintDeps } = deps; const commandStartedAtMs = now(); @@ -32,6 +33,7 @@ export function preparePolicyHint( Boolean(completion.invocationError), commandStartedAtMs, hintDeps, + gatewayName, ); }; } diff --git a/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts b/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts index ef68c01610a..a07f542769c 100644 --- a/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts +++ b/src/lib/actions/sandbox/exec-policy-hint-runtime.test.ts @@ -39,11 +39,22 @@ describe("policy-denial hint runtime adapter integration (#5978)", () => { env: {}, writeStderr: (line) => stderr.push(line), }, + "nemoclaw-8091", ); expect(captureOpenshell).toHaveBeenNthCalledWith( 1, - ["settings", "set", "runtime-sandbox", "--key", "ocsf_json_enabled", "--value", "true"], + [ + "settings", + "set", + "-g", + "nemoclaw-8091", + "runtime-sandbox", + "--key", + "ocsf_json_enabled", + "--value", + "true", + ], expect.objectContaining({ ignoreError: true, includeStderr: true, @@ -52,7 +63,16 @@ describe("policy-denial hint runtime adapter integration (#5978)", () => { ); expect(captureOpenshell).toHaveBeenNthCalledWith( 2, - ["logs", "runtime-sandbox", "-n", String(POLICY_HINT_TAIL_LINES), "--source", "all"], + [ + "logs", + "-g", + "nemoclaw-8091", + "runtime-sandbox", + "-n", + String(POLICY_HINT_TAIL_LINES), + "--source", + "all", + ], expect.objectContaining({ ignoreError: true, includeStderr: true, diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts index e578f853b2a..e9c220fdfe7 100644 --- a/src/lib/actions/sandbox/exec.ts +++ b/src/lib/actions/sandbox/exec.ts @@ -3,6 +3,7 @@ import { spawn, spawnSync } from "node:child_process"; import { spawnExitCode } from "../../core/process-exit"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import type { MutableConfigPermsInspection, MutableConfigRepairResult, @@ -10,6 +11,7 @@ import type { import type { SandboxEntry } from "../../state/registry"; import { type ExecPolicyHintDeps, preparePolicyHint } from "./exec-policy-hint-integration"; import { buildSandboxExecStdio } from "./exec-stdio"; +import type { GatewaySelectResult } from "./gateway-select"; import { wrapExecCommandWithRuntimeEnv } from "./runtime-env"; export { buildSandboxExecStdio, shouldInheritSandboxExecStdin } from "./exec-stdio"; @@ -84,8 +86,10 @@ export function buildOpenshellExecArgs( sandboxName: string, command: readonly string[], options: SandboxExecOptions = {}, + gatewayName?: string, ): string[] { const argv = ["sandbox", "exec", "--name", sandboxName]; + if (gatewayName) argv.push("-g", gatewayName); if (options.workdir) argv.push("--workdir", options.workdir); if (options.tty === true) argv.push("--tty"); if (options.tty === false) argv.push("--no-tty"); @@ -96,8 +100,15 @@ export function buildOpenshellExecArgs( return argv; } -export function buildWorkdirProbeArgs(sandboxName: string, workdir: string): string[] { - return ["sandbox", "exec", "--name", sandboxName, "--", "test", "-d", workdir]; +export function buildWorkdirProbeArgs( + sandboxName: string, + workdir: string, + gatewayName?: string, +): string[] { + const argv = ["sandbox", "exec", "--name", sandboxName]; + if (gatewayName) argv.push("-g", gatewayName); + argv.push("--", "test", "-d", workdir); + return argv; } // OpenShell accepts LF/CR in command argv while retaining field-specific @@ -281,10 +292,11 @@ export async function runSandboxExecCommand( options: SandboxExecOptions, run: SandboxExecRunner, cleanupDeps: SandboxExecCleanupDeps, + gatewayName?: string, ): Promise { let result: SpawnLikeResult; try { - result = await run(binary, buildOpenshellExecArgs(sandboxName, command, options)); + result = await run(binary, buildOpenshellExecArgs(sandboxName, command, options, gatewayName)); } catch (error) { result = { status: null, error: error instanceof Error ? error : new Error(String(error)) }; } @@ -316,8 +328,11 @@ export function validateWorkdirOrFail( sandboxName: string, workdir: string, run: WorkdirProbeRunner = defaultWorkdirProbeRunner, + gatewayName?: string, ): void { - const outcome = evaluateWorkdirProbe(run(binary, buildWorkdirProbeArgs(sandboxName, workdir))); + const outcome = evaluateWorkdirProbe( + run(binary, buildWorkdirProbeArgs(sandboxName, workdir, gatewayName)), + ); if (outcome === "missing") { console.error(workdirMissingMessage(workdir)); process.exit(1); @@ -329,6 +344,12 @@ function defaultResolveBinary(): string { return getOpenshellBinary(); } +function defaultSelectGateway(sandboxName: string): GatewaySelectResult { + return ( + require("./gateway-select") as typeof import("./gateway-select") + ).selectSandboxOwningGateway(sandboxName); +} + // Test seams for execSandbox. All default to the production behavior; tests // inject them so the dispatch path stays hermetic without spawning a real // process or hitting the process-exiting OpenShell binary lookup. @@ -340,6 +361,8 @@ export type ExecSandboxDeps = { run?: SandboxExecRunner; policyHint?: ExecPolicyHintDeps; cleanupDeps?: SandboxExecCleanupDeps; + /** Select the sandbox's owning gateway before the exec talks to OpenShell. */ + selectGateway?: (sandboxName: string) => GatewaySelectResult; }; export async function execSandbox( @@ -360,11 +383,31 @@ export async function execSandbox( console.error(inputError); process.exit(2); } + try { + assertNoOpenShellGatewayEndpointOverride(); + } catch (error) { + console.error(` Error: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); + } const binary = (deps.resolveBinary ?? defaultResolveBinary)(); + const gatewaySelection = (deps.selectGateway ?? defaultSelectGateway)(sandboxName); + if (gatewaySelection.outcome === "failed") { + console.error( + ` Failed to select gateway '${gatewaySelection.gatewayName}' for sandbox '${sandboxName}'.`, + ); + process.exit(1); + } + const gatewayName = + gatewaySelection.outcome === "selected" ? gatewaySelection.gatewayName : undefined; if (options.workdir) { - validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir); + validateWorkdirOrFail(binary, sandboxName, options.workdir, deps.probeWorkdir, gatewayName); } - const emitPolicyDenialHint = preparePolicyHint(CLI_NAME, sandboxName, deps.policyHint); + const emitPolicyDenialHint = preparePolicyHint( + CLI_NAME, + sandboxName, + deps.policyHint, + gatewayName, + ); const completion = await runSandboxExecCommand( binary, sandboxName, @@ -381,6 +424,7 @@ export async function execSandbox( repairMutableConfigPerms: (name) => (require("../../shields") as typeof import("../../shields")).repairMutableConfigPerms(name), }, + gatewayName, ); if (completion.invocationError) { console.error(` Failed to invoke openshell: ${completion.invocationError}`); diff --git a/src/lib/actions/sandbox/gateway-select.test.ts b/src/lib/actions/sandbox/gateway-select.test.ts new file mode 100644 index 00000000000..488dd1d7456 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-select.test.ts @@ -0,0 +1,68 @@ +// 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 * as registry from "../../state/registry"; +import { selectSandboxOwningGateway } from "./gateway-select"; + +describe("selectSandboxOwningGateway", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("selects the owning non-default gateway for a registered sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: 0 }) as never); + + const selected = selectSandboxOwningGateway("beta", run); + + expect(selected).toEqual({ outcome: "selected", gatewayName: "nemoclaw-8091" }); + expect(run).toHaveBeenCalledWith( + ["gateway", "select", "nemoclaw-8091"], + expect.objectContaining({ ignoreError: true }), + ); + }); + + it("keeps the bare default gateway name for a default-port sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8080 } as never); + const run = vi.fn(() => ({ status: 0 }) as never); + + expect(selectSandboxOwningGateway("alpha", run)).toEqual({ + outcome: "selected", + gatewayName: "nemoclaw", + }); + expect(run).toHaveBeenCalledWith(["gateway", "select", "nemoclaw"], expect.anything()); + }); + + it("does not touch the active gateway for an unregistered sandbox", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + const run = vi.fn(() => ({ status: 0 }) as never); + + expect(selectSandboxOwningGateway("ghost", run)).toEqual({ + outcome: "unregistered", + gatewayName: null, + }); + expect(run).not.toHaveBeenCalled(); + }); + + it("reports failure when the gateway select command exits nonzero", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: 1 }) as never); + + expect(selectSandboxOwningGateway("beta", run)).toEqual({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + }); + + it("reports failure when the gateway select command errors on spawn", () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const run = vi.fn(() => ({ status: null, error: new Error("spawn failed") }) as never); + + expect(selectSandboxOwningGateway("beta", run)).toEqual({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + }); +}); diff --git a/src/lib/actions/sandbox/gateway-select.ts b/src/lib/actions/sandbox/gateway-select.ts new file mode 100644 index 00000000000..ef2e0aa576c --- /dev/null +++ b/src/lib/actions/sandbox/gateway-select.ts @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { runOpenshell } from "../../adapters/openshell/runtime"; +import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; +import { getKnownSandboxTargetGatewayName } from "./gateway-target"; + +export type GatewaySelectRunner = typeof runOpenshell; + +export type GatewaySelectResult = + | { outcome: "selected"; gatewayName: string } + | { outcome: "failed"; gatewayName: string } + | { outcome: "unregistered"; gatewayName: null }; + +export function selectSandboxOwningGateway( + sandboxName: string, + run: GatewaySelectRunner = runOpenshell, +): GatewaySelectResult { + const targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName); + if (!targetGatewayName) return { outcome: "unregistered", gatewayName: null }; + const result = run(["gateway", "select", targetGatewayName], { + ignoreError: true, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + if (result.error || result.status !== 0) { + return { outcome: "failed", gatewayName: targetGatewayName }; + } + return { outcome: "selected", gatewayName: targetGatewayName }; +} diff --git a/src/lib/actions/sandbox/gateway-state-drift.test.ts b/src/lib/actions/sandbox/gateway-state-drift.test.ts index b1cb161b1b4..feab9617159 100644 --- a/src/lib/actions/sandbox/gateway-state-drift.test.ts +++ b/src/lib/actions/sandbox/gateway-state-drift.test.ts @@ -15,6 +15,7 @@ const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); const gatewayRuntime = requireDist("../../gateway-runtime-action.js"); const dockerDriverRecovery = requireDist("../../onboard/docker-driver-sandbox-recovery.js"); const registry = requireDist("../../state/registry.js"); +const gatewaySelect = requireDist("./gateway-select.js"); const gatewayState: GatewayStateModule = requireDist("./gateway-state.js"); const driftIssue: OpenShellStateRpcIssue = { @@ -42,6 +43,7 @@ describe("sandbox gateway state drift guard", () => { let detectPreflightIssueSpy: MockInstance; let getNamedGatewayLifecycleStateSpy: MockInstance; let getSandboxSpy: MockInstance; + let gatewaySelectSpy: MockInstance; let recoverNamedGatewayRuntimeSpy: MockInstance; let runOpenshellSpy: MockInstance; let removeSandboxSpy: MockInstance; @@ -52,6 +54,9 @@ describe("sandbox gateway state drift guard", () => { errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); getSandboxSpy = vi.spyOn(registry, "getSandbox").mockReturnValue(null); + gatewaySelectSpy = vi + .spyOn(gatewaySelect, "selectSandboxOwningGateway") + .mockReturnValue({ outcome: "selected", gatewayName: "nemoclaw" }); captureOpenshellSpy = vi .spyOn(openshellRuntime, "captureOpenshell") @@ -95,6 +100,7 @@ describe("sandbox gateway state drift guard", () => { vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false), getNamedGatewayLifecycleStateSpy, getSandboxSpy, + gatewaySelectSpy, recoverNamedGatewayRuntimeSpy, vi .spyOn(dockerDriverRecovery, "recoverDockerDriverSandbox") @@ -172,7 +178,7 @@ describe("sandbox gateway state drift guard", () => { expect(removeSandboxSpy).not.toHaveBeenCalled(); }); - it("preserves registry state and prints deterministic guidance when gateway selection cannot expose the sandbox (#2276)", async () => { + it("preserves registry state and prints deterministic guidance after targeting the owning gateway (#2276)", async () => { vi.stubEnv("NEMOCLAW_NON_INTERACTIVE", "1"); detectPreflightIssueSpy.mockReturnValue(null); getSandboxSpy.mockReturnValue({ @@ -196,24 +202,21 @@ describe("sandbox gateway state drift guard", () => { expect(output).toContain("Your sandbox has NOT been removed"); expect(output).toContain("openshell gateway select nemoclaw"); expect(output).not.toMatch(/Press (?:enter|any key)|\?\s+\[/i); - expect(runOpenshellSpy).toHaveBeenCalledWith( - ["gateway", "select", "nemoclaw"], - expect.objectContaining({ ignoreError: true }), - ); + expect(gatewaySelectSpy).toHaveBeenCalledWith("alpha"); expect(removeSandboxSpy).not.toHaveBeenCalled(); }); it.each([ { lifecycle: { state: "missing_named", status: "No gateway configured" }, - expected: "gateway is no longer configured after restart/rebuild", + expected: "gateway is no longer configured or its metadata/runtime has been lost", }, { lifecycle: { state: "named_unreachable", status: "Gateway: nemoclaw\nConnection refused", }, - expected: "gateway is still refusing connections after restart", + expected: "gateway exists in metadata, but its API is refusing connections after restart", }, ])("preserves registry state when the named gateway reports $lifecycle.state", async ({ lifecycle, @@ -265,6 +268,10 @@ describe("sandbox gateway state drift guard", () => { gatewayName: "nemoclaw-8090", gatewayPort: 8090, }); + gatewaySelectSpy.mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8090", + }); recoverNamedGatewayRuntimeSpy.mockResolvedValue({ recovered: true, via: "start", diff --git a/src/lib/actions/sandbox/gateway-state-hints.test.ts b/src/lib/actions/sandbox/gateway-state-hints.test.ts index bcf71ce0f8f..2716d290f6e 100644 --- a/src/lib/actions/sandbox/gateway-state-hints.test.ts +++ b/src/lib/actions/sandbox/gateway-state-hints.test.ts @@ -23,6 +23,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { const openshellRuntime = requireDist("../../adapters/openshell/runtime.js"); const gatewayRuntime = requireDist("../../gateway-runtime-action.js"); const registry = requireDist("../../state/registry.js"); + const gatewaySelect = requireDist("./gateway-select.js"); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); captureOpenshellSpy = vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ @@ -40,6 +41,10 @@ describe("printGatewayLifecycleHint multi-instance hints", () => { gatewayName: "nemoclaw", gatewayPort: 8080, }); + vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw", + }); gatewayState = requireDist("./gateway-state.js"); }); diff --git a/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts new file mode 100644 index 00000000000..b15098f6260 --- /dev/null +++ b/src/lib/actions/sandbox/gateway-state-owning-gateway.test.ts @@ -0,0 +1,218 @@ +// 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 gatewayDrift from "../../adapters/openshell/gateway-drift"; +import * as openshellRuntime from "../../adapters/openshell/runtime"; +import * as gatewayRuntime from "../../gateway-runtime-action"; +import * as registry from "../../state/registry"; +import * as gatewaySelect from "./gateway-select"; +import { + getReconciledSandboxGatewayState, + getSandboxGatewayState, + getSandboxGatewayStateForStatus, +} from "./gateway-state"; + +describe("getReconciledSandboxGatewayState owning-gateway guard", () => { + beforeEach(() => { + vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8091", + }); + vi.spyOn(gatewayRuntime, "getNamedGatewayLifecycleState").mockReturnValue({ + state: "connected_other", + activeGateway: "sibling", + status: "Gateway: sibling\nStatus: Connected", + } as never); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + + it("pins both the sandbox and policy RPCs to the recorded owner", () => { + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); + const capture = vi + .spyOn(openshellRuntime, "captureOpenshell") + .mockReturnValueOnce({ status: 0, output: "Policy:\nPhase: Ready" } as never) + .mockReturnValueOnce({ status: 0, output: "version: 1" } as never); + + const result = getSandboxGatewayState("beta", "nemoclaw-8091"); + + expect(result.state).toBe("present"); + expect(capture).toHaveBeenNthCalledWith( + 1, + ["sandbox", "get", "-g", "nemoclaw-8091", "beta"], + expect.anything(), + ); + expect(capture).toHaveBeenNthCalledWith( + 2, + ["policy", "get", "-g", "nemoclaw-8091", "--full", "beta"], + expect.anything(), + ); + }); + + it("pins the async status RPC to the recorded owner", async () => { + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null); + vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null); + vi.spyOn(openshellRuntime, "isCommandTimeout").mockReturnValue(false); + const capture = vi + .spyOn(openshellRuntime, "captureOpenshellForStatus") + .mockResolvedValueOnce({ status: 0, output: "Phase: Ready" } as never) + .mockResolvedValueOnce({ status: 1, output: "" } as never); + + const result = await getSandboxGatewayStateForStatus("beta", "nemoclaw-8091"); + + expect(result.state).toBe("present"); + expect(capture).toHaveBeenNthCalledWith( + 1, + ["sandbox", "get", "-g", "nemoclaw-8091", "beta"], + expect.anything(), + ); + expect(capture).toHaveBeenNthCalledWith( + 2, + ["policy", "get", "-g", "nemoclaw-8091", "--full", "beta"], + expect.anything(), + ); + }); + + it("rejects endpoint routing before a status RPC can bypass the owner", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://sibling.invalid"); + const syncCapture = vi.spyOn(openshellRuntime, "captureOpenshell"); + const asyncCapture = vi.spyOn(openshellRuntime, "captureOpenshellForStatus"); + + expect(getSandboxGatewayState("beta", "nemoclaw-8091")).toMatchObject({ + state: "gateway_endpoint_override", + output: expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), + }); + await expect(getSandboxGatewayStateForStatus("beta", "nemoclaw-8091")).resolves.toMatchObject({ + state: "gateway_endpoint_override", + output: expect.stringContaining("OPENSHELL_GATEWAY_ENDPOINT is set"), + }); + expect(syncCapture).not.toHaveBeenCalled(); + expect(asyncCapture).not.toHaveBeenCalled(); + }); + + it("targets the registered owner on the first lookup instead of accepting ambient sibling state", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "present", output: "Phase: Provisioning" }, + ); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(result).toMatchObject({ + state: "present", + output: "Phase: Ready", + }); + expect(result.recoveredGateway).toBeUndefined(); + }); + + it("queries the gateway returned by selection when registry ownership changes between snapshots", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8092", + }); + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8092"); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("keeps recovery pinned to the gateway returned by selection after ownership changes", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "selected", + gatewayName: "nemoclaw-8092", + }); + 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 }); + + expect(getState).toHaveBeenNthCalledWith(1, "beta", "nemoclaw-8092"); + expect(recover).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-8092", + }); + expect(getState).toHaveBeenNthCalledWith(2, "beta", "nemoclaw-8092"); + expect(result).toMatchObject({ + state: "present", + output: "Phase: Ready", + recoveredGateway: true, + recoveryVia: "start", + }); + }); + + it("does not return an ambient sibling timeout without first querying the healthy owner", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "status_probe_timeout", output: "sibling timed out" }, + ); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("does not return an ambient sibling unknown error without first querying the healthy owner", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + const getState = vi.fn((_name: string, gatewayName?: string) => + gatewayName === "nemoclaw-8091" + ? { state: "present", output: "Phase: Ready" } + : { state: "unknown_error", output: "sibling failed" }, + ); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).toHaveBeenCalledOnce(); + expect(getState).toHaveBeenCalledWith("beta", "nemoclaw-8091"); + expect(result).toMatchObject({ state: "present", output: "Phase: Ready" }); + }); + + it("fails closed before lookup when the owning gateway cannot be selected", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue({ gatewayPort: 8091 } as never); + vi.mocked(gatewaySelect.selectSandboxOwningGateway).mockReturnValue({ + outcome: "failed", + gatewayName: "nemoclaw-8091", + }); + const getState = vi.fn(); + + const result = await getReconciledSandboxGatewayState("beta", { getState }); + + expect(getState).not.toHaveBeenCalled(); + expect(result.state).toBe("wrong_gateway_active"); + expect(result.recoveredGateway).toBeUndefined(); + }); + + it("leaves an unregistered sandbox on the existing default lookup path", async () => { + vi.spyOn(registry, "getSandbox").mockReturnValue(null); + const getState = vi.fn().mockResolvedValue({ state: "present", output: "Phase: Ready" }); + + const result = await getReconciledSandboxGatewayState("ghost", { getState }); + + expect(getState).toHaveBeenCalledTimes(1); + expect(getState).toHaveBeenCalledWith("ghost", undefined); + expect(result).toMatchObject({ state: "present" }); + }); +}); diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index e573030934b..d6a52a1d91f 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -10,8 +10,14 @@ import { getNamedGatewayLifecycleState, recoverNamedGatewayRuntime, } from "../../gateway-runtime-action"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { isTerminalSandboxPhase, parseSandboxPhase } from "../../state/gateway"; -import { gatewayNamePattern, getSandboxTargetGatewayName } from "./gateway-target"; +import { selectSandboxOwningGateway } from "./gateway-select"; +import { + gatewayNamePattern, + getKnownSandboxTargetGatewayName, + getSandboxTargetGatewayName, +} from "./gateway-target"; const { pruneKnownHostsEntries } = require("../../onboard/known-hosts") as { pruneKnownHostsEntries: (contents: string) => string; @@ -66,8 +72,26 @@ export type SandboxGatewayState = { type SandboxGatewayStateLookup = ( sandboxName: string, + gatewayName?: string, ) => SandboxGatewayState | Promise; +function gatewayScopedArgs(args: string[], gatewayName?: string): string[] { + if (!gatewayName) return args; + return [...args.slice(0, 2), "-g", gatewayName, ...args.slice(2)]; +} + +function gatewayEndpointOverrideState(): SandboxGatewayState | null { + try { + assertNoOpenShellGatewayEndpointOverride(); + return null; + } catch (error) { + return { + state: "gateway_endpoint_override", + output: ` Error: ${error instanceof Error ? error.message : String(error)}`, + }; + } +} + function formatGatewaySchemaMismatchOutput( issue: OpenShellStateRpcIssue, action: string, @@ -110,8 +134,13 @@ export function mergeLivePolicyIntoSandboxOutput(output: string, livePolicyOutpu } /** Query sandbox presence and return its output with the live enforced policy. */ -export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState { - const preflightIssue = detectOpenShellStateRpcPreflightIssue(); +export function getSandboxGatewayState( + sandboxName: string, + gatewayName?: string, +): SandboxGatewayState { + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + const preflightIssue = detectOpenShellStateRpcPreflightIssue({ gatewayName }); if (preflightIssue) { return { state: "gateway_schema_mismatch", @@ -121,11 +150,11 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState ), }; } - const result = captureOpenshell(["sandbox", "get", sandboxName], { + const result = captureOpenshell(gatewayScopedArgs(["sandbox", "get", sandboxName], gatewayName), { timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); let output = result.output; - const resultIssue = detectOpenShellStateRpcResultIssue(result); + const resultIssue = detectOpenShellStateRpcResultIssue(result, { gatewayName }); if (resultIssue) { return { state: "gateway_schema_mismatch", @@ -135,21 +164,23 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState }; } if (result.status === 0) { - const livePolicy = captureOpenshell(["policy", "get", "--full", sandboxName], { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); + const livePolicy = captureOpenshell( + gatewayScopedArgs(["policy", "get", "--full", sandboxName], gatewayName), + { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }, + ); if (livePolicy.status === 0 && livePolicy.output.trim()) { output = mergeLivePolicyIntoSandboxOutput(output, livePolicy.output); } return { state: "present", output }; } - // `sandbox has no spec` is the gRPC reply when the active OpenShell gateway - // is reachable but does not know about this sandbox — the multi-instance - // case where the active gateway is a sibling of the one the sandbox was - // onboarded against. Classify as `missing` so the named-gateway reconciler - // selects the sandbox's owning gateway and retries; without this the lookup - // would fall to `unknown_error` and exit with a hint instead of recovering. + // `sandbox has no spec` is the gRPC reply when the queried gateway does not + // know about this sandbox. On an unscoped lookup that can be an ambient + // sibling; an owner-scoped lookup means the sandbox is genuinely absent + // from its recorded gateway. Both remain `missing`, and reconciliation uses + // the presence of the explicit owner pin to distinguish those cases. if (/\bNotFound\b|\bNot Found\b|sandbox not found|sandbox has no spec/i.test(output)) { return { state: "missing", output }; } @@ -165,9 +196,12 @@ export function getSandboxGatewayState(sandboxName: string): SandboxGatewayState export async function getSandboxGatewayStateForStatus( sandboxName: string, + gatewayName?: string, ): Promise { const timeoutMs = getStatusProbeTimeoutMs(); - const preflightIssue = detectOpenShellStateRpcPreflightIssue({ timeoutMs }); + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + const preflightIssue = detectOpenShellStateRpcPreflightIssue({ gatewayName, timeoutMs }); if (preflightIssue) { return { state: "gateway_schema_mismatch", @@ -178,11 +212,14 @@ export async function getSandboxGatewayStateForStatus( ), }; } - const result = await captureOpenshellForStatus(["sandbox", "get", sandboxName], { - timeout: timeoutMs, - }); + const result = await captureOpenshellForStatus( + gatewayScopedArgs(["sandbox", "get", sandboxName], gatewayName), + { + timeout: timeoutMs, + }, + ); let output = result.output; - const resultIssue = detectOpenShellStateRpcResultIssue(result, { timeoutMs }); + const resultIssue = detectOpenShellStateRpcResultIssue(result, { gatewayName, timeoutMs }); if (resultIssue) { return { state: "gateway_schema_mismatch", @@ -199,10 +236,13 @@ export async function getSandboxGatewayStateForStatus( }; } if (result.status === 0) { - const livePolicy = await captureOpenshellForStatus(["policy", "get", "--full", sandboxName], { - ignoreError: true, - timeout: timeoutMs, - }); + const livePolicy = await captureOpenshellForStatus( + gatewayScopedArgs(["policy", "get", "--full", sandboxName], gatewayName), + { + ignoreError: true, + timeout: timeoutMs, + }, + ); if (!isCommandTimeout(livePolicy) && livePolicy.status === 0 && livePolicy.output.trim()) { output = mergeLivePolicyIntoSandboxOutput(output, livePolicy.output); } @@ -226,22 +266,29 @@ export async function getSandboxGatewayStateForStatus( * When the active OpenShell gateway has drifted off nemoclaw, a NotFound is * ambiguous: the sandbox may actually be registered against the nemoclaw * gateway but invisible because some other gateway is currently active. This - * helper self-heals by attempting `openshell gateway select nemoclaw` and - * re-queries, or returns a `wrong_gateway_active` state so callers can surface - * actionable guidance instead of destroying the registry entry. + * helper self-heals an unscoped lookup by attempting `openshell gateway select + * nemoclaw` and re-querying. When `pinnedGatewayName` is present, the NotFound + * already came from the recorded owner, so ambient selection is ignored and + * only the existing Docker-side recovery path is considered. */ export function reconcileMissingAgainstNamedGateway( sandboxName: string, missingLookup: SandboxGatewayState, + pinnedGatewayName?: string, ): SandboxGatewayState { - const targetGatewayName = getSandboxTargetGatewayName(sandboxName); + const targetGatewayName = pinnedGatewayName ?? getSandboxTargetGatewayName(sandboxName); + if (pinnedGatewayName) { + // The owner-scoped RPC reached this exact gateway and reported NotFound. + // Ambient selection is irrelevant and must not trigger a sibling retry. + return tryRecoverDockerDriverSandbox(sandboxName, missingLookup, pinnedGatewayName); + } const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); if (lifecycle.state === "connected_other") { runOpenshell(["gateway", "select", targetGatewayName], { ignoreError: true, timeout: OPENSHELL_OPERATION_TIMEOUT_MS, }); - const retry = getSandboxGatewayState(sandboxName); + const retry = getSandboxGatewayState(sandboxName, targetGatewayName); if (retry.state === "present") { return { ...retry, recoveredGateway: true, recoveryVia: "select" }; } @@ -301,6 +348,7 @@ export function reconcileMissingAgainstNamedGateway( function tryRecoverDockerDriverSandbox( sandboxName: string, missingLookup: SandboxGatewayState, + gatewayName?: string, ): SandboxGatewayState { let recovery: DockerDriverRecoveryResult; try { @@ -313,7 +361,7 @@ function tryRecoverDockerDriverSandbox( } // Recovery succeeded against Docker; re-query OpenShell so the // returned state reflects what the gateway sees post-restart. - const retried = getSandboxGatewayState(sandboxName); + const retried = getSandboxGatewayState(sandboxName, gatewayName); return { ...retried, recoveredSandbox: true, @@ -428,19 +476,43 @@ export async function getReconciledSandboxGatewayState( opts: { getState?: SandboxGatewayStateLookup } = {}, ): Promise { const getState = opts.getState ?? getSandboxGatewayState; - const lookup = await getState(sandboxName); + let targetGatewayName = getKnownSandboxTargetGatewayName(sandboxName) ?? undefined; + const endpointOverride = gatewayEndpointOverrideState(); + if (endpointOverride) return endpointOverride; + if (targetGatewayName) { + // Keep OpenShell's active selection aligned for downstream operations, but + // never trust that process-global state for this lookup: another CLI can + // change it immediately after selection. The explicit gateway argument + // below is the per-subprocess authority for the status RPC. + const selection = selectSandboxOwningGateway(sandboxName); + if (selection.outcome !== "selected") { + const lifecycle = getNamedGatewayLifecycleState(targetGatewayName); + return { + state: "wrong_gateway_active", + activeGateway: lifecycle.activeGateway, + output: + lifecycle.status || + `Failed to select owning gateway '${targetGatewayName}' for sandbox '${sandboxName}'.`, + }; + } + // Selection resolves registry ownership internally. If that snapshot changed + // after the initial lookup, keep the subprocess-local RPC pin aligned with + // the gateway that was actually selected rather than querying the stale one. + targetGatewayName = selection.gatewayName; + } + const lookup = await getState(sandboxName, targetGatewayName); if (lookup.state === "present") { return lookup; } if (lookup.state === "missing") { - return reconcileMissingAgainstNamedGateway(sandboxName, lookup); + return reconcileMissingAgainstNamedGateway(sandboxName, lookup, targetGatewayName); } if (lookup.state === "gateway_error") { - const targetGatewayName = getSandboxTargetGatewayName(sandboxName); - const recovery = await recoverNamedGatewayRuntime({ gatewayName: targetGatewayName }); + const recoveryGatewayName = targetGatewayName ?? getSandboxTargetGatewayName(); + const recovery = await recoverNamedGatewayRuntime({ gatewayName: recoveryGatewayName }); if (recovery.recovered) { - const retried = await getState(sandboxName); + const retried = await getState(sandboxName, recoveryGatewayName); if (retried.state === "present" || retried.state === "missing") { return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } @@ -454,7 +526,7 @@ export async function getReconciledSandboxGatewayState( } return { ...retried, recoveredGateway: true, recoveryVia: recovery.via || null }; } - const latestLifecycle = getNamedGatewayLifecycleState(targetGatewayName); + const latestLifecycle = getNamedGatewayLifecycleState(recoveryGatewayName); const latestStatus = stripAnsi(latestLifecycle.status || ""); if (/No gateway configured/i.test(latestStatus)) { return { @@ -464,7 +536,7 @@ export async function getReconciledSandboxGatewayState( } if ( /Connection refused|client error \(Connect\)|tcp connect error/i.test(latestStatus) && - gatewayNamePattern(targetGatewayName).test(latestStatus) + gatewayNamePattern(recoveryGatewayName).test(latestStatus) ) { return { state: "gateway_unreachable_after_restart", diff --git a/src/lib/actions/sandbox/gateway-target.ts b/src/lib/actions/sandbox/gateway-target.ts index d8232618920..cd125ceb8b7 100644 --- a/src/lib/actions/sandbox/gateway-target.ts +++ b/src/lib/actions/sandbox/gateway-target.ts @@ -5,9 +5,13 @@ import { GATEWAY_PORT } from "../../core/ports"; import { resolveGatewayName, resolveSandboxGatewayName } from "../../onboard/gateway-binding"; import * as registry from "../../state/registry"; -export function getSandboxTargetGatewayName(sandboxName = ""): string { +export function getKnownSandboxTargetGatewayName(sandboxName = ""): string | null { const sb = sandboxName ? registry.getSandbox(sandboxName) : null; - return sb ? resolveSandboxGatewayName(sb) : resolveGatewayName(GATEWAY_PORT); + return sb ? resolveSandboxGatewayName(sb) : null; +} + +export function getSandboxTargetGatewayName(sandboxName = ""): string { + return getKnownSandboxTargetGatewayName(sandboxName) ?? resolveGatewayName(GATEWAY_PORT); } export function gatewayNamePattern(gatewayName: string): RegExp { diff --git a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts index 0460aef8993..07b2eb50540 100644 --- a/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts +++ b/src/lib/actions/sandbox/rebuild-gateway-drift.test.ts @@ -130,16 +130,17 @@ describe("rebuild gateway drift preflight", () => { recordedPort: 9000, activeGateway: "nemoclaw", }, - ])("refuses stale recovery when $activeGateway is active instead of recorded gateway $recordedGateway (#4497)", async ({ + ])("recovers $recordedGateway as stale even while $activeGateway is ambiently active, since the sandbox RPC is gateway-pinned (#4497)", async ({ recordedGateway, recordedPort, activeGateway, }) => { const entry = makeSandboxEntry(recordedGateway, recordedPort); + const registrySnapshot = { sandboxes: { alpha: entry } }; vi.mocked(registry.getSandbox).mockReturnValue(entry as never); + vi.mocked(registry.load).mockReturnValue(registrySnapshot as never); captureOpenshellSpy .mockReturnValueOnce({ status: 0, output: "" }) - .mockReturnValueOnce({ status: 1, output: "Error: × Not Found: sandbox not found" }) .mockReturnValueOnce({ status: 1, output: "Error: × Not Found: sandbox not found" }); getNamedGatewayLifecycleStateSpy.mockReturnValue({ state: "connected_other", @@ -148,23 +149,25 @@ describe("rebuild gateway drift preflight", () => { } as never); const behaviorLog = vi.fn(); - await expect(resolveRebuildLiveState("alpha", entry, behaviorLog, bail)).rejects.toThrow( - "Could not confirm live state", - ); + const result = await resolveRebuildLiveState("alpha", entry, behaviorLog, bail); - expect(getNamedGatewayLifecycleStateSpy).toHaveBeenCalledWith(recordedGateway); + expect(result).toEqual({ staleRecovery: true, staleRegistrySnapshot: registrySnapshot }); + expect(result?.staleRegistrySnapshot).not.toBe(registrySnapshot); + expect(getNamedGatewayLifecycleStateSpy).not.toHaveBeenCalled(); expect(runOpenshellSpy).toHaveBeenCalledWith( ["gateway", "select", recordedGateway], expect.objectContaining({ ignoreError: true }), ); - const output = errorSpy.mock.calls.flat().join("\n"); - expect(output).toContain("NOT been removed"); - expect(output).toContain(`openshell gateway select ${recordedGateway}`); - expect(registry.load).not.toHaveBeenCalled(); - expect(recoverDockerDriverSandboxSpy).not.toHaveBeenCalled(); - expect([...logSpy.mock.calls, ...behaviorLog.mock.calls].flat().join("\n")).not.toContain( - "No live workspace state to back up", + expect(captureOpenshellSpy).toHaveBeenNthCalledWith(1, ["sandbox", "list"]); + expect(captureOpenshellSpy).toHaveBeenNthCalledWith( + 2, + ["sandbox", "get", "-g", recordedGateway, "alpha"], + expect.anything(), ); + expect(recoverDockerDriverSandboxSpy).toHaveBeenCalledWith("alpha"); + expect(registry.load).toHaveBeenCalledOnce(); + expect(logSpy.mock.calls.flat().join("\n")).toContain("absent from the live OpenShell gateway"); + expect(behaviorLog.mock.calls.flat().join("\n")).toContain("Stale-sandbox recovery"); }); it.each([ @@ -212,10 +215,10 @@ describe("rebuild gateway drift preflight", () => { expect(captureOpenshellSpy).toHaveBeenNthCalledWith(2, ["sandbox", "list"]); expect(captureOpenshellSpy).toHaveBeenNthCalledWith( 3, - ["sandbox", "get", "alpha"], + ["sandbox", "get", "-g", gatewayName, "alpha"], expect.anything(), ); - expect(getNamedGatewayLifecycleStateSpy).toHaveBeenCalledWith(gatewayName); + expect(getNamedGatewayLifecycleStateSpy).not.toHaveBeenCalled(); expect(recoverDockerDriverSandboxSpy).toHaveBeenCalledWith("alpha"); expect(registry.load).toHaveBeenCalledOnce(); expect(logSpy.mock.calls.flat().join("\n")).toContain("absent from the live OpenShell gateway"); diff --git a/src/lib/domain/sandbox/logs.ts b/src/lib/domain/sandbox/logs.ts index 9131db784a8..e8706d3fc92 100644 --- a/src/lib/domain/sandbox/logs.ts +++ b/src/lib/domain/sandbox/logs.ts @@ -50,8 +50,14 @@ export function normalizeSandboxLogsOptions( }; } -export function buildEnableSandboxAuditLogsArgs(sandboxName: string): string[] { - return ["settings", "set", sandboxName, "--key", "ocsf_json_enabled", "--value", "true"]; +export function buildEnableSandboxAuditLogsArgs( + sandboxName: string, + gatewayName?: string, +): string[] { + const args = ["settings", "set"]; + if (gatewayName) args.push("-g", gatewayName); + args.push(sandboxName, "--key", "ocsf_json_enabled", "--value", "true"); + return args; } export function buildSandboxOpenclawGatewayLogsArgs( @@ -66,8 +72,14 @@ export function buildSandboxOpenclawGatewayLogsArgs( return args; } -export function buildSandboxLogsArgs(sandboxName: string, options: SandboxLogsOptions): string[] { - const args = ["logs", sandboxName, "-n", options.lines, "--source", "all"]; +export function buildSandboxLogsArgs( + sandboxName: string, + options: SandboxLogsOptions, + gatewayName?: string, +): string[] { + const args = ["logs"]; + if (gatewayName) args.push("-g", gatewayName); + args.push(sandboxName, "-n", options.lines, "--source", "all"); if (options.since) { args.push("--since", options.since); } diff --git a/test/cli/connect-recovery.test.ts b/test/cli/connect-recovery.test.ts index 7eb1dcfbfc4..e59d15a3800 100644 --- a/test/cli/connect-recovery.test.ts +++ b/test/cli/connect-recovery.test.ts @@ -175,7 +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" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -214,7 +214,7 @@ describe("CLI connect recovery process contracts", () => { expect(result.code).toBe(0); expect(result.out).toContain("Probe complete: recovered OpenClaw gateway"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); + expect(calls).toContain("sandbox get -g nemoclaw alpha"); expect(calls.some((call) => call.startsWith("sandbox exec --name alpha -- sh -c"))).toBe( true, ); @@ -248,7 +248,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -317,7 +317,7 @@ describe("CLI connect recovery process contracts", () => { `calls=${JSON.stringify(openshellCalls)}`, `state_file=${JSON.stringify(stateFile)}`, 'printf \'%s\\n\' "$*" >> "$calls"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -442,7 +442,7 @@ describe("CLI connect recovery process contracts", () => { " echo 'alpha Ready 2m ago'", " exit 0", "fi", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 1e6db629dc2..0172eec8da2 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -25,7 +25,7 @@ describe("CLI dispatch for terminal agents", () => { "#!/usr/bin/env bash", `marker_file=${JSON.stringify(markerFile)}`, 'printf \'%s\\n\' "$*" >> "$marker_file"', - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -55,7 +55,7 @@ describe("CLI dispatch for terminal agents", () => { expect(r.code).toBe(0); expect(r.out).toContain("terminal smoke checks passed"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - expect(calls).toContain("sandbox get alpha"); + expect(calls).toContain("sandbox get -g nemoclaw alpha"); expect(calls.some((call) => call.includes("NEMOCLAW_AGENT_SMOKE_EXIT"))).toBe(true); expect(calls.some((call) => call.includes("nemoclaw-agent-smoke dcode --version"))).toBe(true); expect( diff --git a/test/cli/sandbox-status-json.test.ts b/test/cli/sandbox-status-json.test.ts index e50500203c5..13325121058 100644 --- a/test/cli/sandbox-status-json.test.ts +++ b/test/cli/sandbox-status-json.test.ts @@ -568,7 +568,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -621,7 +621,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -710,7 +710,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", diff --git a/test/cli/sandbox-status-text.test.ts b/test/cli/sandbox-status-text.test.ts index ad536a761e9..348187beb23 100644 --- a/test/cli/sandbox-status-text.test.ts +++ b/test/cli/sandbox-status-text.test.ts @@ -90,7 +90,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -145,7 +145,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "dcode-station" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "dcode-station" ] || [ "$5" = "dcode-station" ]; }; then', " echo 'Sandbox:'", " echo ' Name: dcode-station'", " echo ' Phase: Ready'", @@ -201,7 +201,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Ready'", @@ -329,7 +329,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -423,7 +423,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo ' Name: alpha'", " echo ' Phase: Error'", @@ -493,7 +493,7 @@ describe("CLI sandbox status text output", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", diff --git a/test/cli/status-gateway-lifecycle.test.ts b/test/cli/status-gateway-lifecycle.test.ts index 28b680b74df..0b183226e36 100644 --- a/test/cli/status-gateway-lifecycle.test.ts +++ b/test/cli/status-gateway-lifecycle.test.ts @@ -37,7 +37,7 @@ describe("CLI status gateway lifecycle process contracts", () => { path.join(localBin, "openshell"), [ "#!/usr/bin/env bash", - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', ` ${JSON.stringify(process.execPath)} -e "setInterval(() => {}, 1000)" &`, " wait", "fi", @@ -81,7 +81,7 @@ describe("CLI status gateway lifecycle process contracts", () => { [ "#!/usr/bin/env bash", `printf '%s\\n' "$*" >> ${JSON.stringify(markerFile)}`, - 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && [ "$3" = "alpha" ]; then', + 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', " echo 'Sandbox:'", " echo", " echo ' Id: abc'", @@ -143,7 +143,7 @@ describe("CLI status gateway lifecycle process contracts", () => { expect(result.out).toContain("healthy"); expect(result.out).not.toContain("not verified"); const calls = fs.readFileSync(markerFile, "utf8").trim().split("\n").filter(Boolean); - const sandboxGetIndex = calls.indexOf("sandbox get alpha"); + const sandboxGetIndex = calls.indexOf("sandbox get -g nemoclaw alpha"); const inferenceGetIndex = calls.indexOf("inference get -g nemoclaw"); expect(sandboxGetIndex).toBeGreaterThanOrEqual(0); expect(inferenceGetIndex).toBeGreaterThan(sandboxGetIndex); diff --git a/test/nemoclaw-cli-recovery.test.ts b/test/nemoclaw-cli-recovery.test.ts index d28c8904d5f..e0bccfb09ed 100644 --- a/test/nemoclaw-cli-recovery.test.ts +++ b/test/nemoclaw-cli-recovery.test.ts @@ -72,7 +72,7 @@ if (args[0] === "gateway" && args[1] === "info") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === "my-assistant") { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === "my-assistant" || args[4] === "my-assistant")) { state.sandboxGetCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); if (state.sandboxGetCalls === 1) { diff --git a/test/reboot-identity-drift.test.ts b/test/reboot-identity-drift.test.ts index c08f42ba2c0..30d7388a90f 100644 --- a/test/reboot-identity-drift.test.ts +++ b/test/reboot-identity-drift.test.ts @@ -112,7 +112,7 @@ if (args[0] === "gateway" && args[1] === "select") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { ${sandboxGetBehavior} } @@ -201,7 +201,7 @@ if (args[0] === "gateway" && args[1] === "start") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { process.stdout.write("Sandbox:\\n\\n Id: abc\\n Name: ${sandboxName}\\n Phase: Ready\\n"); process.exit(0); } diff --git a/test/repro-2666-silent-list-status.test.ts b/test/repro-2666-silent-list-status.test.ts index c417d2dad2f..217443d3bfc 100644 --- a/test/repro-2666-silent-list-status.test.ts +++ b/test/repro-2666-silent-list-status.test.ts @@ -187,7 +187,7 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Gateway: nemoclaw'", " exit 0", " ;;", - ' "sandbox get my-assist")', + ' "sandbox get my-assist"|"sandbox get -g nemoclaw my-assist")', " echo 'transport error: client error (Connect)' >&2", " exit 1", " ;;", @@ -354,6 +354,10 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Error: sandbox not found' >&2", " exit 1", " ;;", + ' "sandbox get -g nemoclaw my-assist")', + " echo 'client error (Connect): tcp connect error: Connection refused (os error 61)' >&2", + " exit 1", + " ;;", " status)", " cat <<'EOF'", "Status: Disconnected", @@ -392,6 +396,10 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress " echo 'Error: sandbox not found' >&2", " exit 1", " ;;", + ' "sandbox get -g nemoclaw my-assist")', + " echo 'transport error: no gateway configured' >&2", + " exit 1", + " ;;", " status)", " echo 'No gateway configured'", " exit 1", @@ -444,7 +452,7 @@ describe("simulated container-stopped and foreign-port-holder subprocess regress writeFakeOpenshell([ "#!/usr/bin/env bash", 'case "$*" in', - ' "sandbox get my-assist")', + ' "sandbox get my-assist"|"sandbox get -g nemoclaw my-assist")', " echo 'transport error: unexpected EOF' >&2", " exit 1", " ;;", diff --git a/test/sandbox-stuck-recovery.test.ts b/test/sandbox-stuck-recovery.test.ts index 1e8acc06088..16b417cc096 100644 --- a/test/sandbox-stuck-recovery.test.ts +++ b/test/sandbox-stuck-recovery.test.ts @@ -59,7 +59,7 @@ if (args[0] === "gateway" && args[1] === "info") { process.exit(0); } -if (args[0] === "sandbox" && args[1] === "get" && args[2] === ${JSON.stringify(sandboxName)}) { +if (args[0] === "sandbox" && args[1] === "get" && (args[2] === ${JSON.stringify(sandboxName)} || args[4] === ${JSON.stringify(sandboxName)})) { process.stdout.write("Sandbox:\\n\\n Id: abc\\n Name: ${sandboxName}\\n Phase: ${phase}\\n"); process.exit(0); }