diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index ffd0d8a7e49..b6002db1d4f 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -793,6 +793,11 @@ $$nemoclaw deploy ### `$$nemoclaw connect` Connect to a sandbox by name. +Bare `$$nemoclaw connect` (no sandbox name) connects to the registry default. +NemoClaw uses the stored default when it names a non-pending registered sandbox, then falls back to the first non-pending registration. +If only pending registrations remain, the command exits non-zero and tells you to wait for onboarding or remove the incomplete sandbox. +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. @@ -823,6 +828,7 @@ You no longer need to re-run `$$nemoclaw onboard` after a reboot in this case. ```bash $$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. diff --git a/src/lib/cli/bare-connect-routing.ts b/src/lib/cli/bare-connect-routing.ts new file mode 100644 index 00000000000..3424e1b855b --- /dev/null +++ b/src/lib/cli/bare-connect-routing.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { NormalizedSandboxArgv } from "./argv-normalizer"; +import { CLI_NAME } from "./branding"; + +type SandboxSummary = { + name: string; + pendingRouteReservation?: true; +}; + +export type BareConnectRoutingDeps = { + findRegisteredSandboxName: (tokens: string[]) => string | null; + getDefault: () => string | null; + getSandbox: (name: string) => unknown | null; + listSandboxes: () => { sandboxes: SandboxSummary[] }; + printConnectOrderHint: (candidate: string | null) => void; + printSandboxConnectHelp: (sandboxName?: string) => void; + recoverRegistryEntries: () => Promise; +}; + +/** + * Route a bare `connect` invocation to the default sandbox. + * + * Returns the (possibly rewritten) argv to dispatch, or `null` when the + * invocation was fully handled here (bare `connect --help`). A registered + * sandbox literally named `connect` keeps the historical name-first grammar. + */ +export async function resolveBareConnectArgv( + normalized: NormalizedSandboxArgv, + deps: BareConnectRoutingDeps, +): Promise { + if (normalized.sandboxName !== "connect" || deps.getSandbox("connect")) { + return normalized; + } + + if (normalized.action !== "connect") { + const reorderedCandidate = deps.findRegisteredSandboxName([normalized.action]); + if (reorderedCandidate) { + deps.printConnectOrderHint(reorderedCandidate); + process.exit(1); + } + return normalized; + } + + if (normalized.connectHelpRequested) { + deps.printSandboxConnectHelp(deps.getDefault() ?? undefined); + return null; + } + + const defaultName = await resolveDefaultSandboxForBareConnect(deps); + if (!defaultName) printBareConnectWithoutDefault(deps); + return { ...normalized, sandboxName: defaultName }; +} + +async function resolveDefaultSandboxForBareConnect( + deps: BareConnectRoutingDeps, +): Promise { + const currentDefault = deps.getDefault(); + if (currentDefault) return currentDefault; + + await deps.recoverRegistryEntries(); + return deps.getDefault(); +} + +function printBareConnectWithoutDefault(deps: BareConnectRoutingDeps): never { + const pendingNames = deps + .listSandboxes() + .sandboxes.filter((sandbox) => sandbox.pendingRouteReservation === true) + .map((sandbox) => sandbox.name); + + console.error(` '${CLI_NAME} connect' could not resolve a ready default sandbox.`); + console.error(""); + if (pendingNames.length > 0) { + console.error(` Sandbox setup is still pending: ${pendingNames.join(", ")}`); + console.error(" Wait for onboarding to finish or remove the incomplete sandbox."); + } else { + console.error(` Run '${CLI_NAME} onboard' to create one.`); + } + process.exit(1); +} diff --git a/src/lib/cli/public-dispatch.ts b/src/lib/cli/public-dispatch.ts index 9734efa66b6..0c4d3840d5b 100644 --- a/src/lib/cli/public-dispatch.ts +++ b/src/lib/cli/public-dispatch.ts @@ -28,6 +28,7 @@ import { normalizeArgv, suggestCommand, } from "./argv-normalizer"; +import { resolveBareConnectArgv } from "./bare-connect-routing"; import { getRegisteredOclifCommandMetadata } from "./oclif-metadata"; import { type PublicTranslationResult, @@ -358,17 +359,27 @@ async function dispatchSandboxArgv( normalized: NormalizedSandboxArgv, argv: string[], ): Promise { - const cmd = normalized.sandboxName; + const routed = await resolveBareConnectArgv(normalized, { + findRegisteredSandboxName, + getDefault: () => registry().getDefault(), + getSandbox: (name) => registry().getSandbox(name), + listSandboxes: () => registry().listSandboxes(), + printConnectOrderHint, + printSandboxConnectHelp: (sandboxName) => sandboxConnect().printSandboxConnectHelp(sandboxName), + recoverRegistryEntries: () => registryRecovery().recoverRegistryEntries(), + }); + if (!routed) return; + const cmd = routed.sandboxName; const rawArgsAfterCmd = argv.slice(1); - const requestedSandboxAction = normalized.action; - const requestedSandboxActionArgs = normalized.actionArgs; - if (handlePublicConnectHelp(normalized)) return; + const requestedSandboxAction = routed.action; + const requestedSandboxActionArgs = routed.actionArgs; + if (handlePublicConnectHelp(routed)) return; // Help is parser metadata, not sandbox runtime behavior. Render sandbox-scoped // public help before registry recovery so `nemoclaw missing channels start --help` // stays side-effect free and never starts or repairs services. if ( - !normalized.connectHelpRequested && + !routed.connectHelpRequested && isKnownSandboxAction(requestedSandboxAction) && hasPublicSandboxHelpFlag(requestedSandboxAction, requestedSandboxActionArgs) ) { diff --git a/test/cli/dispatch-basics.test.ts b/test/cli/dispatch-basics.test.ts index 573491b8889..6f504b43d97 100644 --- a/test/cli/dispatch-basics.test.ts +++ b/test/cli/dispatch-basics.test.ts @@ -402,7 +402,7 @@ describe("CLI dispatch", () => { let code = 0; let out = ""; try { - execSync(`node "${CLI}" alpha connect 2>&1`, { + execSync(`node "${CLI}" connect 2>&1`, { encoding: "utf-8", stdio: "pipe", timeout: execTimeout(), @@ -446,6 +446,122 @@ describe("CLI dispatch", () => { ); }); + it("connects to the default sandbox when connect is invoked without a sandbox name (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById }) => { + await dispatchCli(["connect"]); + + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:connect", + ["dcode-managed"], + expect.anything(), + ); + expect(recoverRegistryEntries).not.toHaveBeenCalled(); + }, + { sandboxNames: ["dcode-managed"], defaultSandbox: "dcode-managed" }, + ); + }); + + it("forwards connect flags to the default sandbox on a bare connect invocation (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, runOclifCommandById }) => { + await dispatchCli(["connect", "--probe-only"]); + + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:connect", + ["dcode-managed", "--probe-only"], + expect.anything(), + ); + }, + { + sandboxNames: ["dcode-managed"], + defaultSandbox: "dcode-managed", + connectFlags: ["--probe-only"], + }, + ); + }); + + it("uses the first non-pending sandbox when no stored default is valid (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, recoverRegistryEntries, runOclifCommandById }) => { + await dispatchCli(["connect"]); + + expect(recoverRegistryEntries).not.toHaveBeenCalled(); + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:connect", + ["alpha"], + expect.anything(), + ); + }, + { + sandboxNames: ["pending", "alpha", "beta"], + defaultSandbox: "missing", + pendingSandboxNames: ["pending"], + }, + ); + }); + + it("waits for pending-only sandbox setup instead of suggesting it as a default (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, exitSpy, recoverRegistryEntries, stderr }) => { + await expect(dispatchCli(["connect"])).rejects.toThrow("process.exit:1"); + + const output = stderr.join("\n"); + expect(recoverRegistryEntries).toHaveBeenCalledTimes(1); + expect(output).toContain("'nemoclaw connect' could not resolve a ready default sandbox."); + expect(output).toContain("Sandbox setup is still pending: alpha"); + expect(output).toContain("Wait for onboarding to finish or remove the incomplete sandbox."); + expect(output).not.toContain("nemoclaw use"); + expect(exitSpy).toHaveBeenCalledWith(1); + }, + { sandboxNames: ["alpha"], pendingSandboxNames: ["alpha"] }, + ); + }); + + it("points bare connect at onboarding when no sandboxes are registered (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, exitSpy, recoverRegistryEntries, stderr }) => { + await expect(dispatchCli(["connect"])).rejects.toThrow("process.exit:1"); + + const output = stderr.join("\n"); + expect(recoverRegistryEntries).toHaveBeenCalledTimes(1); + expect(output).toContain("'nemoclaw connect' could not resolve a ready default sandbox."); + expect(output).toContain("Run 'nemoclaw onboard' to create one."); + expect(exitSpy).toHaveBeenCalledWith(1); + }, + ); + }); + + it("keeps the name-first grammar for a sandbox literally named connect (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, getDefault, runOclifCommandById }) => { + await dispatchCli(["connect"]); + + expect(runOclifCommandById).toHaveBeenCalledWith( + "sandbox:connect", + ["connect"], + expect.anything(), + ); + expect(getDefault).not.toHaveBeenCalled(); + }, + { sandboxNames: ["connect"], defaultSandbox: null }, + ); + }); + + it("explains connect command order when only the sandbox name follows connect (#6627)", async () => { + await withDirectPublicDispatch( + async ({ dispatchCli, exitSpy, stderr }) => { + await expect(dispatchCli(["connect", "alpha"])).rejects.toThrow("process.exit:1"); + + const output = stderr.join("\n"); + expect(output).toContain("Command order is: nemoclaw connect"); + expect(output).toContain("Did you mean: nemoclaw alpha connect?"); + expect(exitSpy).toHaveBeenCalledWith(1); + }, + { sandboxNames: ["alpha"] }, + ); + }); + it("suggests the closest registered sandbox name for a mistyped sandbox action", async () => { await withDirectPublicDispatch( async ({ dispatchCli, exitSpy, stderr }) => { diff --git a/test/e2e/live/sandbox-rlimits-connect.test.ts b/test/e2e/live/sandbox-rlimits-connect.test.ts index 4b39272ea46..d18a17e4b82 100644 --- a/test/e2e/live/sandbox-rlimits-connect.test.ts +++ b/test/e2e/live/sandbox-rlimits-connect.test.ts @@ -25,12 +25,11 @@ function expectNoRlimitStartupDiagnostics(text: string): void { ); } -function connectAcceptanceScript(cliPath: string, sandboxName: string): string { +function connectAcceptanceScript(cliPath: string): string { const cli = JSON.stringify(cliPath); - const sandbox = JSON.stringify(sandboxName); return [ "set -euo pipefail", - `cat <<'NEMOCLAW_CONNECT_RLIMITS' | ${cli} ${sandbox} connect`, + `cat <<'NEMOCLAW_CONNECT_RLIMITS' | ${cli} connect`, "set -euo pipefail", 'printf "__NEMOCLAW_RLIMIT_CONNECT_BEGIN__\\n"', 'bash -lc \'printf "login_nproc=%s\\nlogin_nofile=%s\\n" "$(ulimit -u)" "$(ulimit -n)"; ulimit -a\'', @@ -60,7 +59,7 @@ runConnectRlimitTest( sandboxName: SANDBOX_NAME, acceptancePath: [ "nemoclaw onboard --non-interactive --yes-i-accept-third-party-software", - `nemoclaw ${SANDBOX_NAME} connect`, + "nemoclaw connect (routes through the onboarded default sandbox)", "bash -lc 'ulimit -u; ulimit -n'", "bash -ic 'ulimit -u; ulimit -n'", "ulimit -a", @@ -109,16 +108,12 @@ runConnectRlimitTest( ); expect(onboard.exitCode, resultText(onboard)).toBe(0); - const connect = await host.command( - "bash", - ["-lc", connectAcceptanceScript(host.commandPath, SANDBOX_NAME)], - { - artifactName: "phase-2-connect-rlimits", - env: buildAvailabilityProbeEnv(), - redactionValues, - timeoutMs: 10 * 60_000, - }, - ); + const connect = await host.command("bash", ["-lc", connectAcceptanceScript(host.commandPath)], { + artifactName: "phase-2-connect-rlimits", + env: buildAvailabilityProbeEnv(), + redactionValues, + timeoutMs: 10 * 60_000, + }); const output = resultText(connect); await artifacts.writeText("connect-rlimits-output.txt", output); expect(connect.exitCode, output).toBe(0); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 5ffc07fe892..6d47d2babde 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -24,6 +24,14 @@ "src/lib/onboard/sandbox-create-plan-extra-providers.test.ts", "test/onboard-extra-provider-reconciliation.test.ts" ] + }, + { + "live": "test/e2e/live/sandbox-rlimits-connect.test.ts", + "fast": [ + "test/cli/dispatch-basics.test.ts", + "test/e2e/support/rlimit-connect-workflow-boundary.test.ts", + "test/sandbox-rlimit-hooks.test.ts" + ] } ] } diff --git a/test/support/public-dispatch-test-harness.ts b/test/support/public-dispatch-test-harness.ts index 11a0575d71e..36dd810eee9 100644 --- a/test/support/public-dispatch-test-harness.ts +++ b/test/support/public-dispatch-test-harness.ts @@ -3,11 +3,12 @@ import { vi } from "vitest"; -type SandboxStub = { name: string }; +type SandboxStub = { name: string; pendingRouteReservation?: true }; export type DirectPublicDispatchHarness = { dispatchCli: (argv: string[]) => Promise; exitSpy: ReturnType; + getDefault: ReturnType; getSandbox: ReturnType; listSandboxes: ReturnType; recoverRegistryEntries: ReturnType; @@ -20,6 +21,12 @@ export type DirectPublicDispatchHarness = { type DirectPublicDispatchOptions = { sandboxNames?: readonly string[]; + /** Stored default-sandbox pointer; the stub applies the production fallback contract. */ + defaultSandbox?: string | null; + /** Registered route reservations that are not ready or default-eligible. */ + pendingSandboxNames?: readonly string[]; + /** Args the sandbox-connect stub treats as connect flags (default: none). */ + connectFlags?: readonly string[]; }; const requireCache = require.cache as Record; @@ -60,13 +67,29 @@ export async function withDirectPublicDispatch( const priorRegistryRecovery = requireCache[registryRecoveryPath]; const priorRunner = requireCache[runnerPath]; const priorDockerHost = process.env.DOCKER_HOST; + const pendingSandboxNames = new Set(options.pendingSandboxNames ?? []); const sandboxes = new Map( - (options.sandboxNames ?? []).map((name) => [name, { name }]), + (options.sandboxNames ?? []).map((name) => [ + name, + { + name, + ...(pendingSandboxNames.has(name) ? { pendingRouteReservation: true as const } : {}), + }, + ]), ); const getSandbox = vi.fn((name: string) => sandboxes.get(name) ?? null); + const getDefault = vi.fn(() => { + const storedDefault = options.defaultSandbox ?? null; + const stored = storedDefault ? sandboxes.get(storedDefault) : null; + if (stored && stored.pendingRouteReservation !== true) return storedDefault; + return ( + [...sandboxes.values()].find((sandbox) => sandbox.pendingRouteReservation !== true)?.name ?? + null + ); + }); const listSandboxes = vi.fn(() => ({ sandboxes: [...sandboxes.values()], - defaultSandbox: sandboxes.keys().next().value ?? null, + defaultSandbox: options.defaultSandbox ?? null, })); const recoverRegistryEntries = vi.fn(async () => ({ ...listSandboxes(), @@ -86,6 +109,7 @@ export async function withDirectPublicDispatch( const resetObservedCalls = () => { stderr.length = 0; exitSpy.mockClear(); + getDefault.mockClear(); getSandbox.mockClear(); listSandboxes.mockClear(); recoverRegistryEntries.mockClear(); @@ -93,11 +117,14 @@ export async function withDirectPublicDispatch( runOclifCommandById.mockClear(); }; - cacheModule(registryPath, { getSandbox, listSandboxes }); + cacheModule(registryPath, { getDefault, getSandbox, listSandboxes }); cacheModule(registryRecoveryPath, { recoverRegistryEntries }); cacheModule(oclifRunnerPath, { runOclifArgv, runOclifCommandById }); + const connectFlags = new Set(options.connectFlags ?? []); cacheModule(sandboxConnectPath, { - isSandboxConnectFlag: vi.fn(() => false), + isSandboxConnectFlag: vi.fn((arg: string | undefined) => + typeof arg === "string" ? connectFlags.has(arg) : false, + ), parseSandboxConnectArgs: vi.fn(), printSandboxConnectHelp: vi.fn(), }); @@ -110,6 +137,7 @@ export async function withDirectPublicDispatch( await run({ dispatchCli, exitSpy, + getDefault, getSandbox, listSandboxes, recoverRegistryEntries,