diff --git a/src/lib/credentials.ts b/src/lib/credentials.ts index 391b328ad36..15ddbb04111 100644 --- a/src/lib/credentials.ts +++ b/src/lib/credentials.ts @@ -74,10 +74,7 @@ export function resolveHomeDir(): string { ); } } catch (error) { - if ( - !isErrnoException(error) || - error.code !== "ENOENT" - ) { + if (!isErrnoException(error) || error.code !== "ENOENT") { throw error; } } diff --git a/src/lib/inventory-commands.test.ts b/src/lib/inventory-commands.test.ts index 2e59411f167..a1e2873ee00 100644 --- a/src/lib/inventory-commands.test.ts +++ b/src/lib/inventory-commands.test.ts @@ -50,6 +50,39 @@ describe("inventory commands", () => { ); }); + it("prints the dashboard URL for each sandbox when dashboardPort is set", async () => { + const lines: string[] = []; + await listSandboxesCommand({ + recoverRegistryEntries: async () => ({ + sandboxes: [ + { + name: "alpha", + model: "m", + provider: "p", + gpuEnabled: false, + policies: [], + dashboardPort: 18789, + }, + { + name: "beta", + model: "m", + provider: "p", + gpuEnabled: false, + policies: [], + dashboardPort: 18790, + }, + ], + defaultSandbox: "alpha", + }), + getLiveInference: () => null, + loadLastSession: () => null, + log: (message = "") => lines.push(message), + }); + + expect(lines).toContain(" dashboard: http://127.0.0.1:18789"); + expect(lines).toContain(" dashboard: http://127.0.0.1:18790"); + }); + it("uses live gateway inference for the default sandbox in list output (#2369)", async () => { const lines: string[] = []; await listSandboxesCommand({ @@ -201,6 +234,25 @@ describe("inventory commands", () => { expect(lines).toContain(" (onboarded: provider=configured-provider)"); }); + it("prints the dashboard URL per sandbox in status when dashboardPort is set", () => { + const lines: string[] = []; + showStatusCommand({ + listSandboxes: () => ({ + sandboxes: [ + { name: "alpha", model: "m", dashboardPort: 18789 }, + { name: "beta", model: "m", dashboardPort: 18790 }, + ], + defaultSandbox: "alpha", + }), + getLiveInference: () => null, + showServiceStatus: vi.fn(), + log: (message = "") => lines.push(message), + }); + + expect(lines).toContain(" dashboard: http://127.0.0.1:18789"); + expect(lines).toContain(" dashboard: http://127.0.0.1:18790"); + }); + it("flags messaging bridge as degraded when checkMessagingBridgeHealth reports conflicts", () => { const lines: string[] = []; const checkMessagingBridgeHealth = vi.fn().mockReturnValue([ diff --git a/src/lib/inventory-commands.ts b/src/lib/inventory-commands.ts index ba71f1fd28a..18505bf105d 100644 --- a/src/lib/inventory-commands.ts +++ b/src/lib/inventory-commands.ts @@ -44,10 +44,7 @@ export interface ShowStatusCommandDeps { listSandboxes: () => { sandboxes: SandboxEntry[]; defaultSandbox?: string | null }; getLiveInference: () => GatewayInference | null; showServiceStatus: (options: { sandboxName?: string }) => void; - checkMessagingBridgeHealth?: ( - sandboxName: string, - channels: string[], - ) => MessagingBridgeHealth[]; + checkMessagingBridgeHealth?: (sandboxName: string, channels: string[]) => MessagingBridgeHealth[]; backfillAndFindOverlaps?: () => MessagingOverlap[]; readGatewayLog?: (sandboxName: string) => string | null; log?: (message?: string) => void; @@ -95,7 +92,9 @@ export async function listSandboxesCommand(deps: ListSandboxesCommandDeps): Prom } if ((recovery.recoveredFromGateway || 0) > 0) { const count = recovery.recoveredFromGateway || 0; - log(` Recovered ${count} sandbox entr${count === 1 ? "y" : "ies"} from the live OpenShell gateway.`); + log( + ` Recovered ${count} sandbox entr${count === 1 ? "y" : "ies"} from the live OpenShell gateway.`, + ); log(""); } log(" Sandboxes:"); @@ -118,15 +117,15 @@ export async function listSandboxesCommand(deps: ListSandboxesCommandDeps): Prom const connected = sessionCount !== null && sessionCount > 0 ? " ●" : ""; log(` ${sb.name}${def}${connected}`); log(` model: ${model} provider: ${provider} ${gpu} policies: ${presets}`); + if (typeof sb.dashboardPort === "number") { + log(` dashboard: http://127.0.0.1:${sb.dashboardPort}`); + } if (modelDrifted || providerDrifted) { const parts: string[] = []; if (modelDrifted) parts.push(`model=${sb.model || "unknown"}`); if (providerDrifted) parts.push(`provider=${sb.provider || "unknown"}`); log(` (onboarded: ${parts.join(", ")})`); } - if (sb.dashboardPort != null) { - log(` dashboard: http://127.0.0.1:${sb.dashboardPort}/`); - } } log(""); log(" * = default sandbox"); @@ -155,8 +154,10 @@ export function showStatusCommand(deps: ShowStatusCommandDeps): void { // agrees with `openshell inference get` (#2369). const liveModel = isDefault && live ? live.model : null; const model = liveModel || sb.model; - const portSuffix = sb.dashboardPort != null ? ` :${sb.dashboardPort}` : ""; - log(` ${sb.name}${def}${model ? ` (${model})` : ""}${portSuffix}`); + log(` ${sb.name}${def}${model ? ` (${model})` : ""}`); + if (typeof sb.dashboardPort === "number") { + log(` dashboard: http://127.0.0.1:${sb.dashboardPort}`); + } if (isDefault && liveModel && liveModel !== sb.model) { log(` (onboarded: ${sb.model || "unknown"})`); } @@ -193,9 +194,7 @@ export function showStatusCommand(deps: ShowStatusCommandDeps): void { if (degraded.length > 0) { log(""); for (const { channel, conflicts } of degraded) { - log( - ` ⚠ ${channel} bridge: degraded (${conflicts} conflict errors in /tmp/gateway.log)`, - ); + log(` ⚠ ${channel} bridge: degraded (${conflicts} conflict errors in /tmp/gateway.log)`); } log( " Another sandbox is likely polling with the same bot token. See docs/reference/troubleshooting.md.", diff --git a/src/lib/onboard-command.test.ts b/src/lib/onboard-command.test.ts index 8257651cdf7..b23b9db7be1 100644 --- a/src/lib/onboard-command.test.ts +++ b/src/lib/onboard-command.test.ts @@ -137,6 +137,35 @@ describe("onboard command", () => { }); }); + it("parses --control-ui-port ", () => { + const result = parseOnboardArgs( + ["--resume", "--control-ui-port", "18795"], + "--yes-i-accept-third-party-software", + "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", + { + env: {}, + error: () => {}, + exit: exitWithCode, + }, + ); + expect(result.controlUiPort).toBe(18795); + }); + + it("exits when --control-ui-port is out of range", () => { + expect(() => + parseOnboardArgs( + ["--control-ui-port", "80"], + "--yes-i-accept-third-party-software", + "NEMOCLAW_ACCEPT_THIRD_PARTY_SOFTWARE", + { + env: {}, + error: () => {}, + exit: exitWithPrefixedCode, + }, + ), + ).toThrow("exit:1"); + }); + it("parses --fresh and surfaces it as fresh=true", () => { expect( parseOnboardArgs( diff --git a/src/lib/onboard-command.ts b/src/lib/onboard-command.ts index 44974146866..9bfd621d39d 100644 --- a/src/lib/onboard-command.ts +++ b/src/lib/onboard-command.ts @@ -72,6 +72,28 @@ export function parseOnboardArgs( parsedArgs.splice(fromIdx, 2); } + let controlUiPort: number | null = null; + const controlUiPortIdx = parsedArgs.indexOf("--control-ui-port"); + if (controlUiPortIdx !== -1) { + const raw = parsedArgs[controlUiPortIdx + 1]; + if (typeof raw !== "string" || raw.startsWith("--")) { + error(" --control-ui-port requires a port number"); + printOnboardUsage(error, noticeAcceptFlag); + exit(1); + } + if (!/^\d+$/.test(raw)) { + error(` --control-ui-port '${raw}' must be an integer between 1024-65535`); + exit(1); + } + const parsed = Number(raw); + if (parsed < 1024 || parsed > 65535) { + error(` --control-ui-port '${raw}' must be an integer between 1024-65535`); + exit(1); + } + controlUiPort = parsed; + parsedArgs.splice(controlUiPortIdx, 2); + } + let agent: string | null = null; const agentIdx = parsedArgs.indexOf("--agent"); if (agentIdx !== -1) { @@ -91,25 +113,6 @@ export function parseOnboardArgs( parsedArgs.splice(agentIdx, 2); } - let controlUiPort: number | null = null; - const portIdx = parsedArgs.indexOf("--control-ui-port"); - if (portIdx !== -1) { - const portValue = parsedArgs[portIdx + 1]; - if (typeof portValue !== "string" || portValue.startsWith("--")) { - error(" --control-ui-port requires a port number"); - printOnboardUsage(error, noticeAcceptFlag); - exit(1); - } - const parsed = Number(portValue); - if (!Number.isInteger(parsed) || parsed < 1024 || parsed > 65535) { - error(` --control-ui-port: ${portValue} is not a valid port (1024-65535)`); - printOnboardUsage(error, noticeAcceptFlag); - exit(1); - } - controlUiPort = parsed; - parsedArgs.splice(portIdx, 2); - } - const allowedArgs = new Set([...ONBOARD_BASE_ARGS, noticeAcceptFlag]); const unknownArgs = parsedArgs.filter((arg) => !allowedArgs.has(arg)); if (unknownArgs.length > 0) { @@ -148,7 +151,23 @@ export async function runOnboardCommand(deps: RunOnboardCommandDeps): Promise string | null; getNonInteractiveProvider: () => string | null; getNonInteractiveModel: (providerKey: string) => string | null; - getSandboxInferenceConfig: (model: string, provider?: string | null, preferredInferenceApi?: string | null) => { - providerKey: string; primaryModelRef: string; inferenceBaseUrl: string; inferenceApi: string; inferenceCompat: LooseObject | null; + getSandboxInferenceConfig: ( + model: string, + provider?: string | null, + preferredInferenceApi?: string | null, + ) => { + providerKey: string; + primaryModelRef: string; + inferenceBaseUrl: string; + inferenceApi: string; + inferenceCompat: LooseObject | null; }; }; const { sleepSeconds } = require("./wait"); @@ -282,7 +291,11 @@ const BRAVE_SEARCH_HELP_URL = "https://brave.com/search/api/"; // Re-export shared JSON types under the names used throughout this module. // See src/lib/json-types.ts for the canonical definitions. -import type { JsonScalar as LooseScalar, JsonValue as LooseValue, JsonObject as LooseObject } from "./json-types"; +import type { + JsonScalar as LooseScalar, + JsonValue as LooseValue, + JsonObject as LooseObject, +} from "./json-types"; type OnboardOptions = { nonInteractive?: boolean; @@ -933,8 +946,21 @@ function persistMigratedLegacyKeys(): void { } } -function upsertProvider(name: string, type: string, credentialEnv: string, baseUrl: string | null, env: NodeJS.ProcessEnv = {}) { - const result = onboardProviders.upsertProvider(name, type, credentialEnv, baseUrl, env, runOpenshell); +function upsertProvider( + name: string, + type: string, + credentialEnv: string, + baseUrl: string | null, + env: NodeJS.ProcessEnv = {}, +) { + const result = onboardProviders.upsertProvider( + name, + type, + credentialEnv, + baseUrl, + env, + runOpenshell, + ); if (result.ok && credentialEnv) { const stagedValue = stagedLegacyValues.get(credentialEnv); if (stagedValue !== undefined) { @@ -1387,7 +1413,11 @@ function agentSupportsWebSearch( agent: AgentDefinition | null | undefined, dockerfilePathOverride: string | null = null, ): boolean { - const candidates = [dockerfilePathOverride, agent?.dockerfilePath, path.join(ROOT, "Dockerfile")].filter( + const candidates = [ + dockerfilePathOverride, + agent?.dockerfilePath, + path.join(ROOT, "Dockerfile"), + ].filter( (candidate): candidate is string => typeof candidate === "string" && candidate.length > 0, ); @@ -1468,10 +1498,10 @@ function verifyWebSearchInsideSandbox( if (agentName === "hermes") { // `hermes dump` outputs config_overrides and active toolsets. // Look for the web backend in its output. - const dump = runCaptureOpenshell( - ["sandbox", "exec", sandboxName, "hermes", "dump"], - { ignoreError: true, timeout: 10_000 }, - ); + const dump = runCaptureOpenshell(["sandbox", "exec", sandboxName, "hermes", "dump"], { + ignoreError: true, + timeout: 10_000, + }); if (!dump) { console.warn(" ⚠ Could not verify web search config inside sandbox (hermes dump failed)."); return; @@ -1483,7 +1513,9 @@ function verifyWebSearchInsideSandbox( /^\s*active toolsets:\s*.*\bweb\b/im.test(dump) || /^\s*toolsets:\s*.*\bweb\b/im.test(dump); if (!hasWebBackend) { - console.warn(" ⚠ Web search was configured but Hermes does not report an active web backend."); + console.warn( + " ⚠ Web search was configured but Hermes does not report an active web backend.", + ); console.warn(" The agent may not have accepted the web search configuration."); console.warn(" Check: nemoclaw " + sandboxName + " exec hermes dump"); } else { @@ -1504,7 +1536,9 @@ function verifyWebSearchInsideSandbox( if (parsed?.tools?.web?.search?.enabled) { console.log(" ✓ Web search is active inside sandbox"); } else { - console.warn(" ⚠ Web search was configured but tools.web.search is not enabled in openclaw.json."); + console.warn( + " ⚠ Web search was configured but tools.web.search is not enabled in openclaw.json.", + ); } } catch { console.warn(" ⚠ Could not parse openclaw.json to verify web search config."); @@ -1710,7 +1744,6 @@ const { // nvcfFunctionNotFoundMessage — see validation import above. They live in // src/lib/validation.ts so they can be unit-tested independently. - async function validateOpenAiLikeSelection( label: string, endpointUrl: string, @@ -1891,7 +1924,6 @@ function getRequestedProviderHint(nonInteractive = isNonInteractive()) { } function getRequestedModelHint(nonInteractive = isNonInteractive()) { return onboardProviders.getRequestedModelHint(nonInteractive); - } function getResumeConfigConflicts( @@ -2330,25 +2362,19 @@ async function preflight(): Promise> { console.warn( " ⚠ Container DNS probe inconclusive: docker couldn't pull the busybox test image.", ); - console.warn( - " This usually means the docker daemon itself can't reach Docker Hub,", - ); + console.warn(" This usually means the docker daemon itself can't reach Docker Hub,"); console.warn( " but doesn't prove container DNS is broken — the sandbox build may still succeed.", ); } else { - console.warn( - ` ⚠ Container DNS probe inconclusive (reason: ${dns.reason ?? "unknown"}).`, - ); + console.warn(` ⚠ Container DNS probe inconclusive (reason: ${dns.reason ?? "unknown"}).`); } if (dns.details) { for (const line of String(dns.details).split("\n").slice(-3)) { if (line.trim()) console.warn(` ${line.trim()}`); } } - console.warn( - " Proceeding. If the sandbox build later hangs at `npm ci`, see issue #2101.", - ); + console.warn(" Proceeding. If the sandbox build later hangs at `npm ci`, see issue #2101."); } else { console.error(" ✗ DNS resolution from inside a docker container failed."); if (dns.details) { @@ -2358,18 +2384,10 @@ async function preflight(): Promise> { } console.error(""); { - console.error( - " The sandbox build runs `npm ci` inside a container and needs to resolve", - ); - console.error( - " registry.npmjs.org. On networks that block outbound UDP:53 to public DNS", - ); - console.error( - " (common in corporate environments that force DNS-over-TLS on the host),", - ); - console.error( - " the build appears to hang for ~15 minutes and then prints the cryptic", - ); + console.error(" The sandbox build runs `npm ci` inside a container and needs to resolve"); + console.error(" registry.npmjs.org. On networks that block outbound UDP:53 to public DNS"); + console.error(" (common in corporate environments that force DNS-over-TLS on the host),"); + console.error(" the build appears to hang for ~15 minutes and then prints the cryptic"); console.error(" `npm error Exit handler never called`. See issue #2101."); console.error(""); console.error(" Fix options:"); @@ -2418,9 +2436,7 @@ async function preflight(): Promise> { console.error(" 1. Make systemd-resolved reachable from containers (recommended):"); printLinuxFix(bridgeIp, bridgeNote); console.error(""); - console.error( - " 2. Configure an explicit UDP:53-capable DNS in /etc/docker/daemon.json", - ); + console.error(" 2. Configure an explicit UDP:53-capable DNS in /etc/docker/daemon.json"); console.error(" (ask your IT team for an internal DNS server IP)."); } else if (host.platform === "darwin") { // On macOS, branch by the detected runtime (host.runtime) so users get @@ -2429,9 +2445,7 @@ async function preflight(): Promise> { console.error(" Configure Colima's DNS (macOS):"); console.error(" colima stop"); console.error(" colima start --dns "); - console.error( - " (or edit ~/.colima/default/colima.yaml and `colima restart`)", - ); + console.error(" (or edit ~/.colima/default/colima.yaml and `colima restart`)"); } else if (host.runtime === "docker-desktop" || host.runtime === "docker") { console.error(" Configure Docker Desktop's DNS (macOS):"); console.error( @@ -2449,7 +2463,7 @@ async function preflight(): Promise> { console.error(" Configure your container runtime's DNS (macOS):"); console.error(" - Docker Desktop:"); console.error( - " { jq '. + {\"dns\":[\"\"]}' ~/.docker/daemon.json 2>/dev/null || echo '{\"dns\":[\"\"]}'; } > ~/.docker/daemon.json.new && mv ~/.docker/daemon.json.new ~/.docker/daemon.json", + ' { jq \'. + {"dns":[""]}\' ~/.docker/daemon.json 2>/dev/null || echo \'{"dns":[""]}\'; } > ~/.docker/daemon.json.new && mv ~/.docker/daemon.json.new ~/.docker/daemon.json', ); console.error(" osascript -e 'quit app \"Docker\"' && sleep 3 && open -a Docker"); console.error(" - Colima:"); @@ -2457,13 +2471,9 @@ async function preflight(): Promise> { console.error(" - Rancher Desktop / Podman: edit the runtime's DNS config"); console.error(" and restart it."); } - console.error( - " Ask your IT team for an internal DNS server IP that accepts UDP:53.", - ); + console.error(" Ask your IT team for an internal DNS server IP that accepts UDP:53."); } else if (host.platform === "win32" || host.isWsl) { - console.error( - " 1. Configure Docker Desktop's DNS (Windows / WSL via Docker Desktop):", - ); + console.error(" 1. Configure Docker Desktop's DNS (Windows / WSL via Docker Desktop):"); console.error( " Docker Desktop for Windows → Settings → Docker Engine — edit the JSON to add:", ); @@ -2488,9 +2498,7 @@ async function preflight(): Promise> { } printLinuxFix(wslBridgeIp || "172.17.0.1", wslBridgeNote); } else { - console.error( - " Configure your docker daemon to use a DNS server that accepts UDP:53.", - ); + console.error(" Configure your docker daemon to use a DNS server that accepts UDP:53."); console.error( ' Add { "dns": [""] } to your docker daemon.json and restart the daemon.', ); @@ -3350,13 +3358,18 @@ async function createSandbox( if (process.env.CHAT_UI_URL) { try { const u = new URL( - process.env.CHAT_UI_URL.includes("://") ? process.env.CHAT_UI_URL : `http://${process.env.CHAT_UI_URL}`, + process.env.CHAT_UI_URL.includes("://") + ? process.env.CHAT_UI_URL + : `http://${process.env.CHAT_UI_URL}`, ); const p = Number(u.port); if (p > 0) envPort = p; - } catch { /* malformed URL — ignore */ } + } catch { + /* malformed URL — ignore */ + } } - const preferredPort = controlUiPort ?? envPort ?? persistedPort ?? (agent ? agent.forwardPort : CONTROL_UI_PORT); + const preferredPort = + controlUiPort ?? envPort ?? persistedPort ?? (agent ? agent.forwardPort : CONTROL_UI_PORT); const earlyForwards = runCaptureOpenshell(["forward", "list"], { ignoreError: true }); const effectivePort = findAvailableDashboardPort(sandboxName, preferredPort, earlyForwards); if (effectivePort !== preferredPort) { @@ -3367,7 +3380,9 @@ async function createSandbox( let chatUiUrl: string; if (process.env.CHAT_UI_URL && controlUiPort == null) { const parsed = new URL( - process.env.CHAT_UI_URL.includes("://") ? process.env.CHAT_UI_URL : `http://${process.env.CHAT_UI_URL}`, + process.env.CHAT_UI_URL.includes("://") + ? process.env.CHAT_UI_URL + : `http://${process.env.CHAT_UI_URL}`, ); parsed.port = String(effectivePort); chatUiUrl = parsed.toString().replace(/\/$/, ""); @@ -4042,7 +4057,14 @@ async function createSandbox( const openshellBin = getOpenshellBinary(); for (let i = 0; i < 15; i++) { const readyMatch = runCaptureOpenshell( - ["sandbox", "exec", sandboxName, "curl", "-sf", `http://localhost:${effectiveDashboardPort}/`], + [ + "sandbox", + "exec", + sandboxName, + "curl", + "-sf", + `http://localhost:${effectiveDashboardPort}/`, + ], { ignoreError: true }, ); if (readyMatch) { @@ -5384,7 +5406,9 @@ async function setupMessagingChannels(): Promise { console.log(` ${ch.help}`); const token = normalizeCredentialValue(await prompt(` ${ch.label}: `, { secret: true })); if (token && ch.tokenFormat && !ch.tokenFormat.test(token)) { - console.log(` ✗ Invalid format. ${ch.tokenFormatHint || "Check the token and try again."}`); + console.log( + ` ✗ Invalid format. ${ch.tokenFormatHint || "Check the token and try again."}`, + ); console.log(` Skipped ${ch.name} (invalid token format)`); enabled.delete(ch.name); continue; @@ -6238,7 +6262,9 @@ async function setupPoliciesWithSelection( // the sandbox with no presets. Warn, optionally suggest the intended // variable, and fall through to the tier-derived suggestions list. console.warn(` Unsupported NEMOCLAW_POLICY_MODE: ${policyMode}`); - console.warn(" Valid values: suggested, custom, skip (aliases: default/auto, list, none/no)."); + console.warn( + " Valid values: suggested, custom, skip (aliases: default/auto, list, none/no).", + ); if (tiers.getTier(policyMode)) { console.warn( ` '${policyMode}' is a policy tier — did you mean NEMOCLAW_POLICY_TIER=${policyMode}?`, @@ -6386,7 +6412,7 @@ function findDashboardForwardOwner( /** * Parse `openshell forward list` output into a Map. - * Only includes running forwards — stopped/stale entries are ignored so + * Only includes active/running forwards — stopped/stale entries are ignored so * they don't block port allocation or cause false "range exhausted" errors. * * Output format (columns separated by whitespace): @@ -6401,7 +6427,7 @@ function getOccupiedPorts(forwardListOutput: string | null): Map // parts: [sandbox, bind, port, pid, status...] if (parts.length < 3 || !/^\d+$/.test(parts[2])) continue; const status = (parts[4] || "").toLowerCase(); - if (status !== "running") continue; + if (status !== "running" && status !== "active") continue; occupied.set(parts[2], parts[0]); } return occupied; @@ -6413,10 +6439,9 @@ function getOccupiedPorts(forwardListOutput: string | null): Map */ function isPortBoundOnHost(port: number): boolean { try { - const out = runCapture( - ["lsof", "-i", `:${port}`, "-sTCP:LISTEN", "-P", "-n"], - { ignoreError: true }, - ); + const out = runCapture(["lsof", "-i", `:${port}`, "-sTCP:LISTEN", "-P", "-n"], { + ignoreError: true, + }); return !!out && out.trim().length > 0; } catch { return false; @@ -6431,7 +6456,11 @@ function isPortBoundOnHost(port: number): boolean { * non-OpenShell processes are skipped. * Throws if the entire range is exhausted. */ -function findAvailableDashboardPort(sandboxName: string, preferredPort: number, forwardListOutput: string | null): number { +function findAvailableDashboardPort( + sandboxName: string, + preferredPort: number, + forwardListOutput: string | null, +): number { const occupied = getOccupiedPorts(forwardListOutput); const preferredStr = String(preferredPort); const owner = occupied.get(preferredStr) ?? null; @@ -6449,7 +6478,9 @@ function findAvailableDashboardPort(sandboxName: string, preferredPort: number, } const owners = [...occupied.entries()] - .filter(([p]) => Number(p) >= DASHBOARD_PORT_RANGE_START && Number(p) <= DASHBOARD_PORT_RANGE_END) + .filter( + ([p]) => Number(p) >= DASHBOARD_PORT_RANGE_START && Number(p) <= DASHBOARD_PORT_RANGE_END, + ) .map(([p, s]) => ` ${p} → ${s}`) .join("\n"); throw new Error( @@ -6463,7 +6494,10 @@ function findAvailableDashboardPort(sandboxName: string, preferredPort: number, * port if the preferred port is taken by a different sandbox (Fixes #2174). * Returns the actual port number used. */ -function ensureDashboardForward(sandboxName: string, chatUiUrl = `http://127.0.0.1:${CONTROL_UI_PORT}`): number { +function ensureDashboardForward( + sandboxName: string, + chatUiUrl = `http://127.0.0.1:${CONTROL_UI_PORT}`, +): number { const preferredPort = Number(getDashboardForwardPort(chatUiUrl)); const existingForwards = runCaptureOpenshell(["forward", "list"], { ignoreError: true }); const actualPort = findAvailableDashboardPort(sandboxName, preferredPort, existingForwards); @@ -6642,10 +6676,12 @@ function getWslHostAddress( } const runCaptureFn = options.runCapture || runCapture; const output = runCaptureFn(["hostname", "-I"], { ignoreError: true }); - return String(output || "") - .trim() - .split(/\s+/) - .filter(Boolean)[0] || null; + return ( + String(output || "") + .trim() + .split(/\s+/) + .filter(Boolean)[0] || null + ); } function getDashboardAccessInfo( @@ -6664,8 +6700,16 @@ function getDashboardAccessInfo( const token = Object.prototype.hasOwnProperty.call(options, "token") ? options.token : fetchGatewayAuthTokenFromSandbox(sandboxName); + // Precedence: caller-supplied > CHAT_UI_URL env > stored dashboardPort > default. + // The stored-port tier ensures the completion banner shows the port actually + // allocated by ensureDashboardForward, not the original default (#2174). + const storedPort = registry.getSandbox(sandboxName)?.dashboardPort; + const storedUrl = typeof storedPort === "number" ? `http://127.0.0.1:${storedPort}` : null; const chatUiUrl = - options.chatUiUrl || process.env.CHAT_UI_URL || `http://127.0.0.1:${CONTROL_UI_PORT}`; + options.chatUiUrl || + process.env.CHAT_UI_URL || + storedUrl || + `http://127.0.0.1:${CONTROL_UI_PORT}`; const chain = buildDashboardChain(chatUiUrl, options); const dashboardAccess = buildControlUiUrls(token, chain.port, chain.accessUrl).map( (url, index) => ({ @@ -6695,10 +6739,16 @@ function getDashboardGuidanceLines( platform?: NodeJS.Platform; release?: string; isWsl?: boolean; + sandboxName?: string; } = {}, ): string[] { + const storedPort = options.sandboxName && registry.getSandbox(options.sandboxName)?.dashboardPort; + const storedUrl = typeof storedPort === "number" ? `http://127.0.0.1:${storedPort}` : null; const chatUiUrl = - options.chatUiUrl || process.env.CHAT_UI_URL || `http://127.0.0.1:${CONTROL_UI_PORT}`; + options.chatUiUrl || + process.env.CHAT_UI_URL || + storedUrl || + `http://127.0.0.1:${CONTROL_UI_PORT}`; const chain = buildDashboardChain(chatUiUrl, options); const guidance = [`Port ${String(chain.port)} must be forwarded before opening these URLs.`]; if (isWsl(options)) { @@ -6726,14 +6776,18 @@ function printDashboard( const providerLabel = getProviderLabel(provider); const token = fetchGatewayAuthTokenFromSandbox(sandboxName); - const chatUiUrl = process.env.CHAT_UI_URL || `http://127.0.0.1:${CONTROL_UI_PORT}`; + // Use the same stored-port precedence logic as getDashboardAccessInfo (#2174) + const storedPort = registry.getSandbox(sandboxName)?.dashboardPort; + const storedUrl = typeof storedPort === "number" ? `http://127.0.0.1:${storedPort}` : null; + const chatUiUrl = process.env.CHAT_UI_URL || storedUrl || `http://127.0.0.1:${CONTROL_UI_PORT}`; const wslAddr = getWslHostAddress(); const chain = buildChain({ chatUiUrl, isWsl: isWsl(), wslHostAddress: wslAddr }); // Build access info inline — uses chain instead of re-deriving from env - const dashboardAccess = buildControlUiUrls(token, chain.port, chain.accessUrl).map( - (url, i) => ({ label: i === 0 ? "Dashboard" : `Alt ${i}`, url }), - ); + const dashboardAccess = buildControlUiUrls(token, chain.port, chain.accessUrl).map((url, i) => ({ + label: i === 0 ? "Dashboard" : `Alt ${i}`, + url, + })); if (wslAddr) { const wslUrl = `http://${wslAddr}:${chain.port}/${token ? `#token=${encodeURIComponent(token)}` : ""}`; const existing = dashboardAccess.find((a) => a.url === wslUrl); @@ -6741,7 +6795,10 @@ function printDashboard( else dashboardAccess.push({ label: "VS Code/WSL", url: wslUrl }); } const guidanceLines = [`Port ${chain.port} must be forwarded before opening these URLs.`]; - if (isWsl()) guidanceLines.push("WSL detected: if localhost fails in Windows, use the WSL host IP shown by `hostname -I`."); + if (isWsl()) + guidanceLines.push( + "WSL detected: if localhost fails in Windows, use the WSL host IP shown by `hostname -I`.", + ); if (dashboardAccess.length === 0) guidanceLines.push("No dashboard URLs were generated."); console.log(""); @@ -7285,7 +7342,9 @@ async function onboard(opts: OnboardOptions = {}): Promise { const webSearchSupportProbePath = fromDockerfile ? path.resolve(fromDockerfile) : null; if (webSearchConfig && !agentSupportsWebSearch(agent, webSearchSupportProbePath)) { - note(` Web search is not yet supported by ${agent?.displayName ?? "this sandbox image"}. Clearing stale config.`); + note( + ` Web search is not yet supported by ${agent?.displayName ?? "this sandbox image"}. Clearing stale config.`, + ); webSearchConfig = null; if (session) { session.webSearchConfig = null; @@ -7489,14 +7548,11 @@ async function onboard(opts: OnboardOptions = {}): Promise { // never received the legacy secret, so unlinking the file would // strand the user's only copy. const allStagedMigrated = - stagedLegacyKeys.length > 0 && - stagedLegacyKeys.every((k) => migratedLegacyKeys.has(k)); + stagedLegacyKeys.length > 0 && stagedLegacyKeys.every((k) => migratedLegacyKeys.has(k)); if (allStagedMigrated) { removeLegacyCredentialsFile(); } else if (stagedLegacyKeys.length > 0) { - const unmigrated = stagedLegacyKeys.filter( - (k) => !migratedLegacyKeys.has(k), - ); + const unmigrated = stagedLegacyKeys.filter((k) => !migratedLegacyKeys.has(k)); console.error( ` Kept ~/.nemoclaw/credentials.json: ${String(unmigrated.length)} ` + `legacy credential(s) were not migrated verbatim to the gateway in this run ` + diff --git a/src/lib/openshell.test.ts b/src/lib/openshell.test.ts index 066c968be91..8e346afc086 100644 --- a/src/lib/openshell.test.ts +++ b/src/lib/openshell.test.ts @@ -39,6 +39,16 @@ function stubSpawnSync(spec: SpawnResultSpec): OpenshellSpawnSync { return () => makeSpawnResult(spec); } +function stubSpawnSyncWithOptions( + spec: SpawnResultSpec, + onOptions: (options: Parameters[2]) => void, +): OpenshellSpawnSync { + return (_command, _args, options) => { + onOptions(options); + return makeSpawnResult(spec); + }; +} + function exitWithCode(code: number): never { throw new Error(`exit:${code}`); } @@ -94,6 +104,25 @@ describe("openshell helpers", () => { expect(result.status).toBe(0); }); + it("passes timeout through to run and capture calls", () => { + const seen: number[] = []; + runOpenshellCommand("openshell", ["status"], { + timeout: 1234, + spawnSyncImpl: stubSpawnSyncWithOptions( + { status: 0, stdout: "ok\n", stderr: "" }, + (options) => seen.push(options.timeout as number), + ), + }); + captureOpenshellCommand("openshell", ["status"], { + timeout: 5678, + spawnSyncImpl: stubSpawnSyncWithOptions( + { status: 0, stdout: "ok\n", stderr: "" }, + (options) => seen.push(options.timeout as number), + ), + }); + expect(seen).toEqual([1234, 5678]); + }); + it("uses the injected exit handler on failure", () => { expect(() => runOpenshellCommand("openshell", ["status"], { @@ -142,6 +171,32 @@ describe("openshell helpers", () => { expect(errors).toEqual([" Failed to start openshell status: spawn ENOENT"]); }); + it("returns timed-out capture output when a timeout was requested", () => { + const result = captureOpenshellCommand("openshell", ["status"], { + timeout: 100, + spawnSyncImpl: stubSpawnSync({ + status: null, + stdout: "", + stderr: "timed out\n", + error: new Error("ETIMEDOUT"), + }), + }); + expect(result).toEqual({ status: 1, output: "timed out" }); + }); + + it("returns ignored run spawn failures instead of exiting", () => { + const result = runOpenshellCommand("openshell", ["status"], { + ignoreError: true, + spawnSyncImpl: stubSpawnSync({ + status: null, + stdout: "", + stderr: "", + error: new Error("ETIMEDOUT"), + }), + }); + expect(result.error?.message).toBe("ETIMEDOUT"); + }); + it("reads the installed openshell version through the capture helper", () => { const version = getInstalledOpenshellVersion("openshell", { spawnSyncImpl: stubSpawnSync({ diff --git a/src/lib/openshell.ts b/src/lib/openshell.ts index 82161a8b175..01414e2a6c0 100644 --- a/src/lib/openshell.ts +++ b/src/lib/openshell.ts @@ -25,10 +25,12 @@ interface OpenshellSpawnOptions { export interface RunOpenshellOptions extends OpenshellSpawnOptions { stdio?: SpawnSyncOptions["stdio"]; ignoreError?: boolean; + timeout?: number; } export interface CaptureOpenshellOptions extends OpenshellSpawnOptions { ignoreError?: boolean; + timeout?: number; } export interface CaptureOpenshellResult { @@ -87,8 +89,12 @@ export function runOpenshellCommand( env: { ...process.env, ...opts.env }, encoding: "utf-8", stdio: opts.stdio ?? "inherit", + timeout: opts.timeout, }); if (result.error) { + if (opts.ignoreError) { + return result; + } return handleSpawnError(binary, args, result.error, opts); } if (result.status !== 0 && !opts.ignoreError) { @@ -111,8 +117,15 @@ export function captureOpenshellCommand( env: { ...process.env, ...opts.env }, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], + timeout: opts.timeout, }); if (result.error) { + if (opts.ignoreError || opts.timeout !== undefined) { + return { + status: result.status ?? 1, + output: `${result.stdout || ""}${opts.ignoreError ? "" : result.stderr || ""}`.trim(), + }; + } return handleSpawnError(binary, args, result.error, opts); } return { diff --git a/src/lib/ports.test.ts b/src/lib/ports.test.ts index 3769c2bf8bd..dd1fc2b7d27 100644 --- a/src/lib/ports.test.ts +++ b/src/lib/ports.test.ts @@ -3,7 +3,7 @@ import { describe, it, expect, beforeEach, afterEach } from "vitest"; // Import from compiled dist/ so coverage is attributed correctly. -import { parsePort } from "../../dist/lib/ports"; +import { parsePort, findFreeDashboardPort } from "../../dist/lib/ports"; describe("parsePort", () => { const ENV_KEY = "TEST_PORT"; @@ -70,3 +70,53 @@ describe("parsePort", () => { expect(() => parsePort(ENV_KEY, 8080)).toThrow("Invalid port"); }); }); + +describe("findFreeDashboardPort", () => { + it("skips ports already held by openshell forwards", () => { + const port = findFreeDashboardPort(18789, { + probe: { + listForwardPorts: () => [18789, 18790], + probePortFree: () => true, + }, + }); + expect(port).toBe(18791); + }); + + it("skips ports bound by other host processes", () => { + const bound = new Set([18789, 18790]); + const port = findFreeDashboardPort(18789, { + probe: { + listForwardPorts: () => [], + probePortFree: (p) => !bound.has(p), + }, + }); + expect(port).toBe(18791); + }); + + it("returns null when the 10-port window is exhausted", () => { + const allHeld = Array.from({ length: 10 }, (_, i) => 18789 + i); + const port = findFreeDashboardPort(18789, { + probe: { + listForwardPorts: () => allHeld, + probePortFree: () => true, + }, + }); + expect(port).toBeNull(); + }); + + it("does not allocate ports above 65535 when preferred is near the upper bound", () => { + const port = findFreeDashboardPort(65535, { + probe: { + listForwardPorts: () => [65535], + probePortFree: () => true, + }, + }); + expect(port).toBeNull(); + }); + + it("returns null when preferred port is out of range", () => { + expect(findFreeDashboardPort(0)).toBeNull(); + expect(findFreeDashboardPort(65536)).toBeNull(); + expect(findFreeDashboardPort(1023)).toBeNull(); + }); +}); diff --git a/src/lib/ports.ts b/src/lib/ports.ts index 15c741c4555..3b730c180ca 100644 --- a/src/lib/ports.ts +++ b/src/lib/ports.ts @@ -15,15 +15,11 @@ export function parsePort(envVar: string, fallback: number): number { if (raw === undefined || raw === "") return fallback; const trimmed = String(raw).trim(); if (!/^\d+$/.test(trimmed)) { - throw new Error( - `Invalid port: ${envVar}="${raw}" — must be an integer between 1024 and 65535`, - ); + throw new Error(`Invalid port: ${envVar}="${raw}" — must be an integer between 1024 and 65535`); } const parsed = Number(trimmed); if (parsed < 1024 || parsed > 65535) { - throw new Error( - `Invalid port: ${envVar}="${raw}" — must be an integer between 1024 and 65535`, - ); + throw new Error(`Invalid port: ${envVar}="${raw}" — must be an integer between 1024 and 65535`); } return parsed; } @@ -50,3 +46,41 @@ export const VLLM_PORT = parsePort("NEMOCLAW_VLLM_PORT", 8000); export const OLLAMA_PORT = parsePort("NEMOCLAW_OLLAMA_PORT", 11434); /** Ollama auth proxy port (default 11435, override via NEMOCLAW_OLLAMA_PROXY_PORT). */ export const OLLAMA_PROXY_PORT = parsePort("NEMOCLAW_OLLAMA_PROXY_PORT", 11435); + +/** + * Injectable probes so tests can drive `findFreeDashboardPort` without touching + * real openshell or real sockets. + */ +export interface PortProbe { + listForwardPorts: () => number[]; + probePortFree: (port: number) => boolean; +} + +/** + * Try up to 10 ports starting at the preferred port before giving up. + * Anything beyond that and the operator has bigger problems; fail loudly. + */ +const PORT_WINDOW = 10; + +/** + * Find a free dashboard port, preferring `preferred` and walking upward. + * Skips ports already claimed by openshell forwards and ports bound by + * other host processes. Returns null if the 10-port window is exhausted. + */ +export function findFreeDashboardPort( + preferred: number, + options: { probe?: PortProbe } = {}, +): number | null { + if (!Number.isInteger(preferred) || preferred < 1024 || preferred > 65535) { + return null; + } + const probe = options.probe; + const held = new Set(probe?.listForwardPorts() ?? []); + const isFree = probe?.probePortFree ?? (() => true); + for (let offset = 0; offset < PORT_WINDOW; offset++) { + const port = preferred + offset; + if (port > 65535) break; + if (!held.has(port) && isFree(port)) return port; + } + return null; +} diff --git a/src/lib/registry.ts b/src/lib/registry.ts index 651255aeba5..58e00cdf7fe 100644 --- a/src/lib/registry.ts +++ b/src/lib/registry.ts @@ -31,6 +31,7 @@ export interface SandboxEntry { providerCredentialHashes?: Record; messagingChannels?: string[]; disabledChannels?: string[]; + /** Host-side port for the openshell forward to the OpenClaw dashboard (#2174). */ dashboardPort?: number | null; } @@ -77,10 +78,7 @@ export function acquireLock(): void { } return; } catch (error) { - if ( - !isErrnoException(error) || - error.code !== "EEXIST" - ) { + if (!isErrnoException(error) || error.code !== "EEXIST") { throw error; } let ownerChecked = false; @@ -93,10 +91,7 @@ export function acquireLock(): void { process.kill(ownerPid, 0); alive = true; } catch (killErr) { - alive = - isErrnoException(killErr) - ? killErr.code === "EPERM" - : false; + alive = isErrnoException(killErr) ? killErr.code === "EPERM" : false; } if (!alive) { const recheck = Number.parseInt(fs.readFileSync(LOCK_OWNER, "utf-8").trim(), 10); @@ -130,20 +125,14 @@ export function releaseLock(): void { try { fs.unlinkSync(LOCK_OWNER); } catch (error) { - if ( - !isErrnoException(error) || - error.code !== "ENOENT" - ) { + if (!isErrnoException(error) || error.code !== "ENOENT") { throw error; } } try { fs.rmSync(LOCK_DIR, { recursive: true, force: true }); } catch (error) { - if ( - !isErrnoException(error) || - error.code !== "ENOENT" - ) { + if (!isErrnoException(error) || error.code !== "ENOENT") { throw error; } } @@ -202,7 +191,12 @@ export function registerSandbox(entry: SandboxEntry): void { Array.isArray(entry.disabledChannels) && entry.disabledChannels.length > 0 ? [...entry.disabledChannels] : undefined, - dashboardPort: entry.dashboardPort ?? undefined, + dashboardPort: + Number.isInteger(entry.dashboardPort) && + (entry.dashboardPort as number) >= 1024 && + (entry.dashboardPort as number) <= 65535 + ? entry.dashboardPort + : undefined, }; if (!data.defaultSandbox) { data.defaultSandbox = entry.name; diff --git a/src/nemoclaw.ts b/src/nemoclaw.ts index 42c45f65e62..fd91c476cc6 100644 --- a/src/nemoclaw.ts +++ b/src/nemoclaw.ts @@ -38,10 +38,7 @@ const { isNonInteractive, } = require("./lib/onboard"); const { parseGatewayTokenArgs, runGatewayTokenCommand } = require("./lib/gateway-token-command"); -const { - getCredential, - prompt: askPrompt, -} = require("./lib/credentials"); +const { getCredential, prompt: askPrompt } = require("./lib/credentials"); const registry = require("./lib/registry"); import type { SandboxEntry } from "./lib/registry"; const nim = require("./lib/nim"); @@ -131,6 +128,7 @@ const REMOTE_UNINSTALL_URL = buildVersionedUninstallUrl(getVersion()); let OPENSHELL_BIN: string | null = null; const NEMOCLAW_GATEWAY_NAME = "nemoclaw"; const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT); +const OPENSHELL_PROBE_TIMEOUT_MS = 15_000; function getOpenshellBinary(): string { if (!OPENSHELL_BIN) { @@ -178,7 +176,10 @@ function cleanupGatewayAfterLastSandbox() { } function hasNoLiveSandboxes() { - const liveList = captureOpenshell(["sandbox", "list"], { ignoreError: true }); + const liveList = captureOpenshell(["sandbox", "list"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); if (liveList.status !== 0) { return false; } @@ -216,6 +217,7 @@ function executeSandboxCommand(sandboxName: string, command: string): SandboxCom ignoreError: true, }); if (sshConfigResult.status !== 0) return null; + if (!sshConfigResult.output.trim()) return null; const tmpFile = path.join(os.tmpdir(), `nemoclaw-ssh-${process.pid}-${Date.now()}.conf`); fs.writeFileSync(tmpFile, sshConfigResult.output, { mode: 0o600 }); @@ -503,7 +505,10 @@ async function recoverRegistryFromLiveGateway( } let recoveredFromGateway = 0; - const liveList = captureOpenshell(["sandbox", "list"], { ignoreError: true }); + const liveList = captureOpenshell(["sandbox", "list"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); const liveNames = Array.from(parseLiveSandboxNames(liveList.output)); for (const name of liveNames) { const metadata = metadataByName.get(name) || undefined; @@ -565,8 +570,10 @@ function getActiveGatewayName(output = ""): string | null { } function getNamedGatewayLifecycleState() { - const status = captureOpenshell(["status"]); - const gatewayInfo = captureOpenshell(["gateway", "info", "-g", "nemoclaw"]); + const status = captureOpenshell(["status"], { timeout: OPENSHELL_PROBE_TIMEOUT_MS }); + const gatewayInfo = captureOpenshell(["gateway", "info", "-g", "nemoclaw"], { + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); const cleanStatus = stripAnsi(status.output); const activeGateway = getActiveGatewayName(status.output); const connected = /^\s*Status:\s*Connected\b/im.test(cleanStatus); @@ -621,7 +628,10 @@ async function recoverNamedGatewayRuntime() { return { recovered: true, before, after: before, attempted: false }; } - runOpenshell(["gateway", "select", "nemoclaw"], { ignoreError: true }); + runOpenshell(["gateway", "select", "nemoclaw"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); let after = getNamedGatewayLifecycleState(); if (after.state === "healthy_named") { process.env.OPENSHELL_GATEWAY = "nemoclaw"; @@ -639,7 +649,10 @@ async function recoverNamedGatewayRuntime() { // Fall through to the lifecycle re-check below so we preserve the // existing recovery result shape and emit the correct classification. } - runOpenshell(["gateway", "select", "nemoclaw"], { ignoreError: true }); + runOpenshell(["gateway", "select", "nemoclaw"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); after = getNamedGatewayLifecycleState(); if (after.state === "healthy_named") { process.env.OPENSHELL_GATEWAY = "nemoclaw"; @@ -652,7 +665,9 @@ async function recoverNamedGatewayRuntime() { /** Query sandbox presence and return its output with the live enforced policy. */ function getSandboxGatewayState(sandboxName: string) { - const result = captureOpenshell(["sandbox", "get", sandboxName]); + const result = captureOpenshell(["sandbox", "get", sandboxName], { + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); let output = result.output; if (result.status === 0) { // `openshell sandbox get` returns the immutable baseline policy from sandbox @@ -662,6 +677,7 @@ function getSandboxGatewayState(sandboxName: string) { // Sandbox info above it. (#1132) const livePolicy = captureOpenshell(["policy", "get", "--full", sandboxName], { ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, }); if (livePolicy.status === 0 && livePolicy.output.trim()) { const rawLines = String(output).split("\n"); @@ -723,7 +739,10 @@ function reconcileMissingAgainstNamedGateway( ) { const lifecycle = getNamedGatewayLifecycleState(); if (lifecycle.state === "connected_other") { - runOpenshell(["gateway", "select", "nemoclaw"], { ignoreError: true }); + runOpenshell(["gateway", "select", "nemoclaw"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); const retry = getSandboxGatewayState(sandboxName); if (retry.state === "present") { return { ...retry, recoveredGateway: true, recoveryVia: "select" }; @@ -1214,11 +1233,19 @@ async function credentialsCommand(args: string[]): Promise { console.log(" Usage: nemoclaw credentials "); console.log(""); console.log(" Subcommands:"); - console.log(" list List provider credentials registered with the OpenShell gateway"); - console.log(" reset [--yes] Remove a provider credential so onboard re-prompts"); + console.log( + " list List provider credentials registered with the OpenShell gateway", + ); + console.log( + " reset [--yes] Remove a provider credential so onboard re-prompts", + ); console.log(""); - console.log(" Credentials live in the OpenShell gateway. Inspect with `openshell provider list`."); - console.log(" Nothing is persisted to host disk; deploy/non-onboard commands read from env vars."); + console.log( + " Credentials live in the OpenShell gateway. Inspect with `openshell provider list`.", + ); + console.log( + " Nothing is persisted to host disk; deploy/non-onboard commands read from env vars.", + ); console.log(""); return; } @@ -1293,9 +1320,7 @@ async function credentialsCommand(args: string[]): Promise { // the gateway provider list could tear down a running bridge and // leave the sandbox in a half-configured state. if (isBridgeProviderName(key)) { - console.error( - ` '${key}' is a per-sandbox messaging bridge, not a credential.`, - ); + console.error(` '${key}' is a per-sandbox messaging bridge, not a credential.`); console.error( " Use `nemoclaw channels remove ` to retire", ); @@ -1309,7 +1334,9 @@ async function credentialsCommand(args: string[]): Promise { } const skipPrompt = args.includes("--yes") || args.includes("-y"); if (!skipPrompt) { - const answer = (await askPrompt(` Remove provider '${key}' from the OpenShell gateway? [y/N]: `)) + const answer = ( + await askPrompt(` Remove provider '${key}' from the OpenShell gateway? [y/N]: `) + ) .trim() .toLowerCase(); if (answer !== "y" && answer !== "yes") { @@ -1453,7 +1480,12 @@ function showStatus() { showStatusCommand({ listSandboxes: () => registry.listSandboxes(), getLiveInference: () => - parseGatewayInference(captureOpenshell(["inference", "get"], { ignoreError: true }).output), + parseGatewayInference( + captureOpenshell(["inference", "get"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }).output, + ), showServiceStatus, checkMessagingBridgeHealth, backfillAndFindOverlaps, @@ -1479,7 +1511,12 @@ async function listSandboxes(): Promise { await listSandboxesCommand({ recoverRegistryEntries: () => recoverRegistryEntries(), getLiveInference: () => - parseGatewayInference(captureOpenshell(["inference", "get"], { ignoreError: true }).output), + parseGatewayInference( + captureOpenshell(["inference", "get"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }).output, + ), loadLastSession: () => onboardSession.loadSession(), getActiveSessionCount: sessionDeps ? (name: string) => { @@ -1695,7 +1732,10 @@ async function sandboxConnect( async function sandboxStatus(sandboxName: string) { const sb = registry.getSandbox(sandboxName); const live = parseGatewayInference( - captureOpenshell(["inference", "get"], { ignoreError: true }).output, + captureOpenshell(["inference", "get"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }).output, ); const currentModel = (live && live.model) || (sb && sb.model) || "unknown"; const currentProvider = (live && live.provider) || (sb && sb.provider) || "unknown"; @@ -1718,6 +1758,9 @@ async function sandboxStatus(sandboxName: string) { } console.log(` GPU: ${sb.gpuEnabled ? "yes" : "no"}`); console.log(` Policies: ${(sb.policies || []).join(", ") || "none"}`); + if (typeof sb.dashboardPort === "number") { + console.log(` Dashboard: http://127.0.0.1:${sb.dashboardPort}`); + } // Active session indicator try { @@ -2217,7 +2260,9 @@ async function applyChannelRemoveToGatewayAndRegistry( const recovery = await recoverNamedGatewayRuntime(); if (!recovery.recovered) { console.error(" Could not reach the NemoClaw OpenShell gateway to delete the bridge."); - console.error(" Re-run after starting the gateway, or run 'openshell gateway start --name nemoclaw'."); + console.error( + " Re-run after starting the gateway, or run 'openshell gateway start --name nemoclaw'.", + ); process.exit(1); } // Capture each delete's outcome. If any non-NotFound failure surfaces @@ -2746,6 +2791,26 @@ function removeSandboxImage(sandboxName: string) { async function sandboxDestroy(sandboxName: string, args: string[] = []): Promise { const skipConfirm = args.includes("--yes") || args.includes("--force"); + const sb = registry.getSandbox(sandboxName); + + if (!sb) { + const liveList = captureOpenshell(["sandbox", "list"], { + ignoreError: true, + timeout: OPENSHELL_PROBE_TIMEOUT_MS, + }); + if (liveList.status !== 0 || !parseLiveSandboxNames(liveList.output).has(sandboxName)) { + const session = onboardSession.loadSession(); + if (session && session.sandboxName === sandboxName) { + onboardSession.updateSession((s: Session) => { + s.sandboxName = null; + return s; + }); + } + console.log(` Sandbox '${sandboxName}' is not registered locally or live in OpenShell.`); + console.log(` ${G}✓${R} Sandbox '${sandboxName}' destroyed`); + return; + } + } // Active session detection — enrich the confirmation prompt if sessions are active let activeSessionCount = 0; @@ -2781,7 +2846,6 @@ async function sandboxDestroy(sandboxName: string, args: string[] = []): Promise } } - const sb = registry.getSandbox(sandboxName); if (sb && sb.nimContainer) { console.log(` Stopping NIM for '${sandboxName}'...`); nim.stopNimContainerByName(sb.nimContainer); @@ -2981,9 +3045,7 @@ async function sandboxRebuild( console.error(""); console.error(` ${_RD}Rebuild preflight failed:${R} provider credential not found.`); console.error(` The non-interactive recreate step requires ${rebuildCredentialEnv},`); - console.error( - " but it is not set in the environment.", - ); + console.error(" but it is not set in the environment."); console.error(""); console.error(" To fix, do one of:"); console.error(` export ${rebuildCredentialEnv}=`); @@ -3994,7 +4056,9 @@ function help() { ` ${D}• Change inference model: openshell inference set -g nemoclaw --model --provider ${R}`, ); lines.push(` ${D}• Add network presets: use the policy-add command on your sandbox${R}`); - lines.push(` ${D}• Change credentials: credentials reset , then re-run onboard${R}`); + lines.push( + ` ${D}• Change credentials: credentials reset , then re-run onboard${R}`, + ); lines.push(` ${D}• openclaw.json is read-only inside the sandbox (Landlock enforced).${R}`); lines.push(` ${D} To change OpenClaw settings, re-run onboard to rebuild the sandbox.${R}`); diff --git a/test/credentials.test.ts b/test/credentials.test.ts index 79da7d35231..2ce382df3ec 100644 --- a/test/credentials.test.ts +++ b/test/credentials.test.ts @@ -286,11 +286,9 @@ describe("legacy credentials.json migration (two-phase: stage then remove)", () fs.mkdirSync(credsDir, { recursive: true }); // Two megabytes of valid JSON, well above the 1 MiB sanity cap. const filler = "x".repeat(2 * 1024 * 1024); - fs.writeFileSync( - legacyFile, - JSON.stringify({ NVIDIA_API_KEY: `nvapi-${filler}` }), - { mode: 0o600 }, - ); + fs.writeFileSync(legacyFile, JSON.stringify({ NVIDIA_API_KEY: `nvapi-${filler}` }), { + mode: 0o600, + }); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); const credentials = await importCredentialsModule(home); @@ -317,10 +315,7 @@ describe("legacy credentials.json migration (two-phase: stage then remove)", () // A real credentials file at an unrelated path; the attacker plants a // symlink at credentials.json that points at it. const realFile = path.join(home, "real-creds.json"); - fs.writeFileSync( - realFile, - JSON.stringify({ NVIDIA_API_KEY: "nvapi-attacker-controlled" }), - ); + fs.writeFileSync(realFile, JSON.stringify({ NVIDIA_API_KEY: "nvapi-attacker-controlled" })); fs.symlinkSync(realFile, legacyFile); const credentials = await importCredentialsModule(home); @@ -339,11 +334,9 @@ describe("legacy credentials.json migration (two-phase: stage then remove)", () const credsDir = path.join(home, ".nemoclaw"); const legacyFile = path.join(credsDir, "credentials.json"); fs.mkdirSync(credsDir, { recursive: true }); - fs.writeFileSync( - legacyFile, - JSON.stringify({ NVIDIA_API_KEY: "nvapi-survives-crash" }), - { mode: 0o600 }, - ); + fs.writeFileSync(legacyFile, JSON.stringify({ NVIDIA_API_KEY: "nvapi-survives-crash" }), { + mode: 0o600, + }); // --- Process A: stage, then "crash" (we just abandon the env). --- { diff --git a/test/onboard.test.ts b/test/onboard.test.ts index 2d7c6997b32..27ace3a6763 100644 --- a/test/onboard.test.ts +++ b/test/onboard.test.ts @@ -4742,6 +4742,110 @@ const { createSandbox } = require(${onboardPath}); ); }); + it("reuses the stored dashboard port when OpenShell reports the existing forward as active", async () => { + const repoRoot = path.join(import.meta.dirname, ".."); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-active-port-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "reuse-active-dashboard-port.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "onboard.js")); + const runnerPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "runner.js")); + const registryPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "registry.js")); + + fs.mkdirSync(fakeBin, { recursive: true }); + fs.writeFileSync(path.join(fakeBin, "openshell"), "#!/usr/bin/env bash\nexit 0\n", { + mode: 0o755, + }); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); + +const commands = []; +const updates = []; +runner.run = (command, opts = {}) => { + commands.push({ command: _n(command), env: opts.env || null }); + return { status: 0 }; +}; +runner.runCapture = (command) => { + const text = _n(command); + if (text.includes("sandbox get my-assistant")) return "my-assistant"; + if (text.includes("sandbox list")) return "my-assistant Ready"; + if (text.includes("forward list")) return [ + "SANDBOX BIND PORT PID STATUS", + "install 127.0.0.1 18789 11111 active", + "other 127.0.0.1 18790 11112 active", + "third 127.0.0.1 18791 11113 active", + "my-assistant 127.0.0.1 18795 12345 active", + ].join("\n"); + if (text.includes("lsof -i :18789") || text.includes("lsof -i :18790") || text.includes("lsof -i :18791") || text.includes("lsof -i :18795")) { + return "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\nopenshell 12345 runner 10u IPv4 TCP 127.0.0.1:18795 (LISTEN)"; + } + return ""; +}; +registry.getSandbox = () => ({ + name: "my-assistant", + model: "gpt-5.4", + provider: "nvidia-prod", + gpuEnabled: false, + dashboardPort: 18795, +}); +registry.updateSandbox = (_name, patch) => { + updates.push(patch); + return true; +}; + +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + delete process.env.CHAT_UI_URL; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands, updates, chatUiUrl: process.env.CHAT_UI_URL })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = spawnSync(process.execPath, [scriptPath], { + cwd: repoRoot, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + assert.ok( + !result.stderr.includes("Port 18795 is taken"), + `stored port should not be reported as taken:\n${result.stderr}`, + ); + const payload = parseStdoutJson<{ + sandboxName: string; + commands: CommandEntry[]; + updates: Array<{ dashboardPort?: number }>; + chatUiUrl: string; + }>(result.stdout); + assert.equal(payload.sandboxName, "my-assistant"); + assert.equal(payload.chatUiUrl, "http://127.0.0.1:18795"); + assert.ok( + payload.commands.some((entry: CommandEntry) => + /forward start --background (?:0\.0\.0\.0:)?18795 my-assistant/.test(entry.command), + ), + "expected reused sandbox to keep its stored dashboard port 18795", + ); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("18792")), + "did not expect dashboard port ratcheting to a different port", + ); + assert.deepEqual(payload.updates.at(-1), { dashboardPort: 18795 }); + }); + it("prints resume guidance when sandbox image upload times out", () => { const errors: string[] = []; const originalError = console.error;