From 5b2f046f4525560bd54ad91e09acb07f71429105 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 11:29:12 +0530 Subject: [PATCH 01/24] fix(install): manage openshell gateway user service Signed-off-by: San Dang --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/architecture.mdx | 9 +- docs/reference/commands.mdx | 2 +- scripts/install-openshell.sh | 65 +++++ .../run-plan-gateway-service.test.ts | 99 +++++++ src/lib/actions/uninstall/run-plan.ts | 50 ++++ src/lib/onboard.ts | 14 + .../docker-driver-gateway-service.test.ts | 181 +++++++++++- .../onboard/docker-driver-gateway-service.ts | 263 +++++++++++++++++- 9 files changed, 654 insertions(+), 31 deletions(-) create mode 100644 src/lib/actions/uninstall/run-plan-gateway-service.test.ts diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 69354ff4d6d..ee72cea03cb 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries installed. | +| `--keep-openshell` | Leave OpenShell binaries installed. NemoClaw still disables and removes its own marked `~/.config/systemd/user/openshell-gateway.service` user unit when present, and never removes upstream package-managed OpenShell service units. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 1401afd46b9..58859e1b268 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -81,10 +81,11 @@ graph LR The logical diagram above shows how components relate. This section shows what actually runs where on the host. NemoClaw's default Docker-driver topology does not place the sandbox in an embedded k3s cluster. -On Linux, NemoClaw configures and restarts the package-managed OpenShell gateway user service when it is installed, then creates the sandbox as a Docker container. -NemoClaw treats that service as authoritative only when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. -Per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process used by earlier installs. -That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the package-managed handoff has direct nightly coverage. +On Linux, NemoClaw configures and restarts a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. +NemoClaw prefers the upstream package-managed `openshell-gateway.service` when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. +For tarball-installed OpenShell binaries, NemoClaw stages a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. +Arbitrary per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process when no trusted service path is available. +That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. On Apple Silicon macOS, NemoClaw starts the OpenShell Docker-driver gateway and creates the sandbox as a Docker container. In both Docker-driver modes, the sandbox is a Docker container, not a Kubernetes pod. Entrypoint supervisors create the in-container `/tmp/nemoclaw-gateway-local` marker only when they actually launch an in-container gateway, and they normally keep it present while that supervisor is active. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index f77b64a90ea..0035950bdcf 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries installed | +| `--keep-openshell` | Leave OpenShell binaries installed. NemoClaw still disables and removes its own marked `~/.config/systemd/user/openshell-gateway.service` user unit when present, and never removes upstream package-managed OpenShell service units. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/scripts/install-openshell.sh b/scripts/install-openshell.sh index 0c0bf559eb6..9cf8abbd41c 100755 --- a/scripts/install-openshell.sh +++ b/scripts/install-openshell.sh @@ -16,6 +16,70 @@ fail() { exit 1 } +NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" + +upstream_openshell_gateway_service_installed() { + [ -f /usr/local/lib/systemd/user/openshell-gateway.service ] \ + || [ -f /usr/lib/systemd/user/openshell-gateway.service ] \ + || [ -f /lib/systemd/user/openshell-gateway.service ] +} + +install_nemoclaw_openshell_gateway_user_service() { + [ "$OS" = "Linux" ] || return 0 + [ -x "$target_dir/openshell-gateway" ] || return 0 + + local config_home="${XDG_CONFIG_HOME:-$HOME/.config}" + local service_dir="$config_home/systemd/user" + local service_path="$service_dir/openshell-gateway.service" + + if upstream_openshell_gateway_service_installed; then + if [ -f "$service_path" ] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + rm -f "$service_path" + info "Removed NemoClaw OpenShell gateway user service override: $service_path" + fi + return 0 + fi + + local gateway_bin="$target_dir/openshell-gateway" + case "$gateway_bin" in + *[[:space:]]*) + warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" + return 0 + ;; + esac + + if [ -f "$service_path" ] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" + return 0 + fi + + mkdir -p "$service_dir" + chmod 700 "$service_dir" + cat >"$service_path" <&1 || echo openshell) installed" diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts new file mode 100644 index 00000000000..dbd3a471d04 --- /dev/null +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import { + getNemoclawOpenShellGatewayUserServicePath, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + OPENSHELL_GATEWAY_USER_SERVICE, +} from "../../onboard/docker-driver-gateway-service"; +import { type RunResult, runUninstallPlan } from "./run-plan"; + +function ok(stdout = ""): RunResult { + return { status: 0, stdout, stderr: "" }; +} + +describe("uninstall OpenShell gateway user service", () => { + it("removes the NemoClaw-managed user service even when OpenShell binaries are kept", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Service]", + "ExecStart=/home/test/.local/bin/openshell-gateway", + "", + ].join("\n"), + ); + const logs: string[] = []; + const runCalls: string[][] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + log: (line) => logs.push(line), + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => { + runCalls.push([command, ...args]); + return ok(); + }), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + expect(runCalls).toContainEqual([ + "systemctl", + "--user", + "disable", + "--now", + OPENSHELL_GATEWAY_USER_SERVICE, + ]); + expect(runCalls).toContainEqual(["systemctl", "--user", "daemon-reload"]); + expect(logs).toContain(`Removed ${servicePath}`); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("preserves a foreign service file at the NemoClaw service path", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-service-")); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync(servicePath, "[Service]\nExecStart=/tmp/openshell-gateway\n"); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => false, + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + rmSync: fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(true); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); +}); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 282b60394a3..b999d4ff0b6 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -23,6 +23,11 @@ import { providerDeleteSkipMessage, } from "../../domain/uninstall/messaging"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; +import { + getNemoclawOpenShellGatewayUserServicePath, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + OPENSHELL_GATEWAY_USER_SERVICE, +} from "../../onboard/docker-driver-gateway-service"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; import { isModelRouterCommandLineForPort } from "../../onboard/model-router-process"; import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup"; @@ -603,6 +608,50 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { } } +function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): void { + if (process.platform !== "linux") return; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); + if (!runtime.existsSync(servicePath)) return; + + let unit = ""; + try { + unit = fs.readFileSync(servicePath, "utf-8"); + } catch { + runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); + return; + } + if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) { + runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); + return; + } + + if (runtime.commandExists("systemctl")) { + const disable = runtime.run( + "systemctl", + ["--user", "disable", "--now", OPENSHELL_GATEWAY_USER_SERVICE], + { env: runtime.env, stdio: "ignore" }, + ); + if (disable.status === 0) { + runtime.log(`Disabled ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + } else { + runtime.warn(`Failed to disable ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + } + } else { + runtime.warn("systemctl not found; removing NemoClaw gateway user service file only."); + } + + runtime.rmSync(servicePath, { force: true }); + runtime.log(`Removed ${servicePath}`); + + if (runtime.commandExists("systemctl")) { + const reload = runtime.run("systemctl", ["--user", "daemon-reload"], { + env: runtime.env, + stdio: "ignore", + }); + if (reload.status !== 0) runtime.warn("Failed to reload the user systemd manager."); + } +} + function removeOpenShellResources(options: UninstallRunOptions, runtime: UninstallRuntime): void { if (!runtime.commandExists("openshell")) { runtime.warn("openshell not found; skipping gateway/provider/sandbox cleanup."); @@ -895,6 +944,7 @@ function executePlan( if (step.name === "Stopping services") { stopHelperServices(paths, runtime); removeGlob(paths.helperServiceGlob, runtime); + removeNemoclawOpenShellGatewayUserService(runtime); stopMatchingPids( `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, runtime, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index df6934a4fdb..45eb3887e21 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -534,6 +534,8 @@ const { } = require("./onboard/gateway-start-failure") as typeof import("./onboard/gateway-start-failure"); const dockerDriverGatewayEnv: typeof import("./onboard/docker-driver-gateway-env") = require("./onboard/docker-driver-gateway-env"); +const dockerDriverGatewayService: typeof import("./onboard/docker-driver-gateway-service") = + require("./onboard/docker-driver-gateway-service"); const dockerDriverGatewayRuntimeMarker: typeof import("./onboard/docker-driver-gateway-runtime-marker") = require("./onboard/docker-driver-gateway-runtime-marker"); const gatewayBinding: typeof import("./onboard/gateway-binding") = require("./onboard/gateway-binding"); @@ -1985,6 +1987,18 @@ async function startDockerDriverGateway({ const identityGatewayBin = runtimeIdentity?.identityGatewayBin ?? gatewayBin; const { verifySandboxBridgeGatewayReachableOrExit } = require("./onboard/gateway-sandbox-reachability") as typeof import("./onboard/gateway-sandbox-reachability"); + const gatewayService = dockerDriverGatewayService.installNemoclawOpenShellGatewayUserService({ + gatewayBin, + }); + if (gatewayService.installed && gatewayService.path) { + console.log(` Installed OpenShell gateway user service: ${gatewayService.path}`); + } else if (gatewayService.removed && gatewayService.path) { + console.log( + ` Removed NemoClaw OpenShell gateway user service override: ${gatewayService.path}`, + ); + } else if (gatewayService.reason?.startsWith("refusing")) { + console.warn(` OpenShell gateway user service not installed: ${gatewayService.reason}.`); + } if ( await dockerDriverGatewayEnv.startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles, diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index f50515d0cfa..38f8d97d402 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -5,9 +5,14 @@ import { describe, expect, it, vi } from "vitest"; import { createVirtualClock } from "./__test-helpers__/virtual-clock"; import { + buildNemoclawOpenShellGatewayUserService, + getNemoclawOpenShellGatewayUserServicePath, getOpenShellGatewayUserServiceBinaryPaths, getOpenShellGatewayUserServicePaths, + hasNemoclawOpenShellGatewayUserService, hasOpenShellGatewayUserService, + installNemoclawOpenShellGatewayUserService, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, type SpawnSyncLikeResult, startOpenShellGatewayUserService, startPackageManagedDockerDriverGateway, @@ -65,16 +70,51 @@ describe("docker-driver-gateway-service", () => { ]); }); - it("ignores stale per-user service units so standalone fallback remains available", () => { - const existsSync = vi.fn( - (candidate: string) => - candidate === "/home/nvidia/.config/systemd/user/openshell-gateway.service", + it("detects a NemoClaw-managed user service without trusting arbitrary per-user units", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const existsSync = vi.fn((candidate: string) => candidate === servicePath); + const readFileSync = vi.fn((candidate: string) => + candidate === servicePath + ? buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway") + : "", ); - expect(hasOpenShellGatewayUserService({ existsSync, platform: "linux" })).toBe(false); - expect(existsSync.mock.calls.flat()).not.toContain( - "/home/nvidia/.config/systemd/user/openshell-gateway.service", - ); + expect( + hasNemoclawOpenShellGatewayUserService({ + existsSync, + home, + platform: "linux", + readFileSync, + }), + ).toBe(true); + expect( + hasOpenShellGatewayUserService({ existsSync, home, platform: "linux", readFileSync }), + ).toBe(true); + expect( + hasNemoclawOpenShellGatewayUserService({ + existsSync, + home, + platform: "linux", + readFileSync: () => "not managed", + }), + ).toBe(false); + }); + + it("ignores stale per-user service units so standalone fallback remains available", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const existsSync = vi.fn((candidate: string) => candidate === servicePath); + + expect( + hasOpenShellGatewayUserService({ + existsSync, + home, + platform: "linux", + readFileSync: () => "foreign user unit", + }), + ).toBe(false); + expect(existsSync.mock.calls.flat()).toContain(servicePath); }); it("restarts the upstream user service with systemctl --user after validating identity", () => { @@ -93,7 +133,12 @@ describe("docker-driver-gateway-service", () => { spawnSyncImpl, }); - expect(result).toEqual({ attempted: true, fallbackAllowed: false, started: true }); + expect(result).toEqual({ + attempted: true, + fallbackAllowed: false, + serviceName: "openshell-gateway", + started: true, + }); expect(events).toEqual(["daemon-reload", "show", "prepare-env", "enable", "restart"]); expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ ["systemctl", ["--user", "daemon-reload"]], @@ -106,6 +151,120 @@ describe("docker-driver-gateway-service", () => { ]); }); + it("restarts the NemoClaw-managed user service after validating its marker and identity", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const events: string[] = []; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + events.push(args[1] ?? args[0] ?? ""); + return args.includes("show") + ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) + : spawnResult(); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: {}, + existsSync: (candidate) => candidate === servicePath, + home, + platform: "linux", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + spawnSyncImpl, + }); + + expect(result).toEqual({ + attempted: true, + fallbackAllowed: false, + serviceName: "openshell-gateway", + started: true, + }); + expect(events).toEqual(["daemon-reload", "show", "enable", "restart"]); + expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ + ["systemctl", ["--user", "daemon-reload"]], + [ + "systemctl", + ["--user", "show", "openshell-gateway", "--property=FragmentPath", "--property=ExecStart"], + ], + ["systemctl", ["--user", "enable", "openshell-gateway"]], + ["systemctl", ["--user", "restart", "openshell-gateway"]], + ]); + }); + + it("installs the NemoClaw-managed user service without overwriting foreign units", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const writes: Array<{ data: string; path: string }> = []; + + const result = installNemoclawOpenShellGatewayUserService({ + chmodSync: vi.fn(), + existsSync: () => false, + gatewayBin, + home, + mkdirSync: vi.fn() as never, + platform: "linux", + writeFileSync: vi.fn((target, data) => { + writes.push({ data: String(data), path: String(target) }); + }) as never, + }); + + expect(result).toEqual({ installed: true, path: servicePath }); + expect(writes).toHaveLength(1); + expect(writes[0]?.path).toBe(servicePath); + expect(writes[0]?.data).toContain("Description=OpenShell Gateway"); + expect(writes[0]?.data).toContain("EnvironmentFile=-%E/openshell/gateway.env"); + expect(writes[0]?.data).toContain(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER); + expect(writes[0]?.data).toContain(`ExecStart=${gatewayBin}`); + expect(writes[0]?.data).toContain("RestartSec=5s"); + expect(writes[0]?.data).toContain("PrivateTmp=true"); + + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: (candidate) => candidate === servicePath, + gatewayBin, + home, + platform: "linux", + readFileSync: () => "foreign unit", + }), + ).toMatchObject({ + installed: false, + path: servicePath, + reason: "refusing to overwrite a non-NemoClaw gateway user service", + }); + }); + + it("removes a marked user service override when an upstream package service exists", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const removed: string[] = []; + const writes: string[] = []; + + const result = installNemoclawOpenShellGatewayUserService({ + existsSync: (candidate) => + candidate === "/usr/lib/systemd/user/openshell-gateway.service" || + candidate === servicePath, + gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", + home, + platform: "linux", + readFileSync: (candidate) => + candidate === servicePath + ? buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway") + : "", + rmSync: vi.fn((target) => removed.push(String(target))) as never, + writeFileSync: vi.fn((target) => writes.push(String(target))) as never, + }); + + expect(result).toEqual({ + installed: false, + path: servicePath, + reason: "upstream OpenShell gateway service is installed", + removed: true, + }); + expect(removed).toEqual([servicePath]); + expect(writes).toEqual([]); + }); + it("allows standalone fallback when the user systemd manager is unavailable", () => { const result = startOpenShellGatewayUserService({ commandExists: () => true, @@ -213,7 +372,7 @@ describe("docker-driver-gateway-service", () => { fallbackAllowed: true, started: false, }); - expect(result.reason).toContain("not the package-managed OpenShell gateway"); + expect(result.reason).toContain("not a trusted OpenShell gateway"); expect(spawnSyncImpl.mock.calls.map(([, args]) => args.join(" "))).not.toContain( "--user restart openshell-gateway", ); @@ -247,7 +406,7 @@ describe("docker-driver-gateway-service", () => { fallbackAllowed: true, started: false, }); - expect(result.reason).toContain("not the package-managed OpenShell gateway"); + expect(result.reason).toContain("not a trusted OpenShell gateway"); expect(spawnSyncImpl.mock.calls.map(([, args]) => args.join(" "))).not.toContain( "--user restart openshell-gateway", ); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index dcdc0db52a0..6e2bb61303c 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -3,6 +3,7 @@ import { type SpawnSyncOptions, spawnSync } from "node:child_process"; import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { sleepSeconds, waitUntilAsync } from "../core/wait"; @@ -15,13 +16,18 @@ import { import { isDockerDriverGatewayHttpReady } from "./gateway-http-readiness"; export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE = OPENSHELL_GATEWAY_USER_SERVICE; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = + "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; env?: NodeJS.ProcessEnv; existsSync?: (filePath: string) => boolean; + home?: string; platform?: NodeJS.Platform; prepareServiceEnv?: () => void; + readFileSync?: (filePath: string, encoding: BufferEncoding) => string; spawnSyncImpl?: SpawnSyncLike; } @@ -29,9 +35,29 @@ export interface OpenShellGatewayUserServiceStartResult { attempted: boolean; fallbackAllowed: boolean; reason?: string; + serviceName?: string; started: boolean; } +export interface InstallNemoclawOpenShellGatewayUserServiceOptions + extends Pick< + OpenShellGatewayUserServiceOptions, + "existsSync" | "home" | "platform" | "readFileSync" + > { + chmodSync?: (filePath: string, mode: number) => void; + gatewayBin: string | null; + mkdirSync?: typeof fs.mkdirSync; + rmSync?: typeof fs.rmSync; + writeFileSync?: typeof fs.writeFileSync; +} + +export interface InstallNemoclawOpenShellGatewayUserServiceResult { + installed: boolean; + path?: string; + reason?: string; + removed?: boolean; +} + export interface SpawnSyncLikeResult { error?: Error; status: number | null; @@ -73,6 +99,12 @@ interface OpenShellGatewayUserServiceIdentity { fragmentPath: string; } +interface OpenShellGatewayUserServiceTarget { + serviceName: string; + trustedBinaryPaths: string[]; + trustedUnitPaths: string[]; +} + export function getOpenShellGatewayUserServicePaths(): string[] { return [ "/usr/local/lib/systemd/user/openshell-gateway.service", @@ -85,7 +117,46 @@ export function getOpenShellGatewayUserServiceBinaryPaths(): string[] { return ["/usr/local/bin/openshell-gateway", "/usr/bin/openshell-gateway"]; } -export function hasOpenShellGatewayUserService( +export function getNemoclawOpenShellGatewayUserServicePath(home = os.homedir()): string { + return path.join(home, ".config", "systemd", "user", "openshell-gateway.service"); +} + +export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.homedir()): string[] { + return [ + path.join(home, ".local", "bin", "openshell-gateway"), + ...getOpenShellGatewayUserServiceBinaryPaths(), + ]; +} + +function readTextFileIfPresent( + filePath: string, + opts: Pick = {}, +): string { + const readFileSync = opts.readFileSync ?? fs.readFileSync; + try { + return readFileSync(filePath, "utf-8"); + } catch (error) { + if ( + error instanceof Error && + "code" in error && + (error as NodeJS.ErrnoException).code === "ENOENT" + ) { + return ""; + } + return ""; + } +} + +function isNemoclawManagedOpenShellGatewayUserServiceUnit( + filePath: string, + opts: Pick = {}, +): boolean { + return readTextFileIfPresent(filePath, opts).includes( + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + ); +} + +function hasUpstreamOpenShellGatewayUserService( opts: Pick = {}, ): boolean { if ((opts.platform ?? process.platform) !== "linux") return false; @@ -93,6 +164,54 @@ export function hasOpenShellGatewayUserService( return getOpenShellGatewayUserServicePaths().some((candidate) => existsSync(candidate)); } +export function hasNemoclawOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "existsSync" | "home" | "platform" | "readFileSync" + > = {}, +): boolean { + if ((opts.platform ?? process.platform) !== "linux") return false; + const existsSync = opts.existsSync ?? fs.existsSync; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(opts.home); + return ( + existsSync(servicePath) && isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, opts) + ); +} + +function resolveOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "existsSync" | "home" | "platform" | "readFileSync" + > = {}, +): OpenShellGatewayUserServiceTarget | null { + if ((opts.platform ?? process.platform) !== "linux") return null; + if (hasUpstreamOpenShellGatewayUserService(opts)) { + return { + serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + trustedBinaryPaths: getOpenShellGatewayUserServiceBinaryPaths(), + trustedUnitPaths: getOpenShellGatewayUserServicePaths(), + }; + } + if (hasNemoclawOpenShellGatewayUserService(opts)) { + const home = opts.home ?? os.homedir(); + return { + serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), + trustedUnitPaths: [getNemoclawOpenShellGatewayUserServicePath(home)], + }; + } + return null; +} + +export function hasOpenShellGatewayUserService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "existsSync" | "home" | "platform" | "readFileSync" + > = {}, +): boolean { + return resolveOpenShellGatewayUserService(opts) !== null; +} + function defaultCommandExists(command: string, env: NodeJS.ProcessEnv): boolean { return ( spawnSync("sh", ["-c", 'command -v "$1" >/dev/null 2>&1', "sh", command], { @@ -145,17 +264,18 @@ function parseSystemctlShowProperties(output: string): Record { } function isTrustedOpenShellGatewayUserServiceIdentity( + service: OpenShellGatewayUserServiceTarget, identity: OpenShellGatewayUserServiceIdentity, ): boolean { const fragmentPath = path.normalize(identity.fragmentPath.trim()); - const trustedUnit = getOpenShellGatewayUserServicePaths().some( + const trustedUnit = service.trustedUnitPaths.some( (candidate) => path.normalize(candidate) === fragmentPath, ); if (!trustedUnit) return false; const execStartPath = extractSystemdExecStartPath(identity.execStart); if (!execStartPath) return false; const normalizedExecStartPath = path.normalize(execStartPath); - return getOpenShellGatewayUserServiceBinaryPaths().some( + return service.trustedBinaryPaths.some( (candidate) => path.normalize(candidate) === normalizedExecStartPath, ); } @@ -168,17 +288,18 @@ function extractSystemdExecStartPath(execStart: string): string | null { } function readTrustedOpenShellGatewayUserServiceIdentity( + service: OpenShellGatewayUserServiceTarget, opts: Required>, ): { fallbackAllowed: boolean; ok: boolean; reason?: string } { const result = runSystemctlUser( - ["show", OPENSHELL_GATEWAY_USER_SERVICE, "--property=FragmentPath", "--property=ExecStart"], + ["show", service.serviceName, "--property=FragmentPath", "--property=ExecStart"], opts, ); if (!result.ok) { return { fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), ok: false, - reason: `systemctl --user show ${OPENSHELL_GATEWAY_USER_SERVICE} failed: ${result.reason}`, + reason: `systemctl --user show ${service.serviceName} failed: ${result.reason}`, }; } @@ -194,16 +315,115 @@ function readTrustedOpenShellGatewayUserServiceIdentity( reason: "service identity is incomplete", }; } - if (!isTrustedOpenShellGatewayUserServiceIdentity(identity)) { + if (!isTrustedOpenShellGatewayUserServiceIdentity(service, identity)) { return { fallbackAllowed: true, ok: false, - reason: `service identity is not the package-managed OpenShell gateway (${identity.fragmentPath})`, + reason: `service identity is not a trusted OpenShell gateway (${identity.fragmentPath})`, }; } return { fallbackAllowed: false, ok: true }; } +function assertSafeSystemdExecPath(filePath: string): void { + if (!path.isAbsolute(filePath)) { + throw new Error("OpenShell gateway service ExecStart must be an absolute path"); + } + if (/[\0\r\n\t ]/.test(filePath)) { + throw new Error("OpenShell gateway service ExecStart path cannot contain whitespace"); + } +} + +export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): string { + assertSafeSystemdExecPath(gatewayBin); + return [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Unit]", + "Description=OpenShell Gateway", + "Documentation=https://github.com/NVIDIA/OpenShell", + "After=default.target", + "", + "[Service]", + "Type=simple", + "StateDirectory=openshell/gateway", + "EnvironmentFile=-%E/openshell/gateway.env", + `ExecStart=${gatewayBin}`, + "Restart=on-failure", + "RestartSec=5s", + "PrivateTmp=true", + "UMask=0077", + "", + "[Install]", + "WantedBy=default.target", + "", + ].join("\n"); +} + +export function installNemoclawOpenShellGatewayUserService( + opts: InstallNemoclawOpenShellGatewayUserServiceOptions, +): InstallNemoclawOpenShellGatewayUserServiceResult { + const platform = opts.platform ?? process.platform; + if (platform !== "linux") return { installed: false, reason: "not a Linux host" }; + const home = opts.home ?? os.homedir(); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const existsSync = opts.existsSync ?? fs.existsSync; + if (hasUpstreamOpenShellGatewayUserService(opts)) { + if ( + existsSync(servicePath) && + isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) + ) { + const rmSync = opts.rmSync ?? fs.rmSync; + rmSync(servicePath, { force: true }); + return { + installed: false, + path: servicePath, + reason: "upstream OpenShell gateway service is installed", + removed: true, + }; + } + return { installed: false, reason: "upstream OpenShell gateway service is installed" }; + } + if (!opts.gatewayBin) return { installed: false, reason: "OpenShell gateway binary not found" }; + + const alreadyExists = existsSync(servicePath); + if ( + alreadyExists && + !isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) + ) { + return { + installed: false, + path: servicePath, + reason: "refusing to overwrite a non-NemoClaw gateway user service", + }; + } + + let unit: string; + try { + unit = buildNemoclawOpenShellGatewayUserService(opts.gatewayBin); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: error instanceof Error ? error.message : String(error), + }; + } + + const serviceDir = path.dirname(servicePath); + const mkdirSync = opts.mkdirSync ?? fs.mkdirSync; + const chmodSync = opts.chmodSync ?? fs.chmodSync; + const writeFileSync = opts.writeFileSync ?? fs.writeFileSync; + mkdirSync(serviceDir, { recursive: true, mode: 0o700 }); + chmodSync(serviceDir, 0o700); + writeFileSync(servicePath, unit, { encoding: "utf-8", mode: 0o600 }); + chmodSync(servicePath, 0o600); + return { installed: true, path: servicePath }; +} + export function startOpenShellGatewayUserService( opts: OpenShellGatewayUserServiceOptions = {}, ): OpenShellGatewayUserServiceStartResult { @@ -212,7 +432,13 @@ export function startOpenShellGatewayUserService( return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; } const existsSync = opts.existsSync ?? fs.existsSync; - if (!hasOpenShellGatewayUserService({ existsSync, platform })) { + const service = resolveOpenShellGatewayUserService({ + existsSync, + home: opts.home, + platform, + readFileSync: opts.readFileSync, + }); + if (!service) { return { attempted: false, fallbackAllowed: true, @@ -246,7 +472,7 @@ export function startOpenShellGatewayUserService( } } - const identity = readTrustedOpenShellGatewayUserServiceIdentity({ env, spawnSyncImpl }); + const identity = readTrustedOpenShellGatewayUserServiceIdentity(service, { env, spawnSyncImpl }); if (!identity.ok) { return { attempted: true, @@ -269,8 +495,8 @@ export function startOpenShellGatewayUserService( } for (const args of [ - ["enable", OPENSHELL_GATEWAY_USER_SERVICE], - ["restart", OPENSHELL_GATEWAY_USER_SERVICE], + ["enable", service.serviceName], + ["restart", service.serviceName], ]) { const result = runSystemctlUser(args, { env, spawnSyncImpl }); if (!result.ok) { @@ -284,7 +510,12 @@ export function startOpenShellGatewayUserService( } } - return { attempted: true, fallbackAllowed: false, started: true }; + return { + attempted: true, + fallbackAllowed: false, + serviceName: service.serviceName, + started: true, + }; } export async function startPackageManagedDockerDriverGateway({ @@ -308,7 +539,7 @@ export async function startPackageManagedDockerDriverGateway({ }: PackageManagedDockerDriverGatewayOptions): Promise { if (!hasOpenShellGatewayUserServiceImpl()) return false; - console.log(" Starting OpenShell Docker-driver gateway via upstream user service..."); + console.log(" Starting OpenShell Docker-driver gateway via user service..."); const serviceStart = startOpenShellGatewayUserServiceImpl({ prepareServiceEnv: prepareOpenShellGatewayUserServiceEnv, }); @@ -322,7 +553,11 @@ export async function startPackageManagedDockerDriverGateway({ } const message = `OpenShell gateway user service failed to start${detail}.`; console.error(` ${message}`); - console.error(" Check: systemctl --user status openshell-gateway"); + console.error( + ` Check: systemctl --user status ${ + serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE + }`, + ); if (exitOnFailure) process.exit(1); throw new Error(message); } From 38e25055144ae015f7ae33ea5c87461fbcae51fb Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 13:22:38 +0530 Subject: [PATCH 02/24] fix(uninstall): preserve openshell gateway daemon --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/architecture.mdx | 4 +- docs/reference/commands.mdx | 2 +- scripts/checks/extract-installer-pins.mts | 2 +- .../run-plan-gateway-service.test.ts | 151 +++++++++++++++++- src/lib/actions/uninstall/run-plan.test.ts | 4 +- src/lib/actions/uninstall/run-plan.ts | 31 ++-- src/lib/onboard.ts | 16 +- src/lib/onboard/docker-driver-gateway-env.ts | 6 + .../docker-driver-gateway-service.test.ts | 13 ++ .../onboard/docker-driver-gateway-service.ts | 22 +++ 11 files changed, 218 insertions(+), 35 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index ee72cea03cb..216715b6e49 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries installed. NemoClaw still disables and removes its own marked `~/.config/systemd/user/openshell-gateway.service` user unit when present, and never removes upstream package-managed OpenShell service units. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon; a full uninstall can remove only NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, and upstream OpenShell services, including Linux package units and the macOS Homebrew service, are preserved. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 58859e1b268..57298e8c816 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -86,7 +86,9 @@ NemoClaw prefers the upstream package-managed `openshell-gateway.service` when ` For tarball-installed OpenShell binaries, NemoClaw stages a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. Arbitrary per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process when no trusted service path is available. That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. -On Apple Silicon macOS, NemoClaw starts the OpenShell Docker-driver gateway and creates the sandbox as a Docker container. +On Apple Silicon macOS, the upstream OpenShell daemon model is the Homebrew service. +NemoClaw does not install or remove that Homebrew service; tarball-installed OpenShell binaries continue to use the standalone Docker-driver gateway process. +In either case, NemoClaw creates the sandbox as a Docker container. In both Docker-driver modes, the sandbox is a Docker container, not a Kubernetes pod. Entrypoint supervisors create the in-container `/tmp/nemoclaw-gateway-local` marker only when they actually launch an in-container gateway, and they normally keep it present while that supervisor is active. On normal exits, handled `SIGTERM`/`SIGINT`, startup failures, and shell `errexit` termination through the `EXIT` trap, the supervisor removes the marker on a best-effort basis so the Docker health check does not keep trusting a stale gateway PID. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0035950bdcf..2d885e73297 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries installed. NemoClaw still disables and removes its own marked `~/.config/systemd/user/openshell-gateway.service` user unit when present, and never removes upstream package-managed OpenShell service units. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon; a full uninstall can remove only NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, and upstream OpenShell services, including Linux package units and the macOS Homebrew service, are preserved. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 2e897b4bca4..44fde592aaa 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -48,7 +48,7 @@ const MAX_INSTALLER_INPUT_BYTES = 1024 * 1024; // release; the later pin PR may then change release data without authorizing // any operational installer change. A mismatch reports the candidate hash. const TRUSTED_INSTALLER_TEMPLATE_SHA256 = - "a101f002bd8e02aa7b38960ddcb76c9fca419bc3766f6870446f6a7e99e14d78"; + "99afb2182930f0017be0211a403aa796f49fa42be17092a04ea637f54daba1d0"; const TRUSTED_BREV_TEMPLATE_SHA256 = "c0a4ddf25a02a9fe02b2df53a60942ea887610f04d4ce16a121b6e79a5aeff1a"; const EXPECTED_INSTALLER_ASSETS = [ diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index dbd3a471d04..9c79f757ede 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -19,7 +19,7 @@ function ok(stdout = ""): RunResult { } describe("uninstall OpenShell gateway user service", () => { - it("removes the NemoClaw-managed user service even when OpenShell binaries are kept", () => { + it("keeps the NemoClaw-managed user service when OpenShell binaries are kept", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); fs.mkdirSync(path.dirname(servicePath), { recursive: true }); @@ -45,6 +45,113 @@ describe("uninstall OpenShell gateway user service", () => { existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, log: (line) => logs.push(line), + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => { + runCalls.push([command, ...args]); + return ok(); + }), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(true); + expect(runCalls).toEqual([]); + expect(logs).not.toContain(`Removed ${servicePath}`); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("keeps the host OpenShell gateway process when OpenShell is kept", () => { + const gatewayPid = 9999887; + const killed: number[] = []; + const run = vi.fn((command: string, args: string[]) => { + if ( + command === "pgrep" && + args[0] === "-f" && + String(args[1]).includes("openshell-gateway") + ) { + return ok(`${gatewayPid}\n`); + } + if ( + command === "ps" && + args[0] === "-p" && + args[1] === String(gatewayPid) && + args[2] === "-o" && + args[3] === "pid=" + ) { + return ok(`${gatewayPid}\n`); + } + if ( + command === "ps" && + args[0] === "-p" && + args[1] === String(gatewayPid) && + args[2] === "-o" && + args[3] === "args=" + ) { + return ok("/home/test/.local/bin/openshell-gateway --port 8080\n"); + } + if (command === "lsof") return ok(""); + if (command === "pgrep") return { status: 1, stdout: "", stderr: "" }; + return ok(); + }); + + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { + commandExists: () => true, + env: { HOME: "/tmp/nemoclaw-uninstall-test-keep-openshell" } as NodeJS.ProcessEnv, + existsSync: () => false, + isTty: false, + kill: (pid) => { + killed.push(pid); + return true; + }, + rmSync: vi.fn(), + run, + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(killed).not.toContain(gatewayPid); + expect( + run.mock.calls.some( + ([command, args]) => + command === "pgrep" && args[0] === "-f" && String(args[1]).includes("openshell-gateway"), + ), + ).toBe(false); + }); + + it("removes the NemoClaw-managed user service when OpenShell is removed", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Service]", + "ExecStart=/home/test/.local/bin/openshell-gateway", + "", + ].join("\n"), + ); + const logs: string[] = []; + const runCalls: string[][] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + log: (line) => logs.push(line), + platform: "linux", rmSync: fs.rmSync, run: vi.fn((command: string, args: string[]) => { runCalls.push([command, ...args]); @@ -84,6 +191,7 @@ describe("uninstall OpenShell gateway user service", () => { env: { HOME: tmpHome } as NodeJS.ProcessEnv, existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, + platform: "linux", rmSync: fs.rmSync, run: vi.fn(() => ok()), runDocker: () => ok(""), @@ -96,4 +204,45 @@ describe("uninstall OpenShell gateway user service", () => { fs.rmSync(tmpHome, { recursive: true, force: true }); } }); + + it("does not remove Linux user service units on macOS", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-macos-service-")); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "", + ].join("\n"), + ); + const run = vi.fn(() => ok()); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "darwin", + rmSync: fs.rmSync, + run, + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(true); + expect(run).not.toHaveBeenCalledWith( + "systemctl", + expect.arrayContaining(["disable"]), + expect.anything(), + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); }); diff --git a/src/lib/actions/uninstall/run-plan.test.ts b/src/lib/actions/uninstall/run-plan.test.ts index bc9885e7dc2..c6eb57cca95 100644 --- a/src/lib/actions/uninstall/run-plan.test.ts +++ b/src/lib/actions/uninstall/run-plan.test.ts @@ -1398,12 +1398,12 @@ describe("uninstall run plan", () => { }); }); - it("kills host openshell-gateway process during uninstall (#3516)", () => { + it("kills host openshell-gateway process during full uninstall (#3516)", () => { const logs: string[] = []; const killed: number[] = []; const exited = new Set(); const result = runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: true }, + { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, env: { HOME: "/tmp/nemoclaw-uninstall-test-3516" } as NodeJS.ProcessEnv, diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index b999d4ff0b6..e37ba2f8198 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -57,6 +57,7 @@ export interface UninstallRunDeps { isTty?: boolean; kill?: (pid: number, signal?: NodeJS.Signals | number) => boolean; log?: (message: string) => void; + platform?: NodeJS.Platform; readLine?: () => string | null; rmSync?: typeof fs.rmSync; run?: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; @@ -238,6 +239,7 @@ interface UninstallRuntime { isTty: boolean; kill: (pid: number, signal?: NodeJS.Signals | number) => boolean; log: (message: string) => void; + platform: NodeJS.Platform; readLine: () => string | null; rmSync: typeof fs.rmSync; run: (command: string, args: string[], options?: SpawnSyncOptions) => RunResult; @@ -266,6 +268,7 @@ function buildRuntime(deps: UninstallRunDeps): UninstallRuntime { } }), log: deps.log ?? ((message) => console.log(message)), + platform: deps.platform ?? process.platform, readLine: deps.readLine ?? readLineFromStdin, rmSync: deps.rmSync ?? fs.rmSync, run: deps.run ?? defaultRun, @@ -609,7 +612,7 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { } function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): void { - if (process.platform !== "linux") return; + if (runtime.platform !== "linux") return; const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); if (!runtime.existsSync(servicePath)) return; @@ -944,7 +947,7 @@ function executePlan( if (step.name === "Stopping services") { stopHelperServices(paths, runtime); removeGlob(paths.helperServiceGlob, runtime); - removeNemoclawOpenShellGatewayUserService(runtime); + if (!options.keepOpenShell) removeNemoclawOpenShellGatewayUserService(runtime); stopMatchingPids( `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, runtime, @@ -959,17 +962,19 @@ function executePlan( commandExists: runtime.commandExists, }); stopOrphanedOpenShell(runtime); - stopHostGatewayProcesses( - { - run: runtime.run, - kill: runtime.kill, - env: runtime.env, - log: runtime.log, - warn: runtime.warn, - commandExists: runtime.commandExists, - }, - { logNoProcesses: true }, - ); + if (!options.keepOpenShell) { + stopHostGatewayProcesses( + { + run: runtime.run, + kill: runtime.kill, + env: runtime.env, + log: runtime.log, + warn: runtime.warn, + commandExists: runtime.commandExists, + }, + { logNoProcesses: true }, + ); + } stopOllamaAuthProxy(paths, runtime); stopOpenRouterRuntimeAdapter(paths, runtime); stopModelRouter(paths, runtime); diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 45eb3887e21..862b84a69d8 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -534,8 +534,6 @@ const { } = require("./onboard/gateway-start-failure") as typeof import("./onboard/gateway-start-failure"); const dockerDriverGatewayEnv: typeof import("./onboard/docker-driver-gateway-env") = require("./onboard/docker-driver-gateway-env"); -const dockerDriverGatewayService: typeof import("./onboard/docker-driver-gateway-service") = - require("./onboard/docker-driver-gateway-service"); const dockerDriverGatewayRuntimeMarker: typeof import("./onboard/docker-driver-gateway-runtime-marker") = require("./onboard/docker-driver-gateway-runtime-marker"); const gatewayBinding: typeof import("./onboard/gateway-binding") = require("./onboard/gateway-binding"); @@ -1987,22 +1985,11 @@ async function startDockerDriverGateway({ const identityGatewayBin = runtimeIdentity?.identityGatewayBin ?? gatewayBin; const { verifySandboxBridgeGatewayReachableOrExit } = require("./onboard/gateway-sandbox-reachability") as typeof import("./onboard/gateway-sandbox-reachability"); - const gatewayService = dockerDriverGatewayService.installNemoclawOpenShellGatewayUserService({ - gatewayBin, - }); - if (gatewayService.installed && gatewayService.path) { - console.log(` Installed OpenShell gateway user service: ${gatewayService.path}`); - } else if (gatewayService.removed && gatewayService.path) { - console.log( - ` Removed NemoClaw OpenShell gateway user service override: ${gatewayService.path}`, - ); - } else if (gatewayService.reason?.startsWith("refusing")) { - console.warn(` OpenShell gateway user service not installed: ${gatewayService.reason}.`); - } if ( await dockerDriverGatewayEnv.startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles, exitOnFailure, + gatewayBin, gatewayEnv: driftGatewayEnv, gatewayName: GATEWAY_NAME, isDockerDriverGatewayReady: () => isDockerDriverGatewayHttpReady(), @@ -2017,7 +2004,6 @@ async function startDockerDriverGateway({ }) ) return; - const gatewayStatus = runCaptureOpenshell(["status"], { ignoreError: true }); const gwInfo = runCaptureOpenshell(["gateway", "info", "-g", GATEWAY_NAME], { ignoreError: true, diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 69d71f4d863..33cb30c6678 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -19,6 +19,7 @@ import { import { buildDockerDriverGatewayLocalTlsEnv } from "./docker-driver-gateway-local-tls"; import { hasOpenShellGatewayUserService, + installAndReportNemoclawOpenShellGatewayUserService, type PackageManagedDockerDriverGatewayOptions, startPackageManagedDockerDriverGateway, } from "./docker-driver-gateway-service"; @@ -57,6 +58,7 @@ export type PackageManagedDockerDriverGatewayWithEnvOverrideOptions = Omit< PackageManagedDockerDriverGatewayOptions, "prepareOpenShellGatewayUserServiceEnv" > & { + gatewayBin?: string | null; gatewayEnv: Record; }; @@ -291,9 +293,13 @@ export function writeDockerGatewayDebEnvOverrideOrThrow( } export function startPackageManagedDockerDriverGatewayWithEnvOverride({ + gatewayBin, gatewayEnv, ...options }: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { + if (gatewayBin !== undefined) { + installAndReportNemoclawOpenShellGatewayUserService({ gatewayBin }); + } assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); return startPackageManagedDockerDriverGateway({ ...options, diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 38f8d97d402..a2ca0594c66 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -234,6 +234,19 @@ describe("docker-driver-gateway-service", () => { }); }); + it("does not install a Linux systemd user service on macOS", () => { + const writeFileSync = vi.fn(); + + expect( + installNemoclawOpenShellGatewayUserService({ + gatewayBin: "/opt/homebrew/bin/openshell-gateway", + platform: "darwin", + writeFileSync: writeFileSync as never, + }), + ).toEqual({ installed: false, reason: "not a Linux host" }); + expect(writeFileSync).not.toHaveBeenCalled(); + }); + it("removes a marked user service override when an upstream package service exists", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 6e2bb61303c..7621f75ba1c 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -58,6 +58,12 @@ export interface InstallNemoclawOpenShellGatewayUserServiceResult { removed?: boolean; } +export interface InstallAndReportNemoclawOpenShellGatewayUserServiceOptions + extends InstallNemoclawOpenShellGatewayUserServiceOptions { + log?: (message: string) => void; + warn?: (message: string) => void; +} + export interface SpawnSyncLikeResult { error?: Error; status: number | null; @@ -424,6 +430,22 @@ export function installNemoclawOpenShellGatewayUserService( return { installed: true, path: servicePath }; } +export function installAndReportNemoclawOpenShellGatewayUserService( + opts: InstallAndReportNemoclawOpenShellGatewayUserServiceOptions, +): InstallNemoclawOpenShellGatewayUserServiceResult { + const result = installNemoclawOpenShellGatewayUserService(opts); + const log = opts.log ?? console.log; + const warn = opts.warn ?? console.warn; + if (result.installed && result.path) { + log(` Installed OpenShell gateway user service: ${result.path}`); + } else if (result.removed && result.path) { + log(` Removed NemoClaw OpenShell gateway user service override: ${result.path}`); + } else if (result.reason?.startsWith("refusing")) { + warn(` OpenShell gateway user service not installed: ${result.reason}.`); + } + return result; +} + export function startOpenShellGatewayUserService( opts: OpenShellGatewayUserServiceOptions = {}, ): OpenShellGatewayUserServiceStartResult { From 6b2cc095bc1202523371fd370ab01aef5afddb39 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 13:45:56 +0530 Subject: [PATCH 03/24] fix(install): preserve openshell service ownership Signed-off-by: San Dang --- docs/reference/architecture.mdx | 5 +- docs/reference/commands.mdx | 4 +- scripts/checks/extract-installer-pins.mts | 2 +- scripts/install-openshell.sh | 65 ------------- scripts/install.sh | 84 ++++++++++++++++ .../run-plan-gateway-service.test.ts | 96 ++++++++++++------- src/lib/actions/uninstall/run-plan.ts | 15 +-- .../docker-driver-gateway-service.test.ts | 65 +++++++++++++ .../onboard/docker-driver-gateway-service.ts | 71 ++++++++++++-- .../install-openshell-gateway-service.test.ts | 51 ++++++++++ 10 files changed, 338 insertions(+), 120 deletions(-) create mode 100644 test/install-openshell-gateway-service.test.ts diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 57298e8c816..370f1281db2 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -81,10 +81,11 @@ graph LR The logical diagram above shows how components relate. This section shows what actually runs where on the host. NemoClaw's default Docker-driver topology does not place the sandbox in an embedded k3s cluster. -On Linux, NemoClaw configures and restarts a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. +On Linux, NemoClaw configures, enables, and restarts a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. NemoClaw prefers the upstream package-managed `openshell-gateway.service` when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. -For tarball-installed OpenShell binaries, NemoClaw stages a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. +For tarball-installed OpenShell binaries, the installer and onboarding stage a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. Arbitrary per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process when no trusted service path is available. +If NemoClaw cannot write or remove its marked user unit, it reports the filesystem failure and keeps the standalone fallback available. That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. On Apple Silicon macOS, the upstream OpenShell daemon model is the Homebrew service. NemoClaw does not install or remove that Homebrew service; tarball-installed OpenShell binaries continue to use the standalone Docker-driver gateway process. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 2d885e73297..3bacf790a0b 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3429,8 +3429,8 @@ Set them before running `$$nemoclaw onboard`. | `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD` | unset or `auto` (default); `1`, `true`, `yes`, or `on` to enable; `0`, `false`, `no`, or `off` to disable | Controls whether base-image resolution may build a compatible image locally. The default allows builds during normal CLI runs and disables them when `NODE_ENV=test` or `VITEST=true`. When source inputs or a missing/incompatible release-version base require a fresh build, disabling local builds makes resolution fail instead of using an unproven image. | | `NEMOCLAW_DOCKER_GPU_PATCH` | unset, `auto`, `fallback`, `1`, or `0`; other legacy nonzero values remain accepted through `v0.0.x` and will be removed in `v0.1.0` | Selects Linux Docker-driver GPU routing. Unset, `auto`, or `0` uses native OpenShell GPU injection on ordinary native Linux. `fallback` explicitly opts into one native attempt followed by one bounded compatibility retry when trusted host evidence identifies a GPU-routing failure. `1` and legacy nonzero values select the compatibility patch from the outset. Docker Desktop WSL and Jetson/Tegra use the compatibility path by default; Docker Desktop WSL ignores `0`, while Jetson/Tegra accepts `0` only as a troubleshooting override that bypasses device-group propagation. | | `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH` | `1` to enable; disabled by default | This setting explicitly opts into the Linux gateway compatibility container for an older host ABI or a diagnostic run; use it only on a trusted local host because it uses host networking and mounts the Docker socket read-only even though the socket still exposes the privileged Docker API; prefer OpenShell 0.0.72's directly supported glibc 2.28+ path; see the [OpenShell 0.0.72 compatibility review](/user-guide/openclaw/security/openshell-0.0.72-compatibility-review#source-of-truth-boundaries) for details. | -| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by the Linux Docker-driver standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | -| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by the Linux Docker-driver standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Linux Docker-driver gateway startup, including the marked user service and standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by Linux Docker-driver gateway startup, including the marked user service environment and standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | | `NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR` | path | Advanced override for the Linux Docker-driver gateway SQLite state directory and standalone-fallback PID file. Defaults to `~/.local/state/nemoclaw/openshell-docker-gateway`. | | `NEMOCLAW_AUTO_FIX_FIREWALL` | `1` to enable | Opts in to automatic UFW remediation when Linux Docker-driver sandbox containers cannot reach the host gateway after a proven TCP failure. NemoClaw runs `sudo -n` only, validates the narrow Docker bridge subnet → gateway IP:port rule before invoking UFW, re-probes after applying it, and otherwise falls back to the printed manual command. | diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 44fde592aaa..2e897b4bca4 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -48,7 +48,7 @@ const MAX_INSTALLER_INPUT_BYTES = 1024 * 1024; // release; the later pin PR may then change release data without authorizing // any operational installer change. A mismatch reports the candidate hash. const TRUSTED_INSTALLER_TEMPLATE_SHA256 = - "99afb2182930f0017be0211a403aa796f49fa42be17092a04ea637f54daba1d0"; + "a101f002bd8e02aa7b38960ddcb76c9fca419bc3766f6870446f6a7e99e14d78"; const TRUSTED_BREV_TEMPLATE_SHA256 = "c0a4ddf25a02a9fe02b2df53a60942ea887610f04d4ce16a121b6e79a5aeff1a"; const EXPECTED_INSTALLER_ASSETS = [ diff --git a/scripts/install-openshell.sh b/scripts/install-openshell.sh index 9cf8abbd41c..0c0bf559eb6 100755 --- a/scripts/install-openshell.sh +++ b/scripts/install-openshell.sh @@ -16,70 +16,6 @@ fail() { exit 1 } -NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" - -upstream_openshell_gateway_service_installed() { - [ -f /usr/local/lib/systemd/user/openshell-gateway.service ] \ - || [ -f /usr/lib/systemd/user/openshell-gateway.service ] \ - || [ -f /lib/systemd/user/openshell-gateway.service ] -} - -install_nemoclaw_openshell_gateway_user_service() { - [ "$OS" = "Linux" ] || return 0 - [ -x "$target_dir/openshell-gateway" ] || return 0 - - local config_home="${XDG_CONFIG_HOME:-$HOME/.config}" - local service_dir="$config_home/systemd/user" - local service_path="$service_dir/openshell-gateway.service" - - if upstream_openshell_gateway_service_installed; then - if [ -f "$service_path" ] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then - rm -f "$service_path" - info "Removed NemoClaw OpenShell gateway user service override: $service_path" - fi - return 0 - fi - - local gateway_bin="$target_dir/openshell-gateway" - case "$gateway_bin" in - *[[:space:]]*) - warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" - return 0 - ;; - esac - - if [ -f "$service_path" ] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then - warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" - return 0 - fi - - mkdir -p "$service_dir" - chmod 700 "$service_dir" - cat >"$service_path" <&1 || echo openshell) installed" diff --git a/scripts/install.sh b/scripts/install.sh index f487398830e..cdac28c7fcb 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1119,6 +1119,89 @@ prefer_user_local_openshell() { fi } +NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" + +upstream_openshell_gateway_user_service_installed() { + [[ "$(uname -s)" == "Linux" ]] || return 1 + [[ -f /usr/local/lib/systemd/user/openshell-gateway.service ]] \ + || [[ -f /usr/lib/systemd/user/openshell-gateway.service ]] \ + || [[ -f /lib/systemd/user/openshell-gateway.service ]] +} + +resolve_openshell_gateway_bin_for_service() { + local gateway_bin="${NEMOCLAW_OPENSHELL_GATEWAY_BIN:-}" + if [[ -n "$gateway_bin" && -x "$gateway_bin" ]]; then + printf "%s\n" "$gateway_bin" + return 0 + fi + + gateway_bin="$(command -v openshell-gateway 2>/dev/null || true)" + [[ -n "$gateway_bin" && -x "$gateway_bin" ]] || return 1 + printf "%s\n" "$gateway_bin" +} + +install_nemoclaw_openshell_gateway_user_service() { + [[ "$(uname -s)" == "Linux" ]] || return 0 + + local gateway_bin + gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 + + local service_dir="${HOME}/.config/systemd/user" + local service_path="${service_dir}/openshell-gateway.service" + + if upstream_openshell_gateway_user_service_installed; then + if [[ -f "$service_path" ]] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + rm -f "$service_path" + info "Removed NemoClaw OpenShell gateway user service override: $service_path" + fi + return 0 + fi + + case "$gateway_bin" in + *[[:space:]]*) + warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" + return 0 + ;; + esac + + if [[ -f "$service_path" ]] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" + return 0 + fi + + if ! { + mkdir -p "$service_dir" \ + && chmod 700 "$service_dir" \ + && cat >"$service_path" < { it("keeps the host OpenShell gateway process when OpenShell is kept", () => { const gatewayPid = 9999887; const killed: number[] = []; - const run = vi.fn((command: string, args: string[]) => { - if ( - command === "pgrep" && - args[0] === "-f" && - String(args[1]).includes("openshell-gateway") - ) { - return ok(`${gatewayPid}\n`); - } - if ( - command === "ps" && - args[0] === "-p" && - args[1] === String(gatewayPid) && - args[2] === "-o" && - args[3] === "pid=" - ) { - return ok(`${gatewayPid}\n`); - } - if ( - command === "ps" && - args[0] === "-p" && - args[1] === String(gatewayPid) && - args[2] === "-o" && - args[3] === "args=" - ) { - return ok("/home/test/.local/bin/openshell-gateway --port 8080\n"); - } - if (command === "lsof") return ok(""); - if (command === "pgrep") return { status: 1, stdout: "", stderr: "" }; - return ok(); - }); + const run = vi.fn((_command: string, _args: string[]) => ok()); const result = runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, @@ -117,12 +89,9 @@ describe("uninstall OpenShell gateway user service", () => { expect(result.exitCode).toBe(0); expect(killed).not.toContain(gatewayPid); - expect( - run.mock.calls.some( - ([command, args]) => - command === "pgrep" && args[0] === "-f" && String(args[1]).includes("openshell-gateway"), - ), - ).toBe(false); + expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( + ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), + ); }); it("removes the NemoClaw-managed user service when OpenShell is removed", () => { @@ -177,6 +146,61 @@ describe("uninstall OpenShell gateway user service", () => { } }); + it("reports an incomplete uninstall when the service cannot be disabled", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Service]", + "ExecStart=/home/test/.local/bin/openshell-gateway", + "", + ].join("\n"), + ); + const warnings: string[] = []; + const errors: string[] = []; + const runResults = new Map([ + [ + ["systemctl", "--user", "disable", "--now", OPENSHELL_GATEWAY_USER_SERVICE].join("\0"), + { status: 1, stdout: "", stderr: "failed\n" }, + ], + ]); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + error: (line) => { + warnings.push(line); + errors.push(line); + }, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => { + return runResults.get([command, ...args].join("\0")) ?? ok(); + }), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(false); + expect(warnings).toContain(`Failed to disable ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + it("preserves a foreign service file at the NemoClaw service path", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index e37ba2f8198..2ed83f68059 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -611,23 +611,24 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { } } -function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): void { - if (runtime.platform !== "linux") return; +function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): boolean { + if (runtime.platform !== "linux") return true; const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); - if (!runtime.existsSync(servicePath)) return; + if (!runtime.existsSync(servicePath)) return true; let unit = ""; try { unit = fs.readFileSync(servicePath, "utf-8"); } catch { runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); - return; + return true; } if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) { runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); - return; + return true; } + let disabled = true; if (runtime.commandExists("systemctl")) { const disable = runtime.run( "systemctl", @@ -638,6 +639,7 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): v runtime.log(`Disabled ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); } else { runtime.warn(`Failed to disable ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); + disabled = false; } } else { runtime.warn("systemctl not found; removing NemoClaw gateway user service file only."); @@ -653,6 +655,7 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): v }); if (reload.status !== 0) runtime.warn("Failed to reload the user systemd manager."); } + return disabled; } function removeOpenShellResources(options: UninstallRunOptions, runtime: UninstallRuntime): void { @@ -947,7 +950,7 @@ function executePlan( if (step.name === "Stopping services") { stopHelperServices(paths, runtime); removeGlob(paths.helperServiceGlob, runtime); - if (!options.keepOpenShell) removeNemoclawOpenShellGatewayUserService(runtime); + if (!options.keepOpenShell && !removeNemoclawOpenShellGatewayUserService(runtime)) ok = false; stopMatchingPids( `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, runtime, diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index a2ca0594c66..a0f25a89306 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -11,6 +11,7 @@ import { getOpenShellGatewayUserServicePaths, hasNemoclawOpenShellGatewayUserService, hasOpenShellGatewayUserService, + installAndReportNemoclawOpenShellGatewayUserService, installNemoclawOpenShellGatewayUserService, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, type SpawnSyncLikeResult, @@ -191,6 +192,34 @@ describe("docker-driver-gateway-service", () => { ]); }); + it("trusts the actual binary path written into a NemoClaw-managed user service", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const gatewayBin = "/opt/nemoclaw/openshell/bin/openshell-gateway"; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => + args.includes("show") + ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) + : spawnResult(), + ); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: {}, + existsSync: (candidate) => candidate === servicePath, + home, + platform: "linux", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + spawnSyncImpl, + }); + + expect(result).toEqual({ + attempted: true, + fallbackAllowed: false, + serviceName: "openshell-gateway", + started: true, + }); + }); + it("installs the NemoClaw-managed user service without overwriting foreign units", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); @@ -278,6 +307,42 @@ describe("docker-driver-gateway-service", () => { expect(writes).toEqual([]); }); + it("returns filesystem failures as install failures for standalone fallback", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + + expect( + installNemoclawOpenShellGatewayUserService({ + chmodSync: vi.fn(), + existsSync: () => false, + gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", + home, + mkdirSync: vi.fn(() => { + throw new Error("permission denied"); + }) as never, + platform: "linux", + }), + ).toEqual({ + installed: false, + path: servicePath, + reason: "failed to write OpenShell gateway user service: permission denied", + }); + }); + + it("warns for actionable service install failures", () => { + const warn = vi.fn(); + + installAndReportNemoclawOpenShellGatewayUserService({ + gatewayBin: "/home/nvidia/bad path/openshell-gateway", + platform: "linux", + warn, + }); + + expect(warn).toHaveBeenCalledWith( + " OpenShell gateway user service not installed: OpenShell gateway service ExecStart path cannot contain whitespace.", + ); + }); + it("allows standalone fallback when the user systemd manager is unavailable", () => { const result = startOpenShellGatewayUserService({ commandExists: () => true, diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 7621f75ba1c..9b0904abd17 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -134,6 +134,10 @@ export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.home ]; } +function formatError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + function readTextFileIfPresent( filePath: string, opts: Pick = {}, @@ -162,6 +166,28 @@ function isNemoclawManagedOpenShellGatewayUserServiceUnit( ); } +function extractUnitFileExecStartPath(unit: string): string | null { + const match = /^ExecStart=([^\s]+)\s*$/m.exec(unit); + const execStart = match?.[1]?.trim(); + if (!execStart || !path.isAbsolute(execStart)) return null; + if (path.basename(execStart) !== "openshell-gateway") return null; + try { + assertSafeSystemdExecPath(execStart); + return execStart; + } catch { + return null; + } +} + +function readNemoclawManagedOpenShellGatewayUserServiceExecStart( + filePath: string, + opts: Pick = {}, +): string | null { + const unit = readTextFileIfPresent(filePath, opts); + if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) return null; + return extractUnitFileExecStartPath(unit); +} + function hasUpstreamOpenShellGatewayUserService( opts: Pick = {}, ): boolean { @@ -200,10 +226,15 @@ function resolveOpenShellGatewayUserService( } if (hasNemoclawOpenShellGatewayUserService(opts)) { const home = opts.home ?? os.homedir(); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const execStart = readNemoclawManagedOpenShellGatewayUserServiceExecStart(servicePath, opts); return { serviceName: OPENSHELL_GATEWAY_USER_SERVICE, - trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), - trustedUnitPaths: [getNemoclawOpenShellGatewayUserServicePath(home)], + trustedBinaryPaths: [ + ...getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), + ...(execStart ? [execStart] : []), + ], + trustedUnitPaths: [servicePath], }; } return null; @@ -382,7 +413,15 @@ export function installNemoclawOpenShellGatewayUserService( }) ) { const rmSync = opts.rmSync ?? fs.rmSync; - rmSync(servicePath, { force: true }); + try { + rmSync(servicePath, { force: true }); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: `failed to remove NemoClaw gateway user service override: ${formatError(error)}`, + }; + } return { installed: false, path: servicePath, @@ -423,13 +462,29 @@ export function installNemoclawOpenShellGatewayUserService( const mkdirSync = opts.mkdirSync ?? fs.mkdirSync; const chmodSync = opts.chmodSync ?? fs.chmodSync; const writeFileSync = opts.writeFileSync ?? fs.writeFileSync; - mkdirSync(serviceDir, { recursive: true, mode: 0o700 }); - chmodSync(serviceDir, 0o700); - writeFileSync(servicePath, unit, { encoding: "utf-8", mode: 0o600 }); - chmodSync(servicePath, 0o600); + try { + mkdirSync(serviceDir, { recursive: true, mode: 0o700 }); + chmodSync(serviceDir, 0o700); + writeFileSync(servicePath, unit, { encoding: "utf-8", mode: 0o600 }); + chmodSync(servicePath, 0o600); + } catch (error) { + return { + installed: false, + path: servicePath, + reason: `failed to write OpenShell gateway user service: ${formatError(error)}`, + }; + } return { installed: true, path: servicePath }; } +function isBenignGatewayUserServiceInstallSkip(reason: string | undefined): boolean { + return ( + reason === "not a Linux host" || + reason === "upstream OpenShell gateway service is installed" || + reason === "OpenShell gateway binary not found" + ); +} + export function installAndReportNemoclawOpenShellGatewayUserService( opts: InstallAndReportNemoclawOpenShellGatewayUserServiceOptions, ): InstallNemoclawOpenShellGatewayUserServiceResult { @@ -440,7 +495,7 @@ export function installAndReportNemoclawOpenShellGatewayUserService( log(` Installed OpenShell gateway user service: ${result.path}`); } else if (result.removed && result.path) { log(` Removed NemoClaw OpenShell gateway user service override: ${result.path}`); - } else if (result.reason?.startsWith("refusing")) { + } else if (result.reason && !isBenignGatewayUserServiceInstallSkip(result.reason)) { warn(` OpenShell gateway user service not installed: ${result.reason}.`); } return result; diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts new file mode 100644 index 00000000000..555db3b856b --- /dev/null +++ b/test/install-openshell-gateway-service.test.ts @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +import { TEST_SYSTEM_PATH, writeExecutable } from "./helpers/installer-sourced-env"; + +const INSTALLER = path.join(import.meta.dirname, "..", "install.sh"); + +describe("install.sh OpenShell gateway service", () => { + it("stages a Linux OpenShell gateway user service from the installer wrapper", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + const result = spawnSync( + "bash", + [ + "-c", + [ + "set -euo pipefail", + `source ${JSON.stringify(INSTALLER)}`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + }, + }, + ); + + const unit = fs.readFileSync(servicePath, "utf-8"); + expect(result.status).toBe(0); + expect(unit).toContain("NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); + expect(unit).toContain(`ExecStart=${gatewayBin}`); + }); +}); From 2015c823fb197bfb5234aecb2f2e113d647dc3fe Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 13:50:05 +0530 Subject: [PATCH 04/24] docs: clarify keep-openshell service preservation Signed-off-by: San Dang --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/commands.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index 216715b6e49..fb016c46909 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon; a full uninstall can remove only NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, and upstream OpenShell services, including Linux package units and the macOS Homebrew service, are preserved. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 3bacf790a0b..6260a9b6790 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon; a full uninstall can remove only NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, and upstream OpenShell services, including Linux package units and the macOS Homebrew service, are preserved. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | From 81df38718dec8242889b3aae88ea88ea347c3342 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:06:34 +0530 Subject: [PATCH 05/24] fix(install): honor xdg user service paths Signed-off-by: San Dang --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/commands.mdx | 2 +- scripts/install.sh | 7 ++- .../run-plan-gateway-service.test.ts | 38 +++++++++++++++ src/lib/actions/uninstall/run-plan.ts | 5 +- .../docker-driver-gateway-env-service.test.ts | 38 +++++++++++++++ src/lib/onboard/docker-driver-gateway-env.ts | 20 ++++++-- .../docker-driver-gateway-service.test.ts | 46 ++++++++++++++++++ .../onboard/docker-driver-gateway-service.ts | 48 ++++++++++++++----- .../install-openshell-gateway-service.test.ts | 37 ++++++++++++++ 10 files changed, 222 insertions(+), 21 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index fb016c46909..ffb48048949 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `openshell-gateway.service` user unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 6260a9b6790..ec517282111 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `openshell-gateway.service` user unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/scripts/install.sh b/scripts/install.sh index cdac28c7fcb..406717fa5d3 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1146,7 +1146,12 @@ install_nemoclaw_openshell_gateway_user_service() { local gateway_bin gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 - local service_dir="${HOME}/.config/systemd/user" + local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}" + case "$config_home" in + /*) ;; + *) config_home="${HOME}/.config" ;; + esac + local service_dir="${config_home}/systemd/user" local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index c3f4713c1fa..7a3c26aaeed 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -146,6 +146,44 @@ describe("uninstall OpenShell gateway user service", () => { } }); + it("removes the NemoClaw-managed user service from XDG_CONFIG_HOME", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const xdgConfigHome = path.join(tmpHome, "xdg-config"); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome, xdgConfigHome); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Service]", + "ExecStart=/home/test/.local/bin/openshell-gateway", + "", + ].join("\n"), + ); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv, + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + it("reports an incomplete uninstall when the service cannot be disabled", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 2ed83f68059..ae88c1a8560 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -613,7 +613,10 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): boolean { if (runtime.platform !== "linux") return true; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); + const servicePath = getNemoclawOpenShellGatewayUserServicePath( + runtime.env.HOME || os.homedir(), + runtime.env.XDG_CONFIG_HOME, + ); if (!runtime.existsSync(servicePath)) return true; let unit = ""; diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index 3c9f1861a7e..b05955ddb8f 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -55,6 +55,44 @@ describe("package-managed Docker-driver gateway env service", () => { } }); + it("writes the service env under XDG_CONFIG_HOME", async () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const xdgConfigHome = path.join(tempHome, "xdg-config"); + const envFile = path.join(xdgConfigHome, "openshell", "gateway.env"); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { XDG_CONFIG_HOME: xdgConfigHome }, + exitOnFailure: false, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => + args[0] === "status" + ? "Gateway: nemoclaw\nConnected" + : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:8080/", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: (opts) => { + opts?.prepareServiceEnv?.(); + return { attempted: true, fallbackAllowed: false, started: true }; + }, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).resolves.toBe(true); + + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); + } finally { + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + it("rejects package-managed wildcard binds before writing the service env", () => { expect(() => startPackageManagedDockerDriverGatewayWithEnvOverride({ diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 33cb30c6678..1d28208598b 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -260,9 +260,17 @@ function readTextFileIfPresent(filePath: string): string { } } -function writeDockerGatewayDebEnvOverrideFile(getOverride: () => Record): void { +function getUserConfigHome(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string { + if (env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME)) return env.XDG_CONFIG_HOME; + return path.join(home, ".config"); +} + +function writeDockerGatewayDebEnvOverrideFile( + getOverride: () => Record, + env: NodeJS.ProcessEnv = process.env, +): void { const override = getOverride(); - const envDir = path.join(os.homedir(), ".config", "openshell"); + const envDir = path.join(getUserConfigHome(env), "openshell"); const envFile = path.join(envDir, "gateway.env"); fs.mkdirSync(envDir, { recursive: true, mode: 0o700 }); fs.chmodSync(envDir, 0o700); @@ -279,7 +287,7 @@ export function writeDockerGatewayDebEnvOverride( opts: Parameters[0] = {}, ): boolean { if (!hasOpenShellGatewayUserService(opts)) return false; - writeDockerGatewayDebEnvOverrideFile(getOverride); + writeDockerGatewayDebEnvOverrideFile(getOverride, opts.env); return true; } @@ -297,13 +305,15 @@ export function startPackageManagedDockerDriverGatewayWithEnvOverride({ gatewayEnv, ...options }: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { + const env = options.env ?? process.env; if (gatewayBin !== undefined) { - installAndReportNemoclawOpenShellGatewayUserService({ gatewayBin }); + installAndReportNemoclawOpenShellGatewayUserService({ env, gatewayBin }); } assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); return startPackageManagedDockerDriverGateway({ ...options, + env, prepareOpenShellGatewayUserServiceEnv: () => - writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv), + writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv, env), }); } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index a0f25a89306..3a27e57b506 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -102,6 +102,29 @@ describe("docker-driver-gateway-service", () => { ).toBe(false); }); + it("detects a NemoClaw-managed user service under XDG_CONFIG_HOME", () => { + const home = "/home/nvidia"; + const xdgConfigHome = "/run/user/1000/nemoclaw-config"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, xdgConfigHome); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const existsSync = vi.fn((candidate: string) => candidate === servicePath); + const readFileSync = vi.fn((candidate: string) => + candidate === servicePath ? buildNemoclawOpenShellGatewayUserService(gatewayBin) : "", + ); + + expect(servicePath).toBe(`${xdgConfigHome}/systemd/user/openshell-gateway.service`); + expect( + hasOpenShellGatewayUserService({ + env: { XDG_CONFIG_HOME: xdgConfigHome }, + existsSync, + home, + platform: "linux", + readFileSync, + }), + ).toBe(true); + expect(existsSync.mock.calls.flat()).toContain(servicePath); + }); + it("ignores stale per-user service units so standalone fallback remains available", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); @@ -263,6 +286,29 @@ describe("docker-driver-gateway-service", () => { }); }); + it("installs the NemoClaw-managed user service under XDG_CONFIG_HOME", () => { + const home = "/home/nvidia"; + const xdgConfigHome = "/tmp/nvidia-config"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, xdgConfigHome); + const writes: string[] = []; + + const result = installNemoclawOpenShellGatewayUserService({ + chmodSync: vi.fn(), + env: { XDG_CONFIG_HOME: xdgConfigHome }, + existsSync: () => false, + gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", + home, + mkdirSync: vi.fn() as never, + platform: "linux", + writeFileSync: vi.fn((target) => { + writes.push(String(target)); + }) as never, + }); + + expect(result).toEqual({ installed: true, path: servicePath }); + expect(writes).toEqual([servicePath]); + }); + it("does not install a Linux systemd user service on macOS", () => { const writeFileSync = vi.fn(); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 9b0904abd17..9f65d22e86f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -42,7 +42,7 @@ export interface OpenShellGatewayUserServiceStartResult { export interface InstallNemoclawOpenShellGatewayUserServiceOptions extends Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > { chmodSync?: (filePath: string, mode: number) => void; gatewayBin: string | null; @@ -79,6 +79,7 @@ export type SpawnSyncLike = ( export interface PackageManagedDockerDriverGatewayOptions { clearDockerDriverGatewayRuntimeFiles: () => void; + env?: NodeJS.ProcessEnv; exitOnFailure: boolean; gatewayName: string; hasOpenShellGatewayUserService?: () => boolean; @@ -92,7 +93,7 @@ export interface PackageManagedDockerDriverGatewayOptions { prepareOpenShellGatewayUserServiceEnv?: () => void; skipSandboxBridgeReachability: boolean; startOpenShellGatewayUserService?: ( - opts?: Pick, + opts?: Pick, ) => OpenShellGatewayUserServiceStartResult; verifySandboxBridgeGatewayReachableOrExit: ( exitOnFailure: boolean, @@ -123,8 +124,21 @@ export function getOpenShellGatewayUserServiceBinaryPaths(): string[] { return ["/usr/local/bin/openshell-gateway", "/usr/bin/openshell-gateway"]; } -export function getNemoclawOpenShellGatewayUserServicePath(home = os.homedir()): string { - return path.join(home, ".config", "systemd", "user", "openshell-gateway.service"); +function getSystemdUserConfigHome(home: string, xdgConfigHome?: string): string { + if (xdgConfigHome && path.isAbsolute(xdgConfigHome)) return xdgConfigHome; + return path.join(home, ".config"); +} + +export function getNemoclawOpenShellGatewayUserServicePath( + home = os.homedir(), + xdgConfigHome?: string, +): string { + return path.join( + getSystemdUserConfigHome(home, xdgConfigHome), + "systemd", + "user", + "openshell-gateway.service", + ); } export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.homedir()): string[] { @@ -199,12 +213,15 @@ function hasUpstreamOpenShellGatewayUserService( export function hasNemoclawOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { if ((opts.platform ?? process.platform) !== "linux") return false; const existsSync = opts.existsSync ?? fs.existsSync; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(opts.home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath( + opts.home, + opts.env?.XDG_CONFIG_HOME, + ); return ( existsSync(servicePath) && isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, opts) ); @@ -213,7 +230,7 @@ export function hasNemoclawOpenShellGatewayUserService( function resolveOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): OpenShellGatewayUserServiceTarget | null { if ((opts.platform ?? process.platform) !== "linux") return null; @@ -226,7 +243,7 @@ function resolveOpenShellGatewayUserService( } if (hasNemoclawOpenShellGatewayUserService(opts)) { const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env?.XDG_CONFIG_HOME); const execStart = readNemoclawManagedOpenShellGatewayUserServiceExecStart(servicePath, opts); return { serviceName: OPENSHELL_GATEWAY_USER_SERVICE, @@ -243,7 +260,7 @@ function resolveOpenShellGatewayUserService( export function hasOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { return resolveOpenShellGatewayUserService(opts) !== null; @@ -403,7 +420,7 @@ export function installNemoclawOpenShellGatewayUserService( const platform = opts.platform ?? process.platform; if (platform !== "linux") return { installed: false, reason: "not a Linux host" }; const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env?.XDG_CONFIG_HOME); const existsSync = opts.existsSync ?? fs.existsSync; if (hasUpstreamOpenShellGatewayUserService(opts)) { if ( @@ -508,8 +525,10 @@ export function startOpenShellGatewayUserService( if (platform !== "linux") { return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; } + const env = opts.env ?? process.env; const existsSync = opts.existsSync ?? fs.existsSync; const service = resolveOpenShellGatewayUserService({ + env, existsSync, home: opts.home, platform, @@ -524,7 +543,6 @@ export function startOpenShellGatewayUserService( }; } - const env = opts.env ?? process.env; const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); if (!commandExists("systemctl")) { return { @@ -608,16 +626,22 @@ export async function startPackageManagedDockerDriverGateway({ registerDockerDriverGatewayEndpoint, runCaptureOpenshell, sleepSeconds: sleepSecondsImpl = sleepSeconds, + env = process.env, prepareOpenShellGatewayUserServiceEnv, skipSandboxBridgeReachability, startOpenShellGatewayUserService: startOpenShellGatewayUserServiceImpl = startOpenShellGatewayUserService, verifySandboxBridgeGatewayReachableOrExit, }: PackageManagedDockerDriverGatewayOptions): Promise { - if (!hasOpenShellGatewayUserServiceImpl()) return false; + const hasService = + hasOpenShellGatewayUserServiceImpl === hasOpenShellGatewayUserService + ? hasOpenShellGatewayUserService({ env }) + : hasOpenShellGatewayUserServiceImpl(); + if (!hasService) return false; console.log(" Starting OpenShell Docker-driver gateway via user service..."); const serviceStart = startOpenShellGatewayUserServiceImpl({ + env, prepareServiceEnv: prepareOpenShellGatewayUserServiceEnv, }); if (!serviceStart.started) { diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 555db3b856b..b5d4835ba1a 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -48,4 +48,41 @@ describe("install.sh OpenShell gateway service", () => { expect(unit).toContain("NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); expect(unit).toContain(`ExecStart=${gatewayBin}`); }); + + it("stages the Linux OpenShell gateway user service under XDG_CONFIG_HOME", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const xdgConfigHome = path.join(tmp, "xdg-config"); + const servicePath = path.join(xdgConfigHome, "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + const result = spawnSync( + "bash", + [ + "-c", + [ + "set -euo pipefail", + `source ${JSON.stringify(INSTALLER)}`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + XDG_CONFIG_HOME: xdgConfigHome, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + }, + }, + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + }); }); From a826519671d8ee8557e55cc29c01987adef7ff4a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:14:14 +0530 Subject: [PATCH 06/24] fix(install): harden gateway service ownership Signed-off-by: San Dang --- scripts/install.sh | 24 +++- .../run-plan-gateway-service.test.ts | 11 +- src/lib/actions/uninstall/run-plan.ts | 8 +- .../docker-driver-gateway-service.test.ts | 9 ++ .../onboard/docker-driver-gateway-service.ts | 15 ++- .../install-openshell-gateway-service.test.ts | 119 ++++++++++++++++++ 6 files changed, 172 insertions(+), 14 deletions(-) diff --git a/scripts/install.sh b/scripts/install.sh index 406717fa5d3..24389bd6239 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1120,6 +1120,7 @@ prefer_user_local_openshell() { } NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" +NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE="# ${NEMOCLAW_GATEWAY_SERVICE_MARKER}" upstream_openshell_gateway_user_service_installed() { [[ "$(uname -s)" == "Linux" ]] || return 1 @@ -1140,12 +1141,15 @@ resolve_openshell_gateway_bin_for_service() { printf "%s\n" "$gateway_bin" } +is_nemoclaw_openshell_gateway_user_service() { + local service_path="${1:-}" + [[ -f "$service_path" ]] || return 1 + grep -Fxq "$NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE" "$service_path" +} + install_nemoclaw_openshell_gateway_user_service() { [[ "$(uname -s)" == "Linux" ]] || return 0 - local gateway_bin - gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 - local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}" case "$config_home" in /*) ;; @@ -1155,21 +1159,29 @@ install_nemoclaw_openshell_gateway_user_service() { local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then - if [[ -f "$service_path" ]] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + if is_nemoclaw_openshell_gateway_user_service "$service_path"; then rm -f "$service_path" info "Removed NemoClaw OpenShell gateway user service override: $service_path" fi return 0 fi + local gateway_bin + gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 + case "$gateway_bin" in *[[:space:]]*) warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" return 0 ;; + /*) ;; + *) + warn "Skipping OpenShell gateway user service because the binary path is not absolute: $gateway_bin" + return 0 + ;; esac - if [[ -f "$service_path" ]] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + if [[ -f "$service_path" ]] && ! is_nemoclaw_openshell_gateway_user_service "$service_path"; then warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" return 0 fi @@ -1179,7 +1191,7 @@ install_nemoclaw_openshell_gateway_user_service() { && chmod 700 "$service_dir" \ && cat >"$service_path" < { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync(servicePath, "[Service]\nExecStart=/tmp/openshell-gateway\n"); + fs.writeFileSync( + servicePath, + [ + "# not NemoClaw-owned", + `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + "[Service]", + "ExecStart=/tmp/openshell-gateway", + "", + ].join("\n"), + ); try { const result = runUninstallPlan( diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index ae88c1a8560..08ef23519cb 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -25,7 +25,7 @@ import { import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { getNemoclawOpenShellGatewayUserServicePath, - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, OPENSHELL_GATEWAY_USER_SERVICE, } from "../../onboard/docker-driver-gateway-service"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; @@ -626,7 +626,11 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): b runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); return true; } - if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) { + if ( + !unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE) + ) { runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); return true; } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 3a27e57b506..494095b83d9 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -100,6 +100,14 @@ describe("docker-driver-gateway-service", () => { readFileSync: () => "not managed", }), ).toBe(false); + expect( + hasNemoclawOpenShellGatewayUserService({ + existsSync, + home, + platform: "linux", + readFileSync: () => `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + }), + ).toBe(false); }); it("detects a NemoClaw-managed user service under XDG_CONFIG_HOME", () => { @@ -379,6 +387,7 @@ describe("docker-driver-gateway-service", () => { const warn = vi.fn(); installAndReportNemoclawOpenShellGatewayUserService({ + existsSync: () => false, gatewayBin: "/home/nvidia/bad path/openshell-gateway", platform: "linux", warn, diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 9f65d22e86f..e02ca5a6c7f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -19,6 +19,7 @@ export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE = OPENSHELL_GATEWAY_USER_SERVICE; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; @@ -171,13 +172,17 @@ function readTextFileIfPresent( } } +function unitHasNemoclawGatewayServiceMarker(unit: string): boolean { + return unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE); +} + function isNemoclawManagedOpenShellGatewayUserServiceUnit( filePath: string, opts: Pick = {}, ): boolean { - return readTextFileIfPresent(filePath, opts).includes( - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, - ); + return unitHasNemoclawGatewayServiceMarker(readTextFileIfPresent(filePath, opts)); } function extractUnitFileExecStartPath(unit: string): string | null { @@ -198,7 +203,7 @@ function readNemoclawManagedOpenShellGatewayUserServiceExecStart( opts: Pick = {}, ): string | null { const unit = readTextFileIfPresent(filePath, opts); - if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) return null; + if (!unitHasNemoclawGatewayServiceMarker(unit)) return null; return extractUnitFileExecStartPath(unit); } @@ -392,7 +397,7 @@ export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): st assertSafeSystemdExecPath(gatewayBin); return [ "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, "[Unit]", "Description=OpenShell Gateway", "Documentation=https://github.com/NVIDIA/OpenShell", diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index b5d4835ba1a..a424fedf60b 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -85,4 +85,123 @@ describe("install.sh OpenShell gateway service", () => { expect(result.status).toBe(0); expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); }); + + it("skips service staging for relative gateway binary paths", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + const result = spawnSync( + "bash", + [ + "-c", + [ + "set -euo pipefail", + `source ${JSON.stringify(INSTALLER)}`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + NEMOCLAW_OPENSHELL_GATEWAY_BIN: "./openshell-gateway", + PATH: TEST_SYSTEM_PATH, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + }, + }, + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + }); + + it("removes a marked user override before resolving a gateway binary", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + [ + "# NemoClaw-managed OpenShell gateway user service", + "# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1", + "", + ].join("\n"), + ); + + const result = spawnSync( + "bash", + [ + "-c", + [ + "set -euo pipefail", + `source ${JSON.stringify(INSTALLER)}`, + "upstream_openshell_gateway_user_service_installed() { return 0; }", + "resolve_openshell_gateway_bin_for_service() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + }, + }, + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + }); + + it("does not overwrite a foreign user service containing the marker text", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + const originalUnit = [ + "# foreign unit", + "# not NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1", + "[Service]", + "ExecStart=/tmp/foreign-openshell-gateway", + "", + ].join("\n"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + fs.writeFileSync(servicePath, originalUnit); + + const result = spawnSync( + "bash", + [ + "-c", + [ + "set -euo pipefail", + `source ${JSON.stringify(INSTALLER)}`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + }, + }, + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toBe(originalUnit); + }); }); From 1089026025ea6b9c03aaf41d26ba79ff8e4ddacd Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:19:10 +0530 Subject: [PATCH 07/24] Revert "fix(install): harden gateway service ownership" This reverts commit a826519671d8ee8557e55cc29c01987adef7ff4a. --- scripts/install.sh | 24 +--- .../run-plan-gateway-service.test.ts | 11 +- src/lib/actions/uninstall/run-plan.ts | 8 +- .../docker-driver-gateway-service.test.ts | 9 -- .../onboard/docker-driver-gateway-service.ts | 15 +-- .../install-openshell-gateway-service.test.ts | 119 ------------------ 6 files changed, 14 insertions(+), 172 deletions(-) diff --git a/scripts/install.sh b/scripts/install.sh index 24389bd6239..406717fa5d3 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1120,7 +1120,6 @@ prefer_user_local_openshell() { } NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" -NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE="# ${NEMOCLAW_GATEWAY_SERVICE_MARKER}" upstream_openshell_gateway_user_service_installed() { [[ "$(uname -s)" == "Linux" ]] || return 1 @@ -1141,15 +1140,12 @@ resolve_openshell_gateway_bin_for_service() { printf "%s\n" "$gateway_bin" } -is_nemoclaw_openshell_gateway_user_service() { - local service_path="${1:-}" - [[ -f "$service_path" ]] || return 1 - grep -Fxq "$NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE" "$service_path" -} - install_nemoclaw_openshell_gateway_user_service() { [[ "$(uname -s)" == "Linux" ]] || return 0 + local gateway_bin + gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 + local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}" case "$config_home" in /*) ;; @@ -1159,29 +1155,21 @@ install_nemoclaw_openshell_gateway_user_service() { local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then - if is_nemoclaw_openshell_gateway_user_service "$service_path"; then + if [[ -f "$service_path" ]] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then rm -f "$service_path" info "Removed NemoClaw OpenShell gateway user service override: $service_path" fi return 0 fi - local gateway_bin - gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 - case "$gateway_bin" in *[[:space:]]*) warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" return 0 ;; - /*) ;; - *) - warn "Skipping OpenShell gateway user service because the binary path is not absolute: $gateway_bin" - return 0 - ;; esac - if [[ -f "$service_path" ]] && ! is_nemoclaw_openshell_gateway_user_service "$service_path"; then + if [[ -f "$service_path" ]] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" return 0 fi @@ -1191,7 +1179,7 @@ install_nemoclaw_openshell_gateway_user_service() { && chmod 700 "$service_dir" \ && cat >"$service_path" < { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# not NemoClaw-owned", - `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "[Service]", - "ExecStart=/tmp/openshell-gateway", - "", - ].join("\n"), - ); + fs.writeFileSync(servicePath, "[Service]\nExecStart=/tmp/openshell-gateway\n"); try { const result = runUninstallPlan( diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 08ef23519cb..ae88c1a8560 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -25,7 +25,7 @@ import { import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { getNemoclawOpenShellGatewayUserServicePath, - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, OPENSHELL_GATEWAY_USER_SERVICE, } from "../../onboard/docker-driver-gateway-service"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; @@ -626,11 +626,7 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): b runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); return true; } - if ( - !unit - .split(/\r?\n/) - .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE) - ) { + if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) { runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); return true; } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 494095b83d9..3a27e57b506 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -100,14 +100,6 @@ describe("docker-driver-gateway-service", () => { readFileSync: () => "not managed", }), ).toBe(false); - expect( - hasNemoclawOpenShellGatewayUserService({ - existsSync, - home, - platform: "linux", - readFileSync: () => `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - }), - ).toBe(false); }); it("detects a NemoClaw-managed user service under XDG_CONFIG_HOME", () => { @@ -387,7 +379,6 @@ describe("docker-driver-gateway-service", () => { const warn = vi.fn(); installAndReportNemoclawOpenShellGatewayUserService({ - existsSync: () => false, gatewayBin: "/home/nvidia/bad path/openshell-gateway", platform: "linux", warn, diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index e02ca5a6c7f..9f65d22e86f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -19,7 +19,6 @@ export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE = OPENSHELL_GATEWAY_USER_SERVICE; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; -export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; @@ -172,17 +171,13 @@ function readTextFileIfPresent( } } -function unitHasNemoclawGatewayServiceMarker(unit: string): boolean { - return unit - .split(/\r?\n/) - .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE); -} - function isNemoclawManagedOpenShellGatewayUserServiceUnit( filePath: string, opts: Pick = {}, ): boolean { - return unitHasNemoclawGatewayServiceMarker(readTextFileIfPresent(filePath, opts)); + return readTextFileIfPresent(filePath, opts).includes( + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + ); } function extractUnitFileExecStartPath(unit: string): string | null { @@ -203,7 +198,7 @@ function readNemoclawManagedOpenShellGatewayUserServiceExecStart( opts: Pick = {}, ): string | null { const unit = readTextFileIfPresent(filePath, opts); - if (!unitHasNemoclawGatewayServiceMarker(unit)) return null; + if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) return null; return extractUnitFileExecStartPath(unit); } @@ -397,7 +392,7 @@ export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): st assertSafeSystemdExecPath(gatewayBin); return [ "# NemoClaw-managed OpenShell gateway user service", - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, + `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, "[Unit]", "Description=OpenShell Gateway", "Documentation=https://github.com/NVIDIA/OpenShell", diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index a424fedf60b..b5d4835ba1a 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -85,123 +85,4 @@ describe("install.sh OpenShell gateway service", () => { expect(result.status).toBe(0); expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); }); - - it("skips service staging for relative gateway binary paths", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const gatewayBin = path.join(tmp, "openshell-gateway"); - const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); - writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); - - const result = spawnSync( - "bash", - [ - "-c", - [ - "set -euo pipefail", - `source ${JSON.stringify(INSTALLER)}`, - "upstream_openshell_gateway_user_service_installed() { return 1; }", - "install_nemoclaw_openshell_gateway_user_service", - ].join("\n"), - ], - { - cwd: tmp, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmp, - NEMOCLAW_OPENSHELL_GATEWAY_BIN: "./openshell-gateway", - PATH: TEST_SYSTEM_PATH, - NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), - }, - }, - ); - - expect(result.status).toBe(0); - expect(fs.existsSync(servicePath)).toBe(false); - }); - - it("removes a marked user override before resolving a gateway binary", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - "# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1", - "", - ].join("\n"), - ); - - const result = spawnSync( - "bash", - [ - "-c", - [ - "set -euo pipefail", - `source ${JSON.stringify(INSTALLER)}`, - "upstream_openshell_gateway_user_service_installed() { return 0; }", - "resolve_openshell_gateway_bin_for_service() { return 1; }", - "install_nemoclaw_openshell_gateway_user_service", - ].join("\n"), - ], - { - cwd: tmp, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmp, - PATH: TEST_SYSTEM_PATH, - NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), - }, - }, - ); - - expect(result.status).toBe(0); - expect(fs.existsSync(servicePath)).toBe(false); - }); - - it("does not overwrite a foreign user service containing the marker text", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); - const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); - const originalUnit = [ - "# foreign unit", - "# not NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1", - "[Service]", - "ExecStart=/tmp/foreign-openshell-gateway", - "", - ].join("\n"); - fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); - fs.writeFileSync(servicePath, originalUnit); - - const result = spawnSync( - "bash", - [ - "-c", - [ - "set -euo pipefail", - `source ${JSON.stringify(INSTALLER)}`, - "upstream_openshell_gateway_user_service_installed() { return 1; }", - `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, - "install_nemoclaw_openshell_gateway_user_service", - ].join("\n"), - ], - { - cwd: tmp, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmp, - PATH: TEST_SYSTEM_PATH, - NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), - }, - }, - ); - - expect(result.status).toBe(0); - expect(fs.readFileSync(servicePath, "utf-8")).toBe(originalUnit); - }); }); From 15e1ed2731328bee3476aa271e2b57bd3a467970 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:19:12 +0530 Subject: [PATCH 08/24] Revert "fix(install): honor xdg user service paths" This reverts commit 81df38718dec8242889b3aae88ea88ea347c3342. --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/commands.mdx | 2 +- scripts/install.sh | 7 +-- .../run-plan-gateway-service.test.ts | 38 --------------- src/lib/actions/uninstall/run-plan.ts | 5 +- .../docker-driver-gateway-env-service.test.ts | 38 --------------- src/lib/onboard/docker-driver-gateway-env.ts | 20 ++------ .../docker-driver-gateway-service.test.ts | 46 ------------------ .../onboard/docker-driver-gateway-service.ts | 48 +++++-------------- .../install-openshell-gateway-service.test.ts | 37 -------------- 10 files changed, 21 insertions(+), 222 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index ffb48048949..fb016c46909 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `openshell-gateway.service` user unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index ec517282111..6260a9b6790 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `openshell-gateway.service` user unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/scripts/install.sh b/scripts/install.sh index 406717fa5d3..cdac28c7fcb 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1146,12 +1146,7 @@ install_nemoclaw_openshell_gateway_user_service() { local gateway_bin gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 - local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}" - case "$config_home" in - /*) ;; - *) config_home="${HOME}/.config" ;; - esac - local service_dir="${config_home}/systemd/user" + local service_dir="${HOME}/.config/systemd/user" local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 7a3c26aaeed..c3f4713c1fa 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -146,44 +146,6 @@ describe("uninstall OpenShell gateway user service", () => { } }); - it("removes the NemoClaw-managed user service from XDG_CONFIG_HOME", () => { - const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const xdgConfigHome = path.join(tmpHome, "xdg-config"); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome, xdgConfigHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "[Service]", - "ExecStart=/home/test/.local/bin/openshell-gateway", - "", - ].join("\n"), - ); - - try { - const result = runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: false }, - { - commandExists: (command) => command === "systemctl", - env: { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv, - existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), - isTty: false, - platform: "linux", - rmSync: fs.rmSync, - run: vi.fn(() => ok()), - runDocker: () => ok(""), - }, - ); - - expect(result.exitCode).toBe(0); - expect(fs.existsSync(servicePath)).toBe(false); - } finally { - fs.rmSync(tmpHome, { recursive: true, force: true }); - } - }); - it("reports an incomplete uninstall when the service cannot be disabled", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index ae88c1a8560..2ed83f68059 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -613,10 +613,7 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): boolean { if (runtime.platform !== "linux") return true; - const servicePath = getNemoclawOpenShellGatewayUserServicePath( - runtime.env.HOME || os.homedir(), - runtime.env.XDG_CONFIG_HOME, - ); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); if (!runtime.existsSync(servicePath)) return true; let unit = ""; diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index b05955ddb8f..3c9f1861a7e 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -55,44 +55,6 @@ describe("package-managed Docker-driver gateway env service", () => { } }); - it("writes the service env under XDG_CONFIG_HOME", async () => { - const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); - const xdgConfigHome = path.join(tempHome, "xdg-config"); - const envFile = path.join(xdgConfigHome, "openshell", "gateway.env"); - - try { - await expect( - startPackageManagedDockerDriverGatewayWithEnvOverride({ - clearDockerDriverGatewayRuntimeFiles: vi.fn(), - env: { XDG_CONFIG_HOME: xdgConfigHome }, - exitOnFailure: false, - gatewayEnv: { - OPENSHELL_BIND_ADDRESS: "127.0.0.1", - OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), - }, - gatewayName: "nemoclaw", - hasOpenShellGatewayUserService: () => true, - isDockerDriverGatewayReady: async () => true, - registerDockerDriverGatewayEndpoint: () => true, - runCaptureOpenshell: (args) => - args[0] === "status" - ? "Gateway: nemoclaw\nConnected" - : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:8080/", - skipSandboxBridgeReachability: false, - startOpenShellGatewayUserService: (opts) => { - opts?.prepareServiceEnv?.(); - return { attempted: true, fallbackAllowed: false, started: true }; - }, - verifySandboxBridgeGatewayReachableOrExit: async () => undefined, - }), - ).resolves.toBe(true); - - expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); - } finally { - fs.rmSync(tempHome, { recursive: true, force: true }); - } - }); - it("rejects package-managed wildcard binds before writing the service env", () => { expect(() => startPackageManagedDockerDriverGatewayWithEnvOverride({ diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 1d28208598b..33cb30c6678 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -260,17 +260,9 @@ function readTextFileIfPresent(filePath: string): string { } } -function getUserConfigHome(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string { - if (env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME)) return env.XDG_CONFIG_HOME; - return path.join(home, ".config"); -} - -function writeDockerGatewayDebEnvOverrideFile( - getOverride: () => Record, - env: NodeJS.ProcessEnv = process.env, -): void { +function writeDockerGatewayDebEnvOverrideFile(getOverride: () => Record): void { const override = getOverride(); - const envDir = path.join(getUserConfigHome(env), "openshell"); + const envDir = path.join(os.homedir(), ".config", "openshell"); const envFile = path.join(envDir, "gateway.env"); fs.mkdirSync(envDir, { recursive: true, mode: 0o700 }); fs.chmodSync(envDir, 0o700); @@ -287,7 +279,7 @@ export function writeDockerGatewayDebEnvOverride( opts: Parameters[0] = {}, ): boolean { if (!hasOpenShellGatewayUserService(opts)) return false; - writeDockerGatewayDebEnvOverrideFile(getOverride, opts.env); + writeDockerGatewayDebEnvOverrideFile(getOverride); return true; } @@ -305,15 +297,13 @@ export function startPackageManagedDockerDriverGatewayWithEnvOverride({ gatewayEnv, ...options }: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { - const env = options.env ?? process.env; if (gatewayBin !== undefined) { - installAndReportNemoclawOpenShellGatewayUserService({ env, gatewayBin }); + installAndReportNemoclawOpenShellGatewayUserService({ gatewayBin }); } assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); return startPackageManagedDockerDriverGateway({ ...options, - env, prepareOpenShellGatewayUserServiceEnv: () => - writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv, env), + writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv), }); } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 3a27e57b506..a0f25a89306 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -102,29 +102,6 @@ describe("docker-driver-gateway-service", () => { ).toBe(false); }); - it("detects a NemoClaw-managed user service under XDG_CONFIG_HOME", () => { - const home = "/home/nvidia"; - const xdgConfigHome = "/run/user/1000/nemoclaw-config"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, xdgConfigHome); - const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; - const existsSync = vi.fn((candidate: string) => candidate === servicePath); - const readFileSync = vi.fn((candidate: string) => - candidate === servicePath ? buildNemoclawOpenShellGatewayUserService(gatewayBin) : "", - ); - - expect(servicePath).toBe(`${xdgConfigHome}/systemd/user/openshell-gateway.service`); - expect( - hasOpenShellGatewayUserService({ - env: { XDG_CONFIG_HOME: xdgConfigHome }, - existsSync, - home, - platform: "linux", - readFileSync, - }), - ).toBe(true); - expect(existsSync.mock.calls.flat()).toContain(servicePath); - }); - it("ignores stale per-user service units so standalone fallback remains available", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); @@ -286,29 +263,6 @@ describe("docker-driver-gateway-service", () => { }); }); - it("installs the NemoClaw-managed user service under XDG_CONFIG_HOME", () => { - const home = "/home/nvidia"; - const xdgConfigHome = "/tmp/nvidia-config"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, xdgConfigHome); - const writes: string[] = []; - - const result = installNemoclawOpenShellGatewayUserService({ - chmodSync: vi.fn(), - env: { XDG_CONFIG_HOME: xdgConfigHome }, - existsSync: () => false, - gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", - home, - mkdirSync: vi.fn() as never, - platform: "linux", - writeFileSync: vi.fn((target) => { - writes.push(String(target)); - }) as never, - }); - - expect(result).toEqual({ installed: true, path: servicePath }); - expect(writes).toEqual([servicePath]); - }); - it("does not install a Linux systemd user service on macOS", () => { const writeFileSync = vi.fn(); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 9f65d22e86f..9b0904abd17 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -42,7 +42,7 @@ export interface OpenShellGatewayUserServiceStartResult { export interface InstallNemoclawOpenShellGatewayUserServiceOptions extends Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "existsSync" | "home" | "platform" | "readFileSync" > { chmodSync?: (filePath: string, mode: number) => void; gatewayBin: string | null; @@ -79,7 +79,6 @@ export type SpawnSyncLike = ( export interface PackageManagedDockerDriverGatewayOptions { clearDockerDriverGatewayRuntimeFiles: () => void; - env?: NodeJS.ProcessEnv; exitOnFailure: boolean; gatewayName: string; hasOpenShellGatewayUserService?: () => boolean; @@ -93,7 +92,7 @@ export interface PackageManagedDockerDriverGatewayOptions { prepareOpenShellGatewayUserServiceEnv?: () => void; skipSandboxBridgeReachability: boolean; startOpenShellGatewayUserService?: ( - opts?: Pick, + opts?: Pick, ) => OpenShellGatewayUserServiceStartResult; verifySandboxBridgeGatewayReachableOrExit: ( exitOnFailure: boolean, @@ -124,21 +123,8 @@ export function getOpenShellGatewayUserServiceBinaryPaths(): string[] { return ["/usr/local/bin/openshell-gateway", "/usr/bin/openshell-gateway"]; } -function getSystemdUserConfigHome(home: string, xdgConfigHome?: string): string { - if (xdgConfigHome && path.isAbsolute(xdgConfigHome)) return xdgConfigHome; - return path.join(home, ".config"); -} - -export function getNemoclawOpenShellGatewayUserServicePath( - home = os.homedir(), - xdgConfigHome?: string, -): string { - return path.join( - getSystemdUserConfigHome(home, xdgConfigHome), - "systemd", - "user", - "openshell-gateway.service", - ); +export function getNemoclawOpenShellGatewayUserServicePath(home = os.homedir()): string { + return path.join(home, ".config", "systemd", "user", "openshell-gateway.service"); } export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.homedir()): string[] { @@ -213,15 +199,12 @@ function hasUpstreamOpenShellGatewayUserService( export function hasNemoclawOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { if ((opts.platform ?? process.platform) !== "linux") return false; const existsSync = opts.existsSync ?? fs.existsSync; - const servicePath = getNemoclawOpenShellGatewayUserServicePath( - opts.home, - opts.env?.XDG_CONFIG_HOME, - ); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(opts.home); return ( existsSync(servicePath) && isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, opts) ); @@ -230,7 +213,7 @@ export function hasNemoclawOpenShellGatewayUserService( function resolveOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): OpenShellGatewayUserServiceTarget | null { if ((opts.platform ?? process.platform) !== "linux") return null; @@ -243,7 +226,7 @@ function resolveOpenShellGatewayUserService( } if (hasNemoclawOpenShellGatewayUserService(opts)) { const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env?.XDG_CONFIG_HOME); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); const execStart = readNemoclawManagedOpenShellGatewayUserServiceExecStart(servicePath, opts); return { serviceName: OPENSHELL_GATEWAY_USER_SERVICE, @@ -260,7 +243,7 @@ function resolveOpenShellGatewayUserService( export function hasOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { return resolveOpenShellGatewayUserService(opts) !== null; @@ -420,7 +403,7 @@ export function installNemoclawOpenShellGatewayUserService( const platform = opts.platform ?? process.platform; if (platform !== "linux") return { installed: false, reason: "not a Linux host" }; const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env?.XDG_CONFIG_HOME); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); const existsSync = opts.existsSync ?? fs.existsSync; if (hasUpstreamOpenShellGatewayUserService(opts)) { if ( @@ -525,10 +508,8 @@ export function startOpenShellGatewayUserService( if (platform !== "linux") { return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; } - const env = opts.env ?? process.env; const existsSync = opts.existsSync ?? fs.existsSync; const service = resolveOpenShellGatewayUserService({ - env, existsSync, home: opts.home, platform, @@ -543,6 +524,7 @@ export function startOpenShellGatewayUserService( }; } + const env = opts.env ?? process.env; const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); if (!commandExists("systemctl")) { return { @@ -626,22 +608,16 @@ export async function startPackageManagedDockerDriverGateway({ registerDockerDriverGatewayEndpoint, runCaptureOpenshell, sleepSeconds: sleepSecondsImpl = sleepSeconds, - env = process.env, prepareOpenShellGatewayUserServiceEnv, skipSandboxBridgeReachability, startOpenShellGatewayUserService: startOpenShellGatewayUserServiceImpl = startOpenShellGatewayUserService, verifySandboxBridgeGatewayReachableOrExit, }: PackageManagedDockerDriverGatewayOptions): Promise { - const hasService = - hasOpenShellGatewayUserServiceImpl === hasOpenShellGatewayUserService - ? hasOpenShellGatewayUserService({ env }) - : hasOpenShellGatewayUserServiceImpl(); - if (!hasService) return false; + if (!hasOpenShellGatewayUserServiceImpl()) return false; console.log(" Starting OpenShell Docker-driver gateway via user service..."); const serviceStart = startOpenShellGatewayUserServiceImpl({ - env, prepareServiceEnv: prepareOpenShellGatewayUserServiceEnv, }); if (!serviceStart.started) { diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index b5d4835ba1a..555db3b856b 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -48,41 +48,4 @@ describe("install.sh OpenShell gateway service", () => { expect(unit).toContain("NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); expect(unit).toContain(`ExecStart=${gatewayBin}`); }); - - it("stages the Linux OpenShell gateway user service under XDG_CONFIG_HOME", () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); - const xdgConfigHome = path.join(tmp, "xdg-config"); - const servicePath = path.join(xdgConfigHome, "systemd", "user", "openshell-gateway.service"); - fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); - writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); - - const result = spawnSync( - "bash", - [ - "-c", - [ - "set -euo pipefail", - `source ${JSON.stringify(INSTALLER)}`, - "upstream_openshell_gateway_user_service_installed() { return 1; }", - `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, - "install_nemoclaw_openshell_gateway_user_service", - ].join("\n"), - ], - { - cwd: tmp, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmp, - PATH: TEST_SYSTEM_PATH, - XDG_CONFIG_HOME: xdgConfigHome, - NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), - }, - }, - ); - - expect(result.status).toBe(0); - expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); - }); }); From 2623204f5f90a652bf9928113b145bd1dd6f798a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:29:31 +0530 Subject: [PATCH 09/24] fix(install): slim gateway service daemon changes Signed-off-by: San Dang --- scripts/install.sh | 24 +- .../run-plan-gateway-service.test.ts | 178 +++------- src/lib/actions/uninstall/run-plan.ts | 8 +- src/lib/onboard/docker-driver-gateway-env.ts | 2 +- .../docker-driver-gateway-service.test.ts | 305 +++++------------- .../onboard/docker-driver-gateway-service.ts | 25 +- .../install-openshell-gateway-service.test.ts | 124 +++++-- 7 files changed, 261 insertions(+), 405 deletions(-) diff --git a/scripts/install.sh b/scripts/install.sh index cdac28c7fcb..c8548dc60c3 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1120,6 +1120,7 @@ prefer_user_local_openshell() { } NEMOCLAW_GATEWAY_SERVICE_MARKER="NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1" +NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE="# ${NEMOCLAW_GATEWAY_SERVICE_MARKER}" upstream_openshell_gateway_user_service_installed() { [[ "$(uname -s)" == "Linux" ]] || return 1 @@ -1140,31 +1141,42 @@ resolve_openshell_gateway_bin_for_service() { printf "%s\n" "$gateway_bin" } +is_nemoclaw_openshell_gateway_user_service() { + local service_path="${1:-}" + [[ -f "$service_path" ]] || return 1 + grep -Fxq "$NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE" "$service_path" +} + install_nemoclaw_openshell_gateway_user_service() { [[ "$(uname -s)" == "Linux" ]] || return 0 - local gateway_bin - gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 - local service_dir="${HOME}/.config/systemd/user" local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then - if [[ -f "$service_path" ]] && grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + if is_nemoclaw_openshell_gateway_user_service "$service_path"; then rm -f "$service_path" info "Removed NemoClaw OpenShell gateway user service override: $service_path" fi return 0 fi + local gateway_bin + gateway_bin="$(resolve_openshell_gateway_bin_for_service)" || return 0 + case "$gateway_bin" in *[[:space:]]*) warn "Skipping OpenShell gateway user service because the binary path contains whitespace: $gateway_bin" return 0 ;; + /*) ;; + *) + warn "Skipping OpenShell gateway user service because the binary path is not absolute: $gateway_bin" + return 0 + ;; esac - if [[ -f "$service_path" ]] && ! grep -q "$NEMOCLAW_GATEWAY_SERVICE_MARKER" "$service_path"; then + if [[ -f "$service_path" ]] && ! is_nemoclaw_openshell_gateway_user_service "$service_path"; then warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" return 0 fi @@ -1174,7 +1186,7 @@ install_nemoclaw_openshell_gateway_user_service() { && chmod 700 "$service_dir" \ && cat >"$service_path" < { - it("keeps the NemoClaw-managed user service when OpenShell binaries are kept", () => { + it("keeps OpenShell service and host gateway process when OpenShell is kept", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "[Service]", - "ExecStart=/home/test/.local/bin/openshell-gateway", - "", - ].join("\n"), - ); - const logs: string[] = []; - const runCalls: string[][] = []; + const servicePath = writeManagedService(tmpHome); + const run = vi.fn((_command: string, _args: string[]) => ok()); try { const result = runUninstallPlan( { assumeYes: true, deleteModels: false, keepOpenShell: true }, { - commandExists: (command) => command === "systemctl", + commandExists: () => true, env: { HOME: tmpHome } as NodeJS.ProcessEnv, existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, - log: (line) => logs.push(line), platform: "linux", rmSync: fs.rmSync, - run: vi.fn((command: string, args: string[]) => { - runCalls.push([command, ...args]); - return ok(); - }), + run, runDocker: () => ok(""), }, ); expect(result.exitCode).toBe(0); expect(fs.existsSync(servicePath)).toBe(true); - expect(runCalls).toEqual([]); - expect(logs).not.toContain(`Removed ${servicePath}`); + expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( + ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), + ); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } }); - it("keeps the host OpenShell gateway process when OpenShell is kept", () => { - const gatewayPid = 9999887; - const killed: number[] = []; - const run = vi.fn((_command: string, _args: string[]) => ok()); - - const result = runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: true }, - { - commandExists: () => true, - env: { HOME: "/tmp/nemoclaw-uninstall-test-keep-openshell" } as NodeJS.ProcessEnv, - existsSync: () => false, - isTty: false, - kill: (pid) => { - killed.push(pid); - return true; - }, - rmSync: vi.fn(), - run, - runDocker: () => ok(""), - }, - ); - - expect(result.exitCode).toBe(0); - expect(killed).not.toContain(gatewayPid); - expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( - ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), - ); - }); - - it("removes the NemoClaw-managed user service when OpenShell is removed", () => { + it("removes the NemoClaw-managed Linux user service on full uninstall", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "[Service]", - "ExecStart=/home/test/.local/bin/openshell-gateway", - "", - ].join("\n"), - ); - const logs: string[] = []; + const servicePath = writeManagedService(tmpHome); const runCalls: string[][] = []; try { @@ -119,7 +79,6 @@ describe("uninstall OpenShell gateway user service", () => { env: { HOME: tmpHome } as NodeJS.ProcessEnv, existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, - log: (line) => logs.push(line), platform: "linux", rmSync: fs.rmSync, run: vi.fn((command: string, args: string[]) => { @@ -139,35 +98,15 @@ describe("uninstall OpenShell gateway user service", () => { "--now", OPENSHELL_GATEWAY_USER_SERVICE, ]); - expect(runCalls).toContainEqual(["systemctl", "--user", "daemon-reload"]); - expect(logs).toContain(`Removed ${servicePath}`); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } }); - it("reports an incomplete uninstall when the service cannot be disabled", () => { + it("reports incomplete uninstall when disabling the service fails", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "[Service]", - "ExecStart=/home/test/.local/bin/openshell-gateway", - "", - ].join("\n"), - ); - const warnings: string[] = []; + const servicePath = writeManagedService(tmpHome); const errors: string[] = []; - const runResults = new Map([ - [ - ["systemctl", "--user", "disable", "--now", OPENSHELL_GATEWAY_USER_SERVICE].join("\0"), - { status: 1, stdout: "", stderr: "failed\n" }, - ], - ]); try { const result = runUninstallPlan( @@ -175,24 +114,22 @@ describe("uninstall OpenShell gateway user service", () => { { commandExists: (command) => command === "systemctl", env: { HOME: tmpHome } as NodeJS.ProcessEnv, - error: (line) => { - warnings.push(line); - errors.push(line); - }, + error: (line) => errors.push(line), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, platform: "linux", rmSync: fs.rmSync, - run: vi.fn((command: string, args: string[]) => { - return runResults.get([command, ...args].join("\0")) ?? ok(); - }), + run: vi.fn((command: string, args: string[]) => + command === "systemctl" && args.includes("disable") + ? { status: 1, stdout: "", stderr: "failed\n" } + : ok(), + ), runDocker: () => ok(""), }, ); expect(result.exitCode).toBe(1); expect(fs.existsSync(servicePath)).toBe(false); - expect(warnings).toContain(`Failed to disable ${OPENSHELL_GATEWAY_USER_SERVICE}.service`); expect(errors).toContain( "Uninstall completed with errors. Some state may remain on disk; see warnings above.", ); @@ -201,47 +138,9 @@ describe("uninstall OpenShell gateway user service", () => { } }); - it("preserves a foreign service file at the NemoClaw service path", () => { - const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-foreign-service-")); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync(servicePath, "[Service]\nExecStart=/tmp/openshell-gateway\n"); - - try { - const result = runUninstallPlan( - { assumeYes: true, deleteModels: false, keepOpenShell: true }, - { - commandExists: () => false, - env: { HOME: tmpHome } as NodeJS.ProcessEnv, - existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), - isTty: false, - platform: "linux", - rmSync: fs.rmSync, - run: vi.fn(() => ok()), - runDocker: () => ok(""), - }, - ); - - expect(result.exitCode).toBe(0); - expect(fs.existsSync(servicePath)).toBe(true); - } finally { - fs.rmSync(tmpHome, { recursive: true, force: true }); - } - }); - it("does not remove Linux user service units on macOS", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-macos-service-")); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(tmpHome); - fs.mkdirSync(path.dirname(servicePath), { recursive: true }); - fs.writeFileSync( - servicePath, - [ - "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, - "", - ].join("\n"), - ); - const run = vi.fn(() => ok()); + const servicePath = writeManagedService(tmpHome); try { const result = runUninstallPlan( @@ -253,18 +152,13 @@ describe("uninstall OpenShell gateway user service", () => { isTty: false, platform: "darwin", rmSync: fs.rmSync, - run, + run: vi.fn(() => ok()), runDocker: () => ok(""), }, ); expect(result.exitCode).toBe(0); expect(fs.existsSync(servicePath)).toBe(true); - expect(run).not.toHaveBeenCalledWith( - "systemctl", - expect.arrayContaining(["disable"]), - expect.anything(), - ); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 2ed83f68059..64bc300beec 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -25,7 +25,7 @@ import { import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { getNemoclawOpenShellGatewayUserServicePath, - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, OPENSHELL_GATEWAY_USER_SERVICE, } from "../../onboard/docker-driver-gateway-service"; import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process"; @@ -623,7 +623,11 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): b runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); return true; } - if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) { + if ( + !unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE) + ) { runtime.warn(`Leaving ${servicePath} in place because it is not NemoClaw-managed.`); return true; } diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 33cb30c6678..0445c03f98d 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -297,10 +297,10 @@ export function startPackageManagedDockerDriverGatewayWithEnvOverride({ gatewayEnv, ...options }: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { + assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); if (gatewayBin !== undefined) { installAndReportNemoclawOpenShellGatewayUserService({ gatewayBin }); } - assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); return startPackageManagedDockerDriverGateway({ ...options, prepareOpenShellGatewayUserServiceEnv: () => diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index a0f25a89306..e3574a45036 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -11,7 +11,6 @@ import { getOpenShellGatewayUserServicePaths, hasNemoclawOpenShellGatewayUserService, hasOpenShellGatewayUserService, - installAndReportNemoclawOpenShellGatewayUserService, installNemoclawOpenShellGatewayUserService, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, type SpawnSyncLikeResult, @@ -71,116 +70,135 @@ describe("docker-driver-gateway-service", () => { ]); }); - it("detects a NemoClaw-managed user service without trusting arbitrary per-user units", () => { + it("ignores stale per-user service units so standalone fallback remains available", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); const existsSync = vi.fn((candidate: string) => candidate === servicePath); - const readFileSync = vi.fn((candidate: string) => - candidate === servicePath - ? buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway") - : "", - ); expect( - hasNemoclawOpenShellGatewayUserService({ + hasOpenShellGatewayUserService({ existsSync, home, platform: "linux", - readFileSync, + readFileSync: () => `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, }), - ).toBe(true); + ).toBe(false); + }); + + it("detects and installs a NemoClaw-managed user service on Linux only", () => { + const home = "/home/nvidia"; + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const writeFileSync = vi.fn(); + expect( - hasOpenShellGatewayUserService({ existsSync, home, platform: "linux", readFileSync }), - ).toBe(true); + installNemoclawOpenShellGatewayUserService({ + chmodSync: vi.fn(), + existsSync: () => false, + gatewayBin, + home, + mkdirSync: vi.fn() as never, + platform: "linux", + writeFileSync: writeFileSync as never, + }), + ).toEqual({ installed: true, path: servicePath }); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain(`ExecStart=${gatewayBin}`); expect( hasNemoclawOpenShellGatewayUserService({ - existsSync, + existsSync: (candidate) => candidate === servicePath, home, platform: "linux", - readFileSync: () => "not managed", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), }), - ).toBe(false); + ).toBe(true); + expect( + installNemoclawOpenShellGatewayUserService({ + gatewayBin: "/opt/homebrew/bin/openshell-gateway", + platform: "darwin", + writeFileSync: vi.fn() as never, + }), + ).toEqual({ installed: false, reason: "not a Linux host" }); }); - it("ignores stale per-user service units so standalone fallback remains available", () => { + it("removes a NemoClaw user override when an upstream service exists", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - const existsSync = vi.fn((candidate: string) => candidate === servicePath); + const rmSync = vi.fn(); expect( - hasOpenShellGatewayUserService({ - existsSync, + installNemoclawOpenShellGatewayUserService({ + existsSync: (candidate) => + candidate === "/usr/lib/systemd/user/openshell-gateway.service" || + candidate === servicePath, + gatewayBin: null, home, platform: "linux", - readFileSync: () => "foreign user unit", + readFileSync: () => + buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway"), + rmSync: rmSync as never, }), - ).toBe(false); - expect(existsSync.mock.calls.flat()).toContain(servicePath); + ).toMatchObject({ installed: false, removed: true }); + expect(rmSync).toHaveBeenCalledWith(servicePath, { force: true }); }); - it("restarts the upstream user service with systemctl --user after validating identity", () => { - const events: string[] = []; - const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - events.push(args[1] ?? args[0] ?? ""); - return args.includes("show") ? spawnResult(0, "", trustedShowOutput()) : spawnResult(); - }); - - const result = startOpenShellGatewayUserService({ - commandExists: (command) => command === "systemctl", - env: {}, - existsSync: (candidate) => candidate === "/lib/systemd/user/openshell-gateway.service", - platform: "linux", - prepareServiceEnv: () => events.push("prepare-env"), - spawnSyncImpl, - }); - - expect(result).toEqual({ - attempted: true, - fallbackAllowed: false, - serviceName: "openshell-gateway", - started: true, - }); - expect(events).toEqual(["daemon-reload", "show", "prepare-env", "enable", "restart"]); - expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ - ["systemctl", ["--user", "daemon-reload"]], - [ - "systemctl", - ["--user", "show", "openshell-gateway", "--property=FragmentPath", "--property=ExecStart"], - ], - ["systemctl", ["--user", "enable", "openshell-gateway"]], - ["systemctl", ["--user", "restart", "openshell-gateway"]], - ]); + it("rejects unsafe NemoClaw service ExecStart paths", () => { + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "./openshell-gateway", + platform: "linux", + }).reason, + ).toMatch(/absolute path/); + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "/home/nvidia/bad path/openshell-gateway", + platform: "linux", + }).reason, + ).toMatch(/cannot contain whitespace/); }); - it("restarts the NemoClaw-managed user service after validating its marker and identity", () => { + it("restarts the NemoClaw-managed user service after validating its identity", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => + args.includes("show") + ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) + : spawnResult(), + ); + + expect( + startOpenShellGatewayUserService({ + commandExists: (command) => command === "systemctl", + env: {}, + existsSync: (candidate) => candidate === servicePath, + home, + platform: "linux", + readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + spawnSyncImpl, + }), + ).toMatchObject({ attempted: true, fallbackAllowed: false, started: true }); + }); + + it("restarts the upstream user service with systemctl --user after validating identity", () => { const events: string[] = []; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { events.push(args[1] ?? args[0] ?? ""); - return args.includes("show") - ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) - : spawnResult(); + return args.includes("show") ? spawnResult(0, "", trustedShowOutput()) : spawnResult(); }); const result = startOpenShellGatewayUserService({ commandExists: (command) => command === "systemctl", env: {}, - existsSync: (candidate) => candidate === servicePath, - home, + existsSync: (candidate) => candidate === "/lib/systemd/user/openshell-gateway.service", platform: "linux", - readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), + prepareServiceEnv: () => events.push("prepare-env"), spawnSyncImpl, }); - expect(result).toEqual({ - attempted: true, - fallbackAllowed: false, - serviceName: "openshell-gateway", - started: true, - }); - expect(events).toEqual(["daemon-reload", "show", "enable", "restart"]); + expect(result).toMatchObject({ attempted: true, fallbackAllowed: false, started: true }); + expect(events).toEqual(["daemon-reload", "show", "prepare-env", "enable", "restart"]); expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ ["systemctl", ["--user", "daemon-reload"]], [ @@ -192,157 +210,6 @@ describe("docker-driver-gateway-service", () => { ]); }); - it("trusts the actual binary path written into a NemoClaw-managed user service", () => { - const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - const gatewayBin = "/opt/nemoclaw/openshell/bin/openshell-gateway"; - const spawnSyncImpl = vi.fn((_command: string, args: string[]) => - args.includes("show") - ? spawnResult(0, "", trustedShowOutput(servicePath, gatewayBin)) - : spawnResult(), - ); - - const result = startOpenShellGatewayUserService({ - commandExists: (command) => command === "systemctl", - env: {}, - existsSync: (candidate) => candidate === servicePath, - home, - platform: "linux", - readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), - spawnSyncImpl, - }); - - expect(result).toEqual({ - attempted: true, - fallbackAllowed: false, - serviceName: "openshell-gateway", - started: true, - }); - }); - - it("installs the NemoClaw-managed user service without overwriting foreign units", () => { - const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; - const writes: Array<{ data: string; path: string }> = []; - - const result = installNemoclawOpenShellGatewayUserService({ - chmodSync: vi.fn(), - existsSync: () => false, - gatewayBin, - home, - mkdirSync: vi.fn() as never, - platform: "linux", - writeFileSync: vi.fn((target, data) => { - writes.push({ data: String(data), path: String(target) }); - }) as never, - }); - - expect(result).toEqual({ installed: true, path: servicePath }); - expect(writes).toHaveLength(1); - expect(writes[0]?.path).toBe(servicePath); - expect(writes[0]?.data).toContain("Description=OpenShell Gateway"); - expect(writes[0]?.data).toContain("EnvironmentFile=-%E/openshell/gateway.env"); - expect(writes[0]?.data).toContain(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER); - expect(writes[0]?.data).toContain(`ExecStart=${gatewayBin}`); - expect(writes[0]?.data).toContain("RestartSec=5s"); - expect(writes[0]?.data).toContain("PrivateTmp=true"); - - expect( - installNemoclawOpenShellGatewayUserService({ - existsSync: (candidate) => candidate === servicePath, - gatewayBin, - home, - platform: "linux", - readFileSync: () => "foreign unit", - }), - ).toMatchObject({ - installed: false, - path: servicePath, - reason: "refusing to overwrite a non-NemoClaw gateway user service", - }); - }); - - it("does not install a Linux systemd user service on macOS", () => { - const writeFileSync = vi.fn(); - - expect( - installNemoclawOpenShellGatewayUserService({ - gatewayBin: "/opt/homebrew/bin/openshell-gateway", - platform: "darwin", - writeFileSync: writeFileSync as never, - }), - ).toEqual({ installed: false, reason: "not a Linux host" }); - expect(writeFileSync).not.toHaveBeenCalled(); - }); - - it("removes a marked user service override when an upstream package service exists", () => { - const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - const removed: string[] = []; - const writes: string[] = []; - - const result = installNemoclawOpenShellGatewayUserService({ - existsSync: (candidate) => - candidate === "/usr/lib/systemd/user/openshell-gateway.service" || - candidate === servicePath, - gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", - home, - platform: "linux", - readFileSync: (candidate) => - candidate === servicePath - ? buildNemoclawOpenShellGatewayUserService("/home/nvidia/.local/bin/openshell-gateway") - : "", - rmSync: vi.fn((target) => removed.push(String(target))) as never, - writeFileSync: vi.fn((target) => writes.push(String(target))) as never, - }); - - expect(result).toEqual({ - installed: false, - path: servicePath, - reason: "upstream OpenShell gateway service is installed", - removed: true, - }); - expect(removed).toEqual([servicePath]); - expect(writes).toEqual([]); - }); - - it("returns filesystem failures as install failures for standalone fallback", () => { - const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - - expect( - installNemoclawOpenShellGatewayUserService({ - chmodSync: vi.fn(), - existsSync: () => false, - gatewayBin: "/home/nvidia/.local/bin/openshell-gateway", - home, - mkdirSync: vi.fn(() => { - throw new Error("permission denied"); - }) as never, - platform: "linux", - }), - ).toEqual({ - installed: false, - path: servicePath, - reason: "failed to write OpenShell gateway user service: permission denied", - }); - }); - - it("warns for actionable service install failures", () => { - const warn = vi.fn(); - - installAndReportNemoclawOpenShellGatewayUserService({ - gatewayBin: "/home/nvidia/bad path/openshell-gateway", - platform: "linux", - warn, - }); - - expect(warn).toHaveBeenCalledWith( - " OpenShell gateway user service not installed: OpenShell gateway service ExecStart path cannot contain whitespace.", - ); - }); - it("allows standalone fallback when the user systemd manager is unavailable", () => { const result = startOpenShellGatewayUserService({ commandExists: () => true, diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 9b0904abd17..aa8d60dc99a 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -16,9 +16,9 @@ import { import { isDockerDriverGatewayHttpReady } from "./gateway-http-readiness"; export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; -export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE = OPENSHELL_GATEWAY_USER_SERVICE; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; +export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; @@ -145,25 +145,22 @@ function readTextFileIfPresent( const readFileSync = opts.readFileSync ?? fs.readFileSync; try { return readFileSync(filePath, "utf-8"); - } catch (error) { - if ( - error instanceof Error && - "code" in error && - (error as NodeJS.ErrnoException).code === "ENOENT" - ) { - return ""; - } + } catch { return ""; } } +function hasNemoclawOpenShellGatewayUserServiceMarker(unit: string): boolean { + return unit + .split(/\r?\n/) + .some((line) => line.trimEnd() === NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE); +} + function isNemoclawManagedOpenShellGatewayUserServiceUnit( filePath: string, opts: Pick = {}, ): boolean { - return readTextFileIfPresent(filePath, opts).includes( - NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, - ); + return hasNemoclawOpenShellGatewayUserServiceMarker(readTextFileIfPresent(filePath, opts)); } function extractUnitFileExecStartPath(unit: string): string | null { @@ -184,7 +181,7 @@ function readNemoclawManagedOpenShellGatewayUserServiceExecStart( opts: Pick = {}, ): string | null { const unit = readTextFileIfPresent(filePath, opts); - if (!unit.includes(NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER)) return null; + if (!hasNemoclawOpenShellGatewayUserServiceMarker(unit)) return null; return extractUnitFileExecStartPath(unit); } @@ -375,7 +372,7 @@ export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): st assertSafeSystemdExecPath(gatewayBin); return [ "# NemoClaw-managed OpenShell gateway user service", - `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, + NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, "[Unit]", "Description=OpenShell Gateway", "Documentation=https://github.com/NVIDIA/OpenShell", diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 555db3b856b..10b863e2634 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -11,6 +11,24 @@ import { TEST_SYSTEM_PATH, writeExecutable } from "./helpers/installer-sourced-e const INSTALLER = path.join(import.meta.dirname, "..", "install.sh"); +function runInstallHelper(tmp: string, body: string, env: NodeJS.ProcessEnv = {}) { + return spawnSync( + "bash", + ["-c", ["set -euo pipefail", `source ${JSON.stringify(INSTALLER)}`, body].join("\n")], + { + cwd: tmp, + encoding: "utf-8", + env: { + ...process.env, + HOME: tmp, + PATH: TEST_SYSTEM_PATH, + NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), + ...env, + }, + }, + ); +} + describe("install.sh OpenShell gateway service", () => { it("stages a Linux OpenShell gateway user service from the installer wrapper", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); @@ -19,33 +37,97 @@ describe("install.sh OpenShell gateway service", () => { fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); - const result = spawnSync( - "bash", - [ - "-c", + try { + const result = runInstallHelper( + tmp, [ - "set -euo pipefail", - `source ${JSON.stringify(INSTALLER)}`, "upstream_openshell_gateway_user_service_installed() { return 1; }", `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, "install_nemoclaw_openshell_gateway_user_service", ].join("\n"), - ], - { - cwd: tmp, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmp, - PATH: TEST_SYSTEM_PATH, - NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), - }, - }, + ); + + const unit = fs.readFileSync(servicePath, "utf-8"); + expect(result.status).toBe(0); + expect(unit).toContain("# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); + expect(unit).toContain(`ExecStart=${gatewayBin}`); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("skips service staging for relative gateway binary paths", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + writeExecutable(path.join(tmp, "openshell-gateway"), "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + { NEMOCLAW_OPENSHELL_GATEWAY_BIN: "./openshell-gateway" }, + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("removes a marked user override before resolving a gateway binary", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + fs.writeFileSync( + servicePath, + "# NemoClaw-managed OpenShell gateway user service\n# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1\n", ); - const unit = fs.readFileSync(servicePath, "utf-8"); - expect(result.status).toBe(0); - expect(unit).toContain("NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); - expect(unit).toContain(`ExecStart=${gatewayBin}`); + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 0; }", + "resolve_openshell_gateway_bin_for_service() { return 1; }", + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.existsSync(servicePath)).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("does not overwrite a foreign user service containing the marker text", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + const originalUnit = "# foreign unit\n# not NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1\n"; + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + fs.mkdirSync(path.dirname(servicePath), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + fs.writeFileSync(servicePath, originalUnit); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toBe(originalUnit); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } }); }); From 08bd056fe8c006a2fa3fa74a16003528f1a28920 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:36:36 +0530 Subject: [PATCH 10/24] fix(install): tighten gateway service trust Signed-off-by: San Dang --- docs/reference/commands.mdx | 2 +- scripts/install.sh | 17 +++++++- .../docker-driver-gateway-service.test.ts | 8 ++++ .../onboard/docker-driver-gateway-service.ts | 43 +++++++------------ .../install-openshell-gateway-service.test.ts | 4 +- 5 files changed, 42 insertions(+), 32 deletions(-) diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 6260a9b6790..0db4d77fa16 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3429,7 +3429,7 @@ Set them before running `$$nemoclaw onboard`. | `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD` | unset or `auto` (default); `1`, `true`, `yes`, or `on` to enable; `0`, `false`, `no`, or `off` to disable | Controls whether base-image resolution may build a compatible image locally. The default allows builds during normal CLI runs and disables them when `NODE_ENV=test` or `VITEST=true`. When source inputs or a missing/incompatible release-version base require a fresh build, disabling local builds makes resolution fail instead of using an unproven image. | | `NEMOCLAW_DOCKER_GPU_PATCH` | unset, `auto`, `fallback`, `1`, or `0`; other legacy nonzero values remain accepted through `v0.0.x` and will be removed in `v0.1.0` | Selects Linux Docker-driver GPU routing. Unset, `auto`, or `0` uses native OpenShell GPU injection on ordinary native Linux. `fallback` explicitly opts into one native attempt followed by one bounded compatibility retry when trusted host evidence identifies a GPU-routing failure. `1` and legacy nonzero values select the compatibility patch from the outset. Docker Desktop WSL and Jetson/Tegra use the compatibility path by default; Docker Desktop WSL ignores `0`, while Jetson/Tegra accepts `0` only as a troubleshooting override that bypasses device-group propagation. | | `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH` | `1` to enable; disabled by default | This setting explicitly opts into the Linux gateway compatibility container for an older host ABI or a diagnostic run; use it only on a trusted local host because it uses host networking and mounts the Docker socket read-only even though the socket still exposes the privileged Docker API; prefer OpenShell 0.0.72's directly supported glibc 2.28+ path; see the [OpenShell 0.0.72 compatibility review](/user-guide/openclaw/security/openshell-0.0.72-compatibility-review#source-of-truth-boundaries) for details. | -| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Linux Docker-driver gateway startup, including the marked user service and standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Linux Docker-driver gateway startup. The marked user service accepts only NemoClaw's trusted install paths (`~/.local/bin/openshell-gateway`, `/usr/local/bin/openshell-gateway`, or `/usr/bin/openshell-gateway`); other absolute paths use the standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | | `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by Linux Docker-driver gateway startup, including the marked user service environment and standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | | `NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR` | path | Advanced override for the Linux Docker-driver gateway SQLite state directory and standalone-fallback PID file. Defaults to `~/.local/state/nemoclaw/openshell-docker-gateway`. | | `NEMOCLAW_AUTO_FIX_FIREWALL` | `1` to enable | Opts in to automatic UFW remediation when Linux Docker-driver sandbox containers cannot reach the host gateway after a proven TCP failure. NemoClaw runs `sudo -n` only, validates the narrow Docker bridge subnet → gateway IP:port rule before invoking UFW, re-probes after applying it, and otherwise falls back to the printed manual command. | diff --git a/scripts/install.sh b/scripts/install.sh index c8548dc60c3..2ffaa1f5aa3 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1141,6 +1141,18 @@ resolve_openshell_gateway_bin_for_service() { printf "%s\n" "$gateway_bin" } +trusted_openshell_gateway_bin_for_service() { + local gateway_bin="${1:-}" + case "$gateway_bin" in + "${HOME}/.local/bin/openshell-gateway" | /usr/local/bin/openshell-gateway | /usr/bin/openshell-gateway) + return 0 + ;; + *) + return 1 + ;; + esac +} + is_nemoclaw_openshell_gateway_user_service() { local service_path="${1:-}" [[ -f "$service_path" ]] || return 1 @@ -1175,6 +1187,10 @@ install_nemoclaw_openshell_gateway_user_service() { return 0 ;; esac + if ! trusted_openshell_gateway_bin_for_service "$gateway_bin"; then + warn "Skipping OpenShell gateway user service because the binary path is not a trusted install path: $gateway_bin" + return 0 + fi if [[ -f "$service_path" ]] && ! is_nemoclaw_openshell_gateway_user_service "$service_path"; then warn "Leaving non-NemoClaw OpenShell gateway user service in place: $service_path" @@ -1190,7 +1206,6 @@ $NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE [Unit] Description=OpenShell Gateway Documentation=https://github.com/NVIDIA/OpenShell -After=default.target [Service] Type=simple diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index e3574a45036..f733463f885 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -156,6 +156,14 @@ describe("docker-driver-gateway-service", () => { platform: "linux", }).reason, ).toMatch(/cannot contain whitespace/); + expect( + installNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: "/opt/openshell/bin/openshell-gateway", + home: "/home/nvidia", + platform: "linux", + }).reason, + ).toMatch(/not in a trusted install path/); }); it("restarts the NemoClaw-managed user service after validating its identity", () => { diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index aa8d60dc99a..39e49ebef76 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -163,28 +163,6 @@ function isNemoclawManagedOpenShellGatewayUserServiceUnit( return hasNemoclawOpenShellGatewayUserServiceMarker(readTextFileIfPresent(filePath, opts)); } -function extractUnitFileExecStartPath(unit: string): string | null { - const match = /^ExecStart=([^\s]+)\s*$/m.exec(unit); - const execStart = match?.[1]?.trim(); - if (!execStart || !path.isAbsolute(execStart)) return null; - if (path.basename(execStart) !== "openshell-gateway") return null; - try { - assertSafeSystemdExecPath(execStart); - return execStart; - } catch { - return null; - } -} - -function readNemoclawManagedOpenShellGatewayUserServiceExecStart( - filePath: string, - opts: Pick = {}, -): string | null { - const unit = readTextFileIfPresent(filePath, opts); - if (!hasNemoclawOpenShellGatewayUserServiceMarker(unit)) return null; - return extractUnitFileExecStartPath(unit); -} - function hasUpstreamOpenShellGatewayUserService( opts: Pick = {}, ): boolean { @@ -224,13 +202,9 @@ function resolveOpenShellGatewayUserService( if (hasNemoclawOpenShellGatewayUserService(opts)) { const home = opts.home ?? os.homedir(); const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); - const execStart = readNemoclawManagedOpenShellGatewayUserServiceExecStart(servicePath, opts); return { serviceName: OPENSHELL_GATEWAY_USER_SERVICE, - trustedBinaryPaths: [ - ...getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), - ...(execStart ? [execStart] : []), - ], + trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), trustedUnitPaths: [servicePath], }; } @@ -368,6 +342,13 @@ function assertSafeSystemdExecPath(filePath: string): void { } } +function isTrustedNemoclawGatewayServiceBinaryPath(filePath: string, home: string): boolean { + const normalizedPath = path.normalize(filePath); + return getNemoclawOpenShellGatewayUserServiceBinaryPaths(home).some( + (candidate) => path.normalize(candidate) === normalizedPath, + ); +} + export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): string { assertSafeSystemdExecPath(gatewayBin); return [ @@ -376,7 +357,6 @@ export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): st "[Unit]", "Description=OpenShell Gateway", "Documentation=https://github.com/NVIDIA/OpenShell", - "After=default.target", "", "[Service]", "Type=simple", @@ -454,6 +434,13 @@ export function installNemoclawOpenShellGatewayUserService( reason: error instanceof Error ? error.message : String(error), }; } + if (!isTrustedNemoclawGatewayServiceBinaryPath(opts.gatewayBin, home)) { + return { + installed: false, + path: servicePath, + reason: "OpenShell gateway service ExecStart path is not in a trusted install path", + }; + } const serviceDir = path.dirname(servicePath); const mkdirSync = opts.mkdirSync ?? fs.mkdirSync; diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 10b863e2634..3202ffd6893 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -32,7 +32,7 @@ function runInstallHelper(tmp: string, body: string, env: NodeJS.ProcessEnv = {} describe("install.sh OpenShell gateway service", () => { it("stages a Linux OpenShell gateway user service from the installer wrapper", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); @@ -106,7 +106,7 @@ describe("install.sh OpenShell gateway service", () => { it("does not overwrite a foreign user service containing the marker text", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); - const gatewayBin = path.join(tmp, "bin", "openshell-gateway"); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); const originalUnit = "# foreign unit\n# not NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1\n"; fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); From 85eb8b513b2f3e883ca27610184d8bc3b8351a2a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 14:51:30 +0530 Subject: [PATCH 11/24] fix(uninstall): preserve gateway config when keeping openshell Signed-off-by: San Dang --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/commands.mdx | 2 +- .../uninstall/run-plan-gateway-service.test.ts | 11 +++++++++++ src/lib/actions/uninstall/run-plan.ts | 4 +++- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index fb016c46909..dd9b52cea1d 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0db4d77fa16..89fcef690f5 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries and gateway service daemons in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index b6429a067bf..8c6dfe7975c 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -35,10 +35,18 @@ function writeManagedService(home: string): string { return servicePath; } +function writeGatewayEnv(home: string): string { + const envPath = path.join(home, ".config", "openshell", "gateway.env"); + fs.mkdirSync(path.dirname(envPath), { recursive: true }); + fs.writeFileSync(envPath, "OPENSHELL_SERVER_PORT=8080\n"); + return envPath; +} + describe("uninstall OpenShell gateway user service", () => { it("keeps OpenShell service and host gateway process when OpenShell is kept", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); const servicePath = writeManagedService(tmpHome); + const envPath = writeGatewayEnv(tmpHome); const run = vi.fn((_command: string, _args: string[]) => ok()); try { @@ -58,6 +66,7 @@ describe("uninstall OpenShell gateway user service", () => { expect(result.exitCode).toBe(0); expect(fs.existsSync(servicePath)).toBe(true); + expect(fs.existsSync(envPath)).toBe(true); expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), ); @@ -69,6 +78,7 @@ describe("uninstall OpenShell gateway user service", () => { it("removes the NemoClaw-managed Linux user service on full uninstall", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); const servicePath = writeManagedService(tmpHome); + const envPath = writeGatewayEnv(tmpHome); const runCalls: string[][] = []; try { @@ -91,6 +101,7 @@ describe("uninstall OpenShell gateway user service", () => { expect(result.exitCode).toBe(0); expect(fs.existsSync(servicePath)).toBe(false); + expect(fs.existsSync(envPath)).toBe(false); expect(runCalls).toContainEqual([ "systemctl", "--user", diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 64bc300beec..e7736d64304 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -1007,7 +1007,9 @@ function executePlan( removeFileWithOptionalSudo(target, runtime); if (!removePathExcept(paths.nemoclawStateDir, preserveUnderStateDir, runtime)) ok = false; removePath(paths.gatewayLocalStateDir, runtime); - removePath(paths.openshellConfigDir, runtime); + if (options.keepOpenShell) + runtime.log("Keeping OpenShell gateway configuration as requested."); + else removePath(paths.openshellConfigDir, runtime); removePath(paths.nemoclawConfigDir, runtime); } } From a5b205d3b4e57a1dba2e574ff6772220c508be20 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 15:07:43 +0530 Subject: [PATCH 12/24] test(onboard): cover gateway service env staging --- .../docker-driver-gateway-env-service.test.ts | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index 3c9f1861a7e..3cc5329ad4a 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -13,12 +13,16 @@ import { writeSafeGatewayAuthConfig } from "../../../test/support/docker-driver- describe("package-managed Docker-driver gateway env service", () => { it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); + const servicePath = path.join( + tempHome, + ".config", + "systemd", + "user", + "openshell-gateway.service", + ); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); - const existsSpy = vi - .spyOn(fs, "existsSync") - .mockImplementation( - (candidate) => candidate === "/usr/lib/systemd/user/openshell-gateway.service", - ); + const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); try { @@ -26,9 +30,11 @@ describe("package-managed Docker-driver gateway env service", () => { startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), exitOnFailure: false, + gatewayBin, gatewayEnv: { OPENSHELL_BIND_ADDRESS: "127.0.0.1", OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + OPENSHELL_SERVER_PORT: "18080", }, gatewayName: "nemoclaw", hasOpenShellGatewayUserService: () => true, @@ -37,7 +43,7 @@ describe("package-managed Docker-driver gateway env service", () => { runCaptureOpenshell: (args) => args[0] === "status" ? "Gateway: nemoclaw\nConnected" - : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:8080/", + : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:18080/", skipSandboxBridgeReachability: false, startOpenShellGatewayUserService: (opts) => { opts?.prepareServiceEnv?.(); @@ -47,7 +53,9 @@ describe("package-managed Docker-driver gateway env service", () => { }), ).resolves.toBe(true); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_SERVER_PORT=18080\n"); } finally { existsSpy.mockRestore(); homedirSpy.mockRestore(); From 2c0e16a9f8696786a7b4292d0ae0130b82cd9624 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 15:41:54 +0530 Subject: [PATCH 13/24] test(e2e): assert gateway service reboot recovery --- test/e2e/fixtures/phases/lifecycle.ts | 75 ++++++++++++++++---- test/e2e/registry/definitions/baseline.ts | 43 ++++------- test/e2e/registry/expected-states.ts | 18 +++-- test/e2e/support/e2e-expected-state.test.ts | 5 +- test/e2e/support/e2e-phase-lifecycle.test.ts | 56 +++++++++------ 5 files changed, 122 insertions(+), 75 deletions(-) diff --git a/test/e2e/fixtures/phases/lifecycle.ts b/test/e2e/fixtures/phases/lifecycle.ts index 021bd074b07..3b90081b145 100644 --- a/test/e2e/fixtures/phases/lifecycle.ts +++ b/test/e2e/fixtures/phases/lifecycle.ts @@ -35,6 +35,7 @@ const STATUS_TIMEOUT_MS = 5 * 60_000; const REBUILD_TIMEOUT_MS = 20 * 60_000; const SANDBOX_READY_ATTEMPTS = 30; const SANDBOX_READY_DELAY_MS = 5_000; +const USER_SERVICE_UNAVAILABLE_EXIT = 75; export type LifecycleProfile = "post-reboot-recovery" | "dcode-rebuild-invalid-credential"; @@ -179,25 +180,26 @@ export class LifecyclePhaseFixture { } /** - * Reproduce the host-side conditions of a DGX Spark / Linux Docker-driver - * reboot AND drive the user-visible action that exposes the bug: + * Reproduce the host-side conditions of a Linux Docker-driver reboot and + * drive the user-visible action that exposes reboot recovery bugs: * * 1. Locate the OpenShell-labeled Docker container for the * target's sandbox name and either stop it (default) or * stop+rename it to a `*-nemoclaw-gpu-backup-*` sibling. - * The gateway runtime is left HEALTHY — attempting to stop - * and restart it from the OpenShell CLI is unreliable on - * `ubuntu-latest` (no `gateway start` subcommand) and the - * remaining bug class for #4423 specifically requires a - * `healthy_named` gateway when status runs (otherwise - * #4578's mitigation takes over and masks the signal). + * The gateway runtime is stopped and restarted through the + * OpenShell user service when the host exposes one, which + * mirrors a reboot or user-manager restart. Hosts without a + * visible user service fall back to the existing first-session + * status/start path. * * 2. Invoke `nemoclaw status` — the user-visible action * that documented the regression in #4423. On unfixed `main` * the destructive `missing` branch in `status.ts` wipes the * registry entry. On the PR-A fix branch the new Docker-driver * recovery helper restarts the labeled container before - * stale-removal can fire. + * stale-removal can fire. The preceding gateway restart must + * make `openshell status` report the named gateway connected + * without running `nemoclaw onboard --resume`. * * We deliberately do NOT assert on the status exit code here * because the bug is precisely that status "succeeds" at @@ -265,6 +267,17 @@ export class LifecyclePhaseFixture { }); } + const previousRuntime = await this.restartGatewayRuntime({ + delayMs: 0, + sandboxName: instance.sandboxName, + }); + steps.push({ + id: `gateway-restart:${previousRuntime?.kind ?? "user-service-or-session"}`, + results: [], + }); + await this.waitForGatewayConnected(); + steps.push({ id: "gateway-connected:nemoclaw", results: [] }); + // Final step: drive the user-visible action that exposed #4423. // We invoke status through the host CLI client so artifacts are // captured and the command goes through the same @@ -348,12 +361,18 @@ export class LifecyclePhaseFixture { previousRuntime: HostGatewayRuntime | null, options: { sandboxName?: string } = {}, ): Promise { + const userServiceStart = await this.startOpenShellGatewayUserService(); + if (userServiceStart) return userServiceStart; + if (options.sandboxName) { + return await this.host.nemoclaw([options.sandboxName, "status"], { + artifactName: `lifecycle-gateway-recover-through-nemoclaw-status-${options.sandboxName}`, + env: buildAvailabilityProbeEnv(), + timeoutMs: 120_000, + }); + } if (previousRuntime?.kind === "pid") { - const args = options.sandboxName ? [options.sandboxName, "status"] : ["status"]; - return await this.host.nemoclaw(args, { - artifactName: options.sandboxName - ? `lifecycle-gateway-recover-through-nemoclaw-status-${options.sandboxName}` - : "lifecycle-gateway-recover-through-nemoclaw-status", + return await this.host.nemoclaw(["status"], { + artifactName: "lifecycle-gateway-recover-through-nemoclaw-status", env: buildAvailabilityProbeEnv(), timeoutMs: 120_000, }); @@ -365,6 +384,34 @@ export class LifecyclePhaseFixture { }); } + private async startOpenShellGatewayUserService(): Promise { + const result = await this.host.command( + "sh", + [ + "-lc", + [ + "set -eu", + `if ! command -v systemctl >/dev/null 2>&1; then exit ${USER_SERVICE_UNAVAILABLE_EXIT}; fi`, + `fragment="$(systemctl --user show openshell-gateway --property=FragmentPath --value 2>/dev/null || true)"`, + `case "$fragment" in */openshell-gateway.service) ;; *) exit ${USER_SERVICE_UNAVAILABLE_EXIT} ;; esac`, + "systemctl --user daemon-reload", + "systemctl --user restart openshell-gateway", + ].join("\n"), + ], + { + artifactName: "lifecycle-gateway-user-service-restart", + env: buildAvailabilityProbeEnv(), + timeoutMs: 120_000, + }, + ); + if (result.exitCode === 0) return result; + if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT) return null; + throw new Error( + `OpenShell gateway user service restart failed during reboot lifecycle: ` + + `${result.stderr || result.stdout || `exit ${String(result.exitCode)}`}`, + ); + } + async restartGatewayRuntime( options: { delayMs?: number; sandboxName?: string } = {}, ): Promise { diff --git a/test/e2e/registry/definitions/baseline.ts b/test/e2e/registry/definitions/baseline.ts index b9a1647f91d..366d804ccd4 100644 --- a/test/e2e/registry/definitions/baseline.ts +++ b/test/e2e/registry/definitions/baseline.ts @@ -158,32 +158,19 @@ const canonicalTargetInputs: CanonicalTargetInput[] = [ requiredSecrets: ["NVIDIA_API_KEY"], }, { - // Failing-test-first regression scaffold for #4423. After - // onboarding, the lifecycle phase exercises the host-side - // conditions a Linux Docker-driver host can reach from - // `ubuntu-latest`: - // 1. `docker stop` the labeled sandbox container (gateway is - // left HEALTHY — the OpenShell CLI on `ubuntu-latest` has - // no `gateway start` subcommand and #4578's mitigation - // would otherwise mask the regression target). - // 2. Run `nemoclaw status` so any destructive - // registry/container path runs against host-observable - // state. - // The state-validation phase then asserts the host-side - // invariants declared by the `post-reboot-recovery-ready` - // expected-state: cli installed, local registry entry - // preserved, labeled Docker container present (running, - // stopped, or `*-nemoclaw-gpu-backup-*` sibling). - // - // The full DGX Spark post-reboot bug class — healthy_named - // gateway returning literal `NotFound` while Docker still has - // the labeled container — cannot be reproduced from CI without - // a real reboot. This target therefore locks in #4578's - // mitigation and the host-side preservation invariants any - // recovery path must respect; PR-A's Docker-driver recovery - // helper (parts 2 & 3 of ericksoa's plan) extends this scaffold, - // and a follow-up target on a controlled runner can layer in - // gateway/sandbox runtime probes once that helper lands. + // Reboot-style Docker-driver recovery without a physical reboot: + // 1. `docker stop` the labeled sandbox container. + // 2. Stop the OpenShell gateway runtime, then restart it through + // `openshell-gateway.service` when the host exposes the user + // service. Hosts without a visible user service use the + // documented first-session fallback path. + // 3. Run `nemoclaw status` so any destructive + // registry/container path runs against host-observable state. + // The state-validation phase then asserts the typed + // `post-reboot-recovery-ready` contract: cli installed, named + // gateway healthy, local registry entry preserved, and labeled + // Docker container present (running, stopped, or a + // `*-nemoclaw-gpu-backup-*` sibling). id: "ubuntu-repo-docker-post-reboot-recovery", manifestName: "openclaw-nvidia-post-reboot-recovery", environment: ubuntuRepoDockerLifecycle("cloud-openclaw", "post-reboot-recovery"), @@ -191,8 +178,8 @@ const canonicalTargetInputs: CanonicalTargetInput[] = [ suiteIds: ["smoke"], requiredSecrets: ["NVIDIA_INFERENCE_API_KEY"], description: - "Failing-test-first guard for #4423: post-reboot recovery must preserve " + - "the local registry entry and restart the labeled Docker container.", + "Post-reboot recovery guard: the gateway must recover through the user service " + + "or first-session fallback while preserving the local sandbox registry and container.", }, { id: "ubuntu-repo-openai-compatible-openclaw", diff --git a/test/e2e/registry/expected-states.ts b/test/e2e/registry/expected-states.ts index a1f3c552f01..9edb6cfddc9 100644 --- a/test/e2e/registry/expected-states.ts +++ b/test/e2e/registry/expected-states.ts @@ -88,9 +88,9 @@ const onboardingFailurePolicyPresetsRequired: ExpectedState = { cli: { installed: true }, }; -// Post-reboot recovery contract for #4423. After the lifecycle phase -// stops the labeled sandbox container, the host-side invariants this -// target locks down are: +// Post-reboot recovery contract. After the lifecycle phase restarts +// the OpenShell gateway through the user service when available, then +// runs `nemoclaw status`, this target locks down: // // * `cli` still installed. // * `localRegistry` entry preserved: this is the user-visible @@ -102,16 +102,14 @@ const onboardingFailurePolicyPresetsRequired: ExpectedState = { // not delete the labeled container or its `*-nemoclaw-gpu-backup-*` // sibling as a side effect. // -// Gateway/sandbox runtime state are intentionally OMITTED from this -// expected state. The user-visible bug is host-side state -// destruction; gateway/sandbox liveness on a `ubuntu-latest` runner -// after `docker stop` is environmental and varies independently of -// the regression target. Once PR-A lands its Docker-driver recovery -// helper, a follow-up target can extend the expected state with -// runtime invariants on a more controlled runner. +// * `gateway` healthy: the user-service path must restore the +// named OpenShell gateway without `nemoclaw onboard --resume` +// when persistence is available, with the documented first- +// session fallback used only when a user service is not exposed. const postRebootRecoveryReady: ExpectedState = { id: "post-reboot-recovery-ready", cli: { installed: true }, + gateway: { expected: "present", health: "healthy" }, localRegistry: { expected: "present" }, dockerSandboxContainer: { expected: "present" }, }; diff --git a/test/e2e/support/e2e-expected-state.test.ts b/test/e2e/support/e2e-expected-state.test.ts index edd95b0361f..87a07bcfce9 100644 --- a/test/e2e/support/e2e-expected-state.test.ts +++ b/test/e2e/support/e2e-expected-state.test.ts @@ -200,8 +200,8 @@ describe("target expected-state references", () => { } }); - // source-shape-contract: security -- Post-reboot targets must retain host registry and container preservation probes - it("compiles host-preservation probes for every post-reboot recovery target", () => { + // source-shape-contract: security -- Post-reboot targets must retain host preservation and gateway recovery probes + it("compiles gateway-health and host-preservation probes for every post-reboot recovery target", () => { const recoveryTargets = listTargets().filter( (target) => target.environment?.lifecycle === "post-reboot-recovery", ); @@ -211,6 +211,7 @@ describe("target expected-state references", () => { const probes = probesForState(requireExpectedState(target.expectedStateId!)); expect(probes, target.id).toEqual( expect.arrayContaining([ + "gateway-healthy", "local-registry-entry-present", "docker-sandbox-container-present", ]), diff --git a/test/e2e/support/e2e-phase-lifecycle.test.ts b/test/e2e/support/e2e-phase-lifecycle.test.ts index ead03683b27..298afab3d74 100644 --- a/test/e2e/support/e2e-phase-lifecycle.test.ts +++ b/test/e2e/support/e2e-phase-lifecycle.test.ts @@ -114,10 +114,16 @@ function restoreEnv(name: string, value: string | undefined): void { } describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", () => { - it("stops the labeled container then runs `nemoclaw status`", async () => { + it("stops the labeled container, restarts the gateway service, then runs status", async () => { const runner = new FakeRunner(); runner.enqueue(shellResult(0, "openshell-cluster-e2e-ubuntu-repo-cloud-openclaw\n")); // discover runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status (non-zero on unfixed) const cleanup = new FakeCleanup(); @@ -126,28 +132,20 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", expect(result.profile).toBe("post-reboot-recovery"); expect(result.steps.map((step) => step.id)).toEqual([ "docker-stop:openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", + "gateway-restart:user-service-or-session", + "gateway-connected:nemoclaw", "nemoclaw-status:e2e-ubuntu-repo-cloud-openclaw", ]); - expect(runner.calls.map((call) => ({ command: call.command, args: call.args }))).toEqual([ - { - command: "docker", - args: [ - "ps", - "-a", - "--filter", - "label=openshell.ai/sandbox-name=e2e-ubuntu-repo-cloud-openclaw", - "--format", - "{{.Names}}", - ], - }, - { - command: "docker", - args: ["stop", "openshell-cluster-e2e-ubuntu-repo-cloud-openclaw"], - }, - { - command: "nemoclaw", - args: ["e2e-ubuntu-repo-cloud-openclaw", "status"], - }, + expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual([ + "docker ps -a --filter label=openshell.ai/sandbox-name=e2e-ubuntu-repo-cloud-openclaw --format {{.Names}}", + "docker stop openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", + "sh -lc command -v openshell >/dev/null 2>&1 && openshell forward stop 18789 || true", + "sh -lc command -v openshell >/dev/null 2>&1 && openshell gateway stop -g nemoclaw || true", + expect.stringContaining("sh -lc pid_file="), + expect.stringContaining("sh -lc cid="), + expect.stringContaining("sh -lc set -eu"), + "openshell status", + "nemoclaw e2e-ubuntu-repo-cloud-openclaw status", ]); expect(cleanup.calls.map((call) => call.name)).toEqual([ "lifecycle.docker-start:openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", @@ -158,6 +156,12 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", const runner = new FakeRunner(); runner.enqueue(shellResult(0, "container-1\n")); // discover runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status non-zero const cleanup = new FakeCleanup(); @@ -195,6 +199,12 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (rename-to-gpu-bac runner.enqueue(shellResult(0, "openshell-cluster-e2e-x\n")); // discover runner.enqueue(shellResult(0)); // docker stop runner.enqueue(shellResult(0)); // docker rename + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(0)); // user service restart + runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // openshell status runner.enqueue(shellResult(1, "Removed stale local registry entry.\n")); // status const cleanup = new FakeCleanup(); @@ -267,6 +277,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { runner.enqueue(shellResult(1, "")); // expectHostRuntimeStopped pid probe runner.enqueue(shellResult(0, "")); // expectHostRuntimeStopped container probe runner.enqueue(shellResult(0)); // lifecycle-gateway-stopped true artifact + runner.enqueue(shellResult(75, "")); // no user service available runner.enqueue(shellResult(0, "status recovered\n")); // start through nemoclaw status runner.enqueue(shellResult(0, "Connected to nemoclaw\n")); // waitForGatewayConnected const cleanup = new FakeCleanup(); @@ -289,6 +300,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { expect.stringContaining("sh -lc pid_file="), "docker ps -qf name=openshell-cluster-nemoclaw", "true ", + expect.stringContaining("sh -lc set -eu"), "nemoclaw status", "openshell status", ]); @@ -296,6 +308,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { it("can recover a PID runtime through sandbox-specific status", async () => { const runner = new FakeRunner(); + runner.enqueue(shellResult(75, "")); // no user service available runner.enqueue(shellResult(0, "status recovered\n")); const cleanup = new FakeCleanup(); @@ -309,6 +322,7 @@ describe("LifecyclePhaseFixture gateway runtime restart helpers", () => { ).resolves.toMatchObject({ exitCode: 0 }); expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual([ + expect.stringContaining("sh -lc set -eu"), "nemoclaw e2e-survival status", ]); }); From cb818a0dfe01b79bcb102b268660a5f47ebf670e Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 15:54:45 +0530 Subject: [PATCH 14/24] test(e2e): update source-shape gateway recovery allowance --- ci/source-shape-test-budget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 49b3c98cbe2..c418b1151d2 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -138,7 +138,7 @@ }, { "file": "test/e2e/support/e2e-expected-state.test.ts", - "test": "compiles host-preservation probes for every post-reboot recovery target", + "test": "compiles gateway-health and host-preservation probes for every post-reboot recovery target", "category": "security" }, { From 949bb42373a2f1762e37a0d87c7c0445e8b191f4 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 16:15:31 +0530 Subject: [PATCH 15/24] fix(install): address gateway service review blockers --- docs/reference/troubleshooting.mdx | 23 +++++++++- .../run-plan-gateway-service.test.ts | 43 +++++++++++++++++++ src/lib/actions/uninstall/run-plan.ts | 2 +- test/e2e/fixtures/phases/lifecycle.ts | 36 ++++++++++++---- test/e2e/support/e2e-phase-lifecycle.test.ts | 26 ++++++++++- test/reboot-recovery-docs.test.ts | 33 ++++++++++++++ 6 files changed, 149 insertions(+), 14 deletions(-) create mode 100644 test/reboot-recovery-docs.test.ts diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 9c7387d47ca..cfb53237678 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -848,17 +848,36 @@ Follow these steps to reconnect. - **Linux:** start Docker if it is not already running (`sudo systemctl start docker`) - **macOS:** open Docker Desktop or start Colima (`colima start`) +1. Check the managed OpenShell gateway service on Linux tarball installs. + + NemoClaw installs a marked user `openshell-gateway.service` on Linux tarball installs. + The systemd user manager starts it after reboot, or at the next user session when lingering is not enabled. + If `systemctl --user` is available, check and restart it first: + + ```bash + systemctl --user status openshell-gateway + systemctl --user restart openshell-gateway + ``` + + On macOS, non-systemd Linux hosts, or hosts where the user service cannot be reached, continue with the NemoClaw recovery step below. + 1. Check sandbox state. ```bash openshell sandbox list ``` - If the sandbox shows `Ready`, skip to step 4. + If the sandbox shows `Ready`, skip to step 5. 1. Recover the managed gateway (if needed). - If the sandbox is not listed or the command fails, let NemoClaw recover the managed gateway and sandbox registration: + If the sandbox is not listed after the service restart, or `systemctl --user` is unavailable, first ask NemoClaw to reconnect through the recorded sandbox: + + ```bash + $$nemoclaw status + ``` + + If that cannot restore the gateway registration, resume onboarding to recreate the managed gateway metadata: ```bash $$nemoclaw onboard --resume diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 8c6dfe7975c..9d61ae217a5 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -149,6 +149,49 @@ describe("uninstall OpenShell gateway user service", () => { } }); + it("reports incomplete uninstall when the managed service cannot be read", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + const originalReadFileSync = fs.readFileSync; + const readSpy = vi.spyOn(fs, "readFileSync").mockImplementation((( + target: fs.PathOrFileDescriptor, + options?: Parameters[1], + ) => { + if (String(target) === servicePath) throw new Error("permission denied"); + return originalReadFileSync(target, options as never) as ReturnType; + }) as typeof fs.readFileSync); + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: () => true, + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(true); + expect(errors).toContain( + `Failed to read ${servicePath}; leaving gateway user service in place.`, + ); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + readSpy.mockRestore(); + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + it("does not remove Linux user service units on macOS", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-macos-service-")); const servicePath = writeManagedService(tmpHome); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index e7736d64304..8e1b7d917b2 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -621,7 +621,7 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): b unit = fs.readFileSync(servicePath, "utf-8"); } catch { runtime.warn(`Failed to read ${servicePath}; leaving gateway user service in place.`); - return true; + return false; } if ( !unit diff --git a/test/e2e/fixtures/phases/lifecycle.ts b/test/e2e/fixtures/phases/lifecycle.ts index 3b90081b145..2575bc1b230 100644 --- a/test/e2e/fixtures/phases/lifecycle.ts +++ b/test/e2e/fixtures/phases/lifecycle.ts @@ -36,6 +36,9 @@ const REBUILD_TIMEOUT_MS = 20 * 60_000; const SANDBOX_READY_ATTEMPTS = 30; const SANDBOX_READY_DELAY_MS = 5_000; const USER_SERVICE_UNAVAILABLE_EXIT = 75; +const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; +const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = + "# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; export type LifecycleProfile = "post-reboot-recovery" | "dcode-rebuild-invalid-credential"; @@ -269,10 +272,11 @@ export class LifecyclePhaseFixture { const previousRuntime = await this.restartGatewayRuntime({ delayMs: 0, + requireUserService: true, sandboxName: instance.sandboxName, }); steps.push({ - id: `gateway-restart:${previousRuntime?.kind ?? "user-service-or-session"}`, + id: `gateway-restart:${previousRuntime?.kind ?? "user-service"}`, results: [], }); await this.waitForGatewayConnected(); @@ -359,9 +363,11 @@ export class LifecyclePhaseFixture { async startGatewayRuntime( previousRuntime: HostGatewayRuntime | null, - options: { sandboxName?: string } = {}, + options: { requireUserService?: boolean; sandboxName?: string } = {}, ): Promise { - const userServiceStart = await this.startOpenShellGatewayUserService(); + const userServiceStart = await this.startOpenShellGatewayUserService({ + requireAvailable: options.requireUserService, + }); if (userServiceStart) return userServiceStart; if (options.sandboxName) { return await this.host.nemoclaw([options.sandboxName, "status"], { @@ -384,18 +390,22 @@ export class LifecyclePhaseFixture { }); } - private async startOpenShellGatewayUserService(): Promise { + private async startOpenShellGatewayUserService(options: { + requireAvailable?: boolean; + }): Promise { const result = await this.host.command( "sh", [ "-lc", [ "set -eu", + `unit="$HOME/.config/systemd/user/${OPENSHELL_GATEWAY_USER_SERVICE}.service"`, `if ! command -v systemctl >/dev/null 2>&1; then exit ${USER_SERVICE_UNAVAILABLE_EXIT}; fi`, - `fragment="$(systemctl --user show openshell-gateway --property=FragmentPath --value 2>/dev/null || true)"`, - `case "$fragment" in */openshell-gateway.service) ;; *) exit ${USER_SERVICE_UNAVAILABLE_EXIT} ;; esac`, + `if [ ! -f "$unit" ]; then exit ${USER_SERVICE_UNAVAILABLE_EXIT}; fi`, + `grep -Fxq '${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE}' "$unit" || exit ${USER_SERVICE_UNAVAILABLE_EXIT}`, + `systemctl --user is-enabled ${OPENSHELL_GATEWAY_USER_SERVICE} >/dev/null`, "systemctl --user daemon-reload", - "systemctl --user restart openshell-gateway", + `systemctl --user restart ${OPENSHELL_GATEWAY_USER_SERVICE}`, ].join("\n"), ], { @@ -405,7 +415,14 @@ export class LifecyclePhaseFixture { }, ); if (result.exitCode === 0) return result; - if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT) return null; + if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT && !options.requireAvailable) { + return null; + } + if (result.exitCode === USER_SERVICE_UNAVAILABLE_EXIT) { + throw new Error( + `OpenShell gateway user service is not available for reboot lifecycle recovery.`, + ); + } throw new Error( `OpenShell gateway user service restart failed during reboot lifecycle: ` + `${result.stderr || result.stdout || `exit ${String(result.exitCode)}`}`, @@ -413,7 +430,7 @@ export class LifecyclePhaseFixture { } async restartGatewayRuntime( - options: { delayMs?: number; sandboxName?: string } = {}, + options: { delayMs?: number; requireUserService?: boolean; sandboxName?: string } = {}, ): Promise { const previousRuntime = await this.stopGatewayRuntime(); if (this.gateway) { @@ -426,6 +443,7 @@ export class LifecyclePhaseFixture { await new Promise((resolve) => setTimeout(resolve, delayMs)); } await this.startGatewayRuntime(previousRuntime, { + requireUserService: options.requireUserService, sandboxName: options.sandboxName, }); return previousRuntime; diff --git a/test/e2e/support/e2e-phase-lifecycle.test.ts b/test/e2e/support/e2e-phase-lifecycle.test.ts index 298afab3d74..24175ecbdaa 100644 --- a/test/e2e/support/e2e-phase-lifecycle.test.ts +++ b/test/e2e/support/e2e-phase-lifecycle.test.ts @@ -132,7 +132,7 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", expect(result.profile).toBe("post-reboot-recovery"); expect(result.steps.map((step) => step.id)).toEqual([ "docker-stop:openshell-cluster-e2e-ubuntu-repo-cloud-openclaw", - "gateway-restart:user-service-or-session", + "gateway-restart:user-service", "gateway-connected:nemoclaw", "nemoclaw-status:e2e-ubuntu-repo-cloud-openclaw", ]); @@ -143,7 +143,7 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", "sh -lc command -v openshell >/dev/null 2>&1 && openshell gateway stop -g nemoclaw || true", expect.stringContaining("sh -lc pid_file="), expect.stringContaining("sh -lc cid="), - expect.stringContaining("sh -lc set -eu"), + expect.stringContaining("systemctl --user is-enabled openshell-gateway"), "openshell status", "nemoclaw e2e-ubuntu-repo-cloud-openclaw status", ]); @@ -191,6 +191,28 @@ describe("LifecyclePhaseFixture.simulate post-reboot-recovery (stop-original)", fixture(runner, cleanup).simulate("post-reboot-recovery", instance()), ).rejects.toThrow(/could not query Docker for label/); }); + + it("fails when the managed OpenShell gateway user service is unavailable", async () => { + const runner = new FakeRunner(); + runner.enqueue(shellResult(0, "container-1\n")); // discover + runner.enqueue(shellResult(0)); // docker stop + runner.enqueue(shellResult(0)); // forward stop + runner.enqueue(shellResult(0)); // gateway stop + runner.enqueue(shellResult(0)); // pid stop + runner.enqueue(shellResult(0)); // container stop + runner.enqueue(shellResult(75, "")); // no managed user service available + const cleanup = new FakeCleanup(); + + await expect( + fixture(runner, cleanup).simulate("post-reboot-recovery", instance()), + ).rejects.toThrow(/OpenShell gateway user service is not available/); + + expect(runner.calls.map((call) => `${call.command} ${call.args.join(" ")}`)).toEqual( + expect.arrayContaining([ + expect.stringContaining("systemctl --user is-enabled openshell-gateway"), + ]), + ); + }); }); describe("LifecyclePhaseFixture.simulate post-reboot-recovery (rename-to-gpu-backup)", () => { diff --git a/test/reboot-recovery-docs.test.ts b/test/reboot-recovery-docs.test.ts new file mode 100644 index 00000000000..4f317150c86 --- /dev/null +++ b/test/reboot-recovery-docs.test.ts @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const repoRoot = path.resolve(import.meta.dirname, ".."); +const troubleshooting = readFileSync( + path.join(repoRoot, "docs/reference/troubleshooting.mdx"), + "utf8", +); + +function section(markdown: string, heading: string): string { + const start = markdown.indexOf(heading); + expect(start).toBeGreaterThanOrEqual(0); + const next = markdown.indexOf("\n### ", start + heading.length); + return markdown.slice(start, next === -1 ? undefined : next); +} + +describe("reboot recovery documentation", () => { + it("routes Linux users through the managed OpenShell service before onboard resume", () => { + const reboot = section(troubleshooting, "### Reconnect after a host reboot"); + + expect(reboot).toContain("openshell-gateway.service"); + expect(reboot).toContain("systemctl --user restart openshell-gateway"); + expect(reboot).toContain("macOS, non-systemd Linux hosts"); + expect(reboot.indexOf("systemctl --user restart openshell-gateway")).toBeLessThan( + reboot.indexOf("$$nemoclaw onboard --resume"), + ); + }); +}); From 8155f61b3aa5e303bcd57b64729135938c2b0634 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 16:18:54 +0530 Subject: [PATCH 16/24] test(uninstall): satisfy conditional guardrail --- src/lib/actions/uninstall/run-plan-gateway-service.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 9d61ae217a5..8b108bc1dd3 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -158,8 +158,11 @@ describe("uninstall OpenShell gateway user service", () => { target: fs.PathOrFileDescriptor, options?: Parameters[1], ) => { - if (String(target) === servicePath) throw new Error("permission denied"); - return originalReadFileSync(target, options as never) as ReturnType; + return String(target) === servicePath + ? (() => { + throw new Error("permission denied"); + })() + : (originalReadFileSync(target, options as never) as ReturnType); }) as typeof fs.readFileSync); try { From c6c164b2d0da997f86dad13a318fb36ec39174eb Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 18:18:17 +0530 Subject: [PATCH 17/24] fix(onboard): align openshell gateway service startup --- docs/manage-sandboxes/uninstall-nemoclaw.mdx | 2 +- docs/reference/architecture.mdx | 5 +- docs/reference/commands.mdx | 2 +- docs/reference/troubleshooting.mdx | 2 + scripts/install.sh | 16 +- .../run-plan-gateway-service.test.ts | 72 +++++++++ src/lib/actions/uninstall/run-plan.ts | 65 +++++--- src/lib/onboard.ts | 6 +- .../docker-driver-gateway-env-service.test.ts | 51 +++++- .../onboard/docker-driver-gateway-env.test.ts | 25 +++ src/lib/onboard/docker-driver-gateway-env.ts | 36 +++-- .../docker-driver-gateway-service.test.ts | 146 +++++++++++++++++- .../onboard/docker-driver-gateway-service.ts | 97 +++++++++--- src/lib/onboard/gateway-binding.test.ts | 9 ++ src/lib/onboard/gateway-binding.ts | 7 +- .../onboard/gateway-http-readiness.test.ts | 30 +++- src/lib/onboard/gateway-http-readiness.ts | 9 +- .../install-openshell-gateway-service.test.ts | 61 ++++++++ 18 files changed, 566 insertions(+), 75 deletions(-) diff --git a/docs/manage-sandboxes/uninstall-nemoclaw.mdx b/docs/manage-sandboxes/uninstall-nemoclaw.mdx index dd9b52cea1d..844b4217f51 100644 --- a/docs/manage-sandboxes/uninstall-nemoclaw.mdx +++ b/docs/manage-sandboxes/uninstall-nemoclaw.mdx @@ -20,7 +20,7 @@ $$nemoclaw uninstall | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt. | -| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `$XDG_CONFIG_HOME/systemd/user/openshell-gateway.service` unit, or `~/.config/systemd/user/openshell-gateway.service` when `XDG_CONFIG_HOME` is unset, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models. | | `--destroy-user-data` | Also remove preserved user data in `rebuild-backups/`, `backups/`, and `sandboxes.json`. | | `--gateway ` | Override the gateway name to remove. The default is `nemoclaw`. | diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 370f1281db2..1013cd55cc8 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -81,9 +81,12 @@ graph LR The logical diagram above shows how components relate. This section shows what actually runs where on the host. NemoClaw's default Docker-driver topology does not place the sandbox in an embedded k3s cluster. -On Linux, NemoClaw configures, enables, and restarts a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. +On Linux, NemoClaw configures, enables, restarts, and checks a trusted OpenShell gateway user service, then creates the sandbox as a Docker container. NemoClaw prefers the upstream package-managed `openshell-gateway.service` when `systemctl --user show openshell-gateway` reports a package/vendor unit path and an `openshell-gateway` `ExecStart`. For tarball-installed OpenShell binaries, the installer and onboarding stage a marked user-level `openshell-gateway.service` that follows OpenShell's systemd service model, so the gateway can restart after reboot or at the next user session. +The marker identifies the unit as NemoClaw-owned before NemoClaw reconciles or removes it. +The marked unit generates the local OpenShell mTLS bundle before daemon startup; its `openshell/gateway.env` file overrides the gateway port, Docker-driver configuration, and NemoClaw gateway state. +The marked unit and environment file use `$XDG_CONFIG_HOME` when it is set to an absolute path, otherwise they use `~/.config`. Arbitrary per-user units, partial units, and user-manager or bus outages do not take over gateway ownership; NemoClaw falls back to the standalone gateway process when no trusted service path is available. If NemoClaw cannot write or remove its marked user unit, it reports the filesystem failure and keeps the standalone fallback available. That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 89fcef690f5..4ed4b858d44 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3035,7 +3035,7 @@ On Linux, uninstall removes `~/.local/state/nemoclaw`, which contains Docker-dri | Flag | Effect | |---|---| | `--yes` | Skip the confirmation prompt | -| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `~/.config/systemd/user/openshell-gateway.service` unit, upstream Linux package units, and the macOS Homebrew service. | +| `--keep-openshell` | Leave OpenShell binaries, gateway service daemons, and gateway service configuration in place, without disabling or removing the OpenShell gateway service or stopping the host `openshell-gateway` daemon. This includes NemoClaw's marked Linux `$XDG_CONFIG_HOME/systemd/user/openshell-gateway.service` unit, or `~/.config/systemd/user/openshell-gateway.service` when `XDG_CONFIG_HOME` is unset, upstream Linux package units, and the macOS Homebrew service. | | `--delete-models` | Also remove NemoClaw-pulled Ollama models | | `--destroy-user-data` | Also remove preserved user data (`rebuild-backups/`, `backups/`, `sandboxes.json`) | | `--gateway ` | Override the gateway name to remove (default: `$$nemoclaw`) | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index cfb53237678..4be9151c12d 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -851,6 +851,8 @@ Follow these steps to reconnect. 1. Check the managed OpenShell gateway service on Linux tarball installs. NemoClaw installs a marked user `openshell-gateway.service` on Linux tarball installs. + The unit is written under `$XDG_CONFIG_HOME/systemd/user` when `XDG_CONFIG_HOME` is absolute, otherwise under `~/.config/systemd/user`. + The service generates the local OpenShell mTLS bundle before starting and then reads NemoClaw's `openshell/gateway.env` overrides. The systemd user manager starts it after reboot, or at the next user session when lingering is not enabled. If `systemctl --user` is available, check and restart it first: diff --git a/scripts/install.sh b/scripts/install.sh index 2ffaa1f5aa3..8b9376f2035 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1159,10 +1159,19 @@ is_nemoclaw_openshell_gateway_user_service() { grep -Fxq "$NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE" "$service_path" } +openshell_user_config_home() { + if [[ -n "${XDG_CONFIG_HOME:-}" && "$XDG_CONFIG_HOME" == /* ]]; then + printf '%s\n' "$XDG_CONFIG_HOME" + else + printf '%s\n' "${HOME}/.config" + fi +} + install_nemoclaw_openshell_gateway_user_service() { [[ "$(uname -s)" == "Linux" ]] || return 0 - local service_dir="${HOME}/.config/systemd/user" + local service_dir + service_dir="$(openshell_user_config_home)/systemd/user" local service_path="${service_dir}/openshell-gateway.service" if upstream_openshell_gateway_user_service_installed; then @@ -1206,11 +1215,14 @@ $NEMOCLAW_GATEWAY_SERVICE_MARKER_LINE [Unit] Description=OpenShell Gateway Documentation=https://github.com/NVIDIA/OpenShell +After=default.target [Service] Type=simple StateDirectory=openshell/gateway +Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls EnvironmentFile=-%E/openshell/gateway.env +ExecStartPre=$gateway_bin generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1 ExecStart=$gateway_bin Restart=on-failure RestartSec=5s @@ -1243,6 +1255,8 @@ maybe_install_openshell_during_install() { return 0 fi if [[ "$mode" == "if-missing" ]] && command_exists openshell; then + prefer_user_local_openshell + install_nemoclaw_openshell_gateway_user_service return 0 fi spin "Installing OpenShell CLI" bash "${NEMOCLAW_SOURCE_ROOT}/scripts/install-openshell.sh" diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 8b108bc1dd3..755d3a338b7 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -70,6 +70,7 @@ describe("uninstall OpenShell gateway user service", () => { expect(run.mock.calls.map(([command, args]) => [command, ...args].join("\0"))).not.toContain( ["pgrep", "-f", HOST_GATEWAY_PGREP_PATTERN].join("\0"), ); + expect(run.mock.calls.some(([command]) => command === "pgrep")).toBe(false); } finally { fs.rmSync(tmpHome, { recursive: true, force: true }); } @@ -195,6 +196,77 @@ describe("uninstall OpenShell gateway user service", () => { } }); + it("reports incomplete uninstall when the managed service file cannot be removed", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: vi.fn((target: fs.PathLike) => { + if (String(target) === servicePath) throw new Error("permission denied"); + fs.rmSync(target, { recursive: true, force: true }); + }) as typeof fs.rmSync, + run: vi.fn(() => ok()), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(true); + expect(errors).toContain(`Failed to remove ${servicePath}: permission denied`); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + + it("reports incomplete uninstall when user systemd reload fails after removal", () => { + const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const servicePath = writeManagedService(tmpHome); + const errors: string[] = []; + + try { + const result = runUninstallPlan( + { assumeYes: true, deleteModels: false, keepOpenShell: false }, + { + commandExists: (command) => command === "systemctl", + env: { HOME: tmpHome } as NodeJS.ProcessEnv, + error: (line) => errors.push(line), + existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + isTty: false, + platform: "linux", + rmSync: fs.rmSync, + run: vi.fn((command: string, args: string[]) => + command === "systemctl" && args.includes("daemon-reload") + ? { status: 1, stdout: "", stderr: "failed\n" } + : ok(), + ), + runDocker: () => ok(""), + }, + ); + + expect(result.exitCode).toBe(1); + expect(fs.existsSync(servicePath)).toBe(false); + expect(errors).toContain("Failed to reload the user systemd manager."); + expect(errors).toContain( + "Uninstall completed with errors. Some state may remain on disk; see warnings above.", + ); + } finally { + fs.rmSync(tmpHome, { recursive: true, force: true }); + } + }); + it("does not remove Linux user service units on macOS", () => { const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-macos-service-")); const servicePath = writeManagedService(tmpHome); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 8e1b7d917b2..498a77accef 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -10,18 +10,18 @@ import { dockerSpawnSync } from "../../adapters/docker/exec"; import { type AgentBranding, getAgentBranding } from "../../cli/branding"; import { isStdinTty, readLineFromStdin } from "../../core/stdin"; import { sleepMs } from "../../core/wait"; -import { - defaultUninstallPaths, - NEMOCLAW_OLLAMA_MODELS, - NEMOCLAW_PROVIDERS, - type UninstallPaths, -} from "../../domain/uninstall/paths"; import { gatewayDestroySkipMessage, OPENSHELL_SANDBOXES_DELETE_SKIP_MESSAGE, preservedRegistryUnrecoverableWarnings, providerDeleteSkipMessage, } from "../../domain/uninstall/messaging"; +import { + defaultUninstallPaths, + NEMOCLAW_OLLAMA_MODELS, + NEMOCLAW_PROVIDERS, + type UninstallPaths, +} from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { getNemoclawOpenShellGatewayUserServicePath, @@ -613,7 +613,10 @@ function stopOrphanedOpenShell(runtime: UninstallRuntime): void { function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): boolean { if (runtime.platform !== "linux") return true; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(runtime.env.HOME || os.homedir()); + const servicePath = getNemoclawOpenShellGatewayUserServicePath( + runtime.env.HOME || os.homedir(), + runtime.env, + ); if (!runtime.existsSync(servicePath)) return true; let unit = ""; @@ -649,15 +652,27 @@ function removeNemoclawOpenShellGatewayUserService(runtime: UninstallRuntime): b runtime.warn("systemctl not found; removing NemoClaw gateway user service file only."); } - runtime.rmSync(servicePath, { force: true }); - runtime.log(`Removed ${servicePath}`); + let removed = false; + try { + runtime.rmSync(servicePath, { force: true }); + removed = true; + } catch (error) { + runtime.warn( + `Failed to remove ${servicePath}: ${error instanceof Error ? error.message : String(error)}`, + ); + disabled = false; + } + if (removed) runtime.log(`Removed ${servicePath}`); if (runtime.commandExists("systemctl")) { const reload = runtime.run("systemctl", ["--user", "daemon-reload"], { env: runtime.env, stdio: "ignore", }); - if (reload.status !== 0) runtime.warn("Failed to reload the user systemd manager."); + if (reload.status !== 0) { + runtime.warn("Failed to reload the user systemd manager."); + disabled = false; + } } return disabled; } @@ -954,22 +969,22 @@ function executePlan( if (step.name === "Stopping services") { stopHelperServices(paths, runtime); removeGlob(paths.helperServiceGlob, runtime); - if (!options.keepOpenShell && !removeNemoclawOpenShellGatewayUserService(runtime)) ok = false; - stopMatchingPids( - `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, - runtime, - "local OpenShell forward processes", - ); - stopStaleDashboardListeners({ - run: runtime.run, - kill: runtime.kill, - env: runtime.env, - log: runtime.log, - warn: runtime.warn, - commandExists: runtime.commandExists, - }); - stopOrphanedOpenShell(runtime); if (!options.keepOpenShell) { + if (!removeNemoclawOpenShellGatewayUserService(runtime)) ok = false; + stopMatchingPids( + `openshell.*forward.*${runtime.env.NEMOCLAW_DASHBOARD_PORT || "18789"}`, + runtime, + "local OpenShell forward processes", + ); + stopStaleDashboardListeners({ + run: runtime.run, + kill: runtime.kill, + env: runtime.env, + log: runtime.log, + warn: runtime.warn, + commandExists: runtime.commandExists, + }); + stopOrphanedOpenShell(runtime); stopHostGatewayProcesses( { run: runtime.run, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 862b84a69d8..18fda5d204e 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -1992,7 +1992,8 @@ async function startDockerDriverGateway({ gatewayBin, gatewayEnv: driftGatewayEnv, gatewayName: GATEWAY_NAME, - isDockerDriverGatewayReady: () => isDockerDriverGatewayHttpReady(), + isDockerDriverGatewayReady: () => + isDockerDriverGatewayHttpReady(undefined, undefined, driftGatewayEnv), registerDockerDriverGatewayEndpoint, runCaptureOpenshell, skipSandboxBridgeReachability, @@ -2039,7 +2040,8 @@ async function startDockerDriverGateway({ getDockerDriverGatewayRuntimeDrift, logDockerDriverGatewayRestart, registerDockerDriverGatewayEndpoint, - isDockerDriverGatewayHttpReady, + isDockerDriverGatewayHttpReady: () => + isDockerDriverGatewayHttpReady(undefined, undefined, driftGatewayEnv), verifySandboxBridgeGatewayReachableOrExit: (fail, options) => verifySandboxBridgeGatewayReachableOrExit(fail, { ...options, diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index 3cc5329ad4a..ffdedee5f95 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -6,9 +6,8 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; - -import { startPackageManagedDockerDriverGatewayWithEnvOverride } from "./docker-driver-gateway-env"; import { writeSafeGatewayAuthConfig } from "../../../test/support/docker-driver-gateway-env-test-support"; +import { startPackageManagedDockerDriverGatewayWithEnvOverride } from "./docker-driver-gateway-env"; describe("package-managed Docker-driver gateway env service", () => { it("writes the service env only when package-managed startup prepares the service", async () => { @@ -63,6 +62,54 @@ describe("package-managed Docker-driver gateway env service", () => { } }); + it("uses one XDG config root for the service unit and gateway env", async () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const configHome = path.join(tempHome, "xdg-config"); + const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(configHome, "systemd", "user", "openshell-gateway.service"); + const envFile = path.join(configHome, "openshell", "gateway.env"); + const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); + const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { XDG_CONFIG_HOME: configHome }, + exitOnFailure: false, + gatewayBin, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + OPENSHELL_SERVER_PORT: "18080", + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => + args[0] === "status" + ? "Gateway: nemoclaw\nConnected" + : "Gateway: nemoclaw\nGateway endpoint: https://127.0.0.1:18080/", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: (opts) => { + opts?.prepareServiceEnv?.(); + return { attempted: true, fallbackAllowed: false, started: true }; + }, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).resolves.toBe(true); + + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_SERVER_PORT=18080\n"); + expect(fs.existsSync(path.join(tempHome, ".config", "openshell", "gateway.env"))).toBe(false); + } finally { + existsSpy.mockRestore(); + homedirSpy.mockRestore(); + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + it("rejects package-managed wildcard binds before writing the service env", () => { expect(() => startPackageManagedDockerDriverGatewayWithEnvOverride({ diff --git a/src/lib/onboard/docker-driver-gateway-env.test.ts b/src/lib/onboard/docker-driver-gateway-env.test.ts index c264c530c2c..f903e30d99f 100644 --- a/src/lib/onboard/docker-driver-gateway-env.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env.test.ts @@ -187,6 +187,31 @@ describe("writeDockerGatewayDebEnvOverride", () => { } }); + it("uses the provided HOME as the config root fallback when XDG_CONFIG_HOME is unset", () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-home-")); + const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); + const existsSpy = vi + .spyOn(fs, "existsSync") + .mockImplementation( + (candidate) => candidate === "/usr/lib/systemd/user/openshell-gateway.service", + ); + + try { + const wrote = writeDockerGatewayDebEnvOverride( + () => ({ + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + }), + { env: { HOME: tempHome }, platform: "linux" }, + ); + + expect(wrote).toBe(true); + expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); + } finally { + existsSpy.mockRestore(); + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 0445c03f98d..9755f47930a 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -18,6 +18,7 @@ import { } from "./docker-driver-gateway-config"; import { buildDockerDriverGatewayLocalTlsEnv } from "./docker-driver-gateway-local-tls"; import { + getOpenShellUserConfigHome, hasOpenShellGatewayUserService, installAndReportNemoclawOpenShellGatewayUserService, type PackageManagedDockerDriverGatewayOptions, @@ -58,8 +59,10 @@ export type PackageManagedDockerDriverGatewayWithEnvOverrideOptions = Omit< PackageManagedDockerDriverGatewayOptions, "prepareOpenShellGatewayUserServiceEnv" > & { + env?: NodeJS.ProcessEnv; gatewayBin?: string | null; gatewayEnv: Record; + home?: string; }; export function getGatewayPortCheckOptions(): { host: string } { @@ -260,9 +263,14 @@ function readTextFileIfPresent(filePath: string): string { } } -function writeDockerGatewayDebEnvOverrideFile(getOverride: () => Record): void { +function writeDockerGatewayDebEnvOverrideFile( + getOverride: () => Record, + opts: { env?: NodeJS.ProcessEnv; home?: string } = {}, +): void { const override = getOverride(); - const envDir = path.join(os.homedir(), ".config", "openshell"); + const env = opts.env ?? process.env; + const home = opts.home ?? opts.env?.HOME ?? os.homedir(); + const envDir = path.join(getOpenShellUserConfigHome(home, env), "openshell"); const envFile = path.join(envDir, "gateway.env"); fs.mkdirSync(envDir, { recursive: true, mode: 0o700 }); fs.chmodSync(envDir, 0o700); @@ -279,7 +287,7 @@ export function writeDockerGatewayDebEnvOverride( opts: Parameters[0] = {}, ): boolean { if (!hasOpenShellGatewayUserService(opts)) return false; - writeDockerGatewayDebEnvOverrideFile(getOverride); + writeDockerGatewayDebEnvOverrideFile(getOverride, opts); return true; } @@ -292,18 +300,26 @@ export function writeDockerGatewayDebEnvOverrideOrThrow( } } -export function startPackageManagedDockerDriverGatewayWithEnvOverride({ - gatewayBin, - gatewayEnv, - ...options -}: PackageManagedDockerDriverGatewayWithEnvOverrideOptions): Promise { +export function startPackageManagedDockerDriverGatewayWithEnvOverride( + optionsWithEnv: PackageManagedDockerDriverGatewayWithEnvOverrideOptions, +): Promise { + const { env: _env, gatewayBin, gatewayEnv, home, ...options } = optionsWithEnv; + const env = optionsWithEnv.env ?? process.env; assertDockerDriverGatewayAuthConfigSafe(gatewayEnv); + const effectiveHome = home ?? optionsWithEnv.env?.HOME ?? os.homedir(); if (gatewayBin !== undefined) { - installAndReportNemoclawOpenShellGatewayUserService({ gatewayBin }); + installAndReportNemoclawOpenShellGatewayUserService({ + env, + gatewayBin, + home: effectiveHome, + }); } return startPackageManagedDockerDriverGateway({ ...options, + hasOpenShellGatewayUserService: + options.hasOpenShellGatewayUserService ?? + (() => hasOpenShellGatewayUserService({ env, home: effectiveHome })), prepareOpenShellGatewayUserServiceEnv: () => - writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv), + writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv, { env, home: effectiveHome }), }); } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index f733463f885..2e058c63d9f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import path from "node:path"; + import { describe, expect, it, vi } from "vitest"; import { createVirtualClock } from "./__test-helpers__/virtual-clock"; @@ -9,8 +11,10 @@ import { getNemoclawOpenShellGatewayUserServicePath, getOpenShellGatewayUserServiceBinaryPaths, getOpenShellGatewayUserServicePaths, + getOpenShellUserConfigHome, hasNemoclawOpenShellGatewayUserService, hasOpenShellGatewayUserService, + installAndReportNemoclawOpenShellGatewayUserService, installNemoclawOpenShellGatewayUserService, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, type SpawnSyncLikeResult, @@ -70,6 +74,22 @@ describe("docker-driver-gateway-service", () => { ]); }); + it("resolves the service unit under the effective XDG config home", () => { + expect( + getNemoclawOpenShellGatewayUserServicePath("/home/nvidia", { + XDG_CONFIG_HOME: "/tmp/nemoclaw-config", + }), + ).toBe("/tmp/nemoclaw-config/systemd/user/openshell-gateway.service"); + expect( + getNemoclawOpenShellGatewayUserServicePath("/home/nvidia", { + XDG_CONFIG_HOME: "relative-config", + }), + ).toBe("/home/nvidia/.config/systemd/user/openshell-gateway.service"); + expect(getOpenShellUserConfigHome("/home/nvidia", { XDG_CONFIG_HOME: "/tmp/config" })).toBe( + "/tmp/config", + ); + }); + it("ignores stale per-user service units so standalone fallback remains available", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); @@ -89,20 +109,35 @@ describe("docker-driver-gateway-service", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; + const chmodSync = vi.fn(); + const mkdirSync = vi.fn(); const writeFileSync = vi.fn(); expect( installNemoclawOpenShellGatewayUserService({ - chmodSync: vi.fn(), + chmodSync, existsSync: () => false, gatewayBin, home, - mkdirSync: vi.fn() as never, + mkdirSync: mkdirSync as never, platform: "linux", writeFileSync: writeFileSync as never, }), ).toEqual({ installed: true, path: servicePath }); + expect(mkdirSync).toHaveBeenCalledWith(path.dirname(servicePath), { + recursive: true, + mode: 0o700, + }); + expect(chmodSync).toHaveBeenCalledWith(path.dirname(servicePath), 0o700); + expect(chmodSync).toHaveBeenCalledWith(servicePath, 0o600); expect(String(writeFileSync.mock.calls[0]?.[1])).toContain(`ExecStart=${gatewayBin}`); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain("After=default.target"); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain( + "Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls", + ); + expect(String(writeFileSync.mock.calls[0]?.[1])).toContain( + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, + ); expect( hasNemoclawOpenShellGatewayUserService({ existsSync: (candidate) => candidate === servicePath, @@ -120,6 +155,22 @@ describe("docker-driver-gateway-service", () => { ).toEqual({ installed: false, reason: "not a Linux host" }); }); + it("warns when Linux service installation cannot find a gateway binary", () => { + const warn = vi.fn(); + + expect( + installAndReportNemoclawOpenShellGatewayUserService({ + existsSync: () => false, + gatewayBin: null, + platform: "linux", + warn, + }), + ).toEqual({ installed: false, reason: "OpenShell gateway binary not found" }); + expect(warn).toHaveBeenCalledWith( + " OpenShell gateway user service not installed: OpenShell gateway binary not found.", + ); + }); + it("removes a NemoClaw user override when an upstream service exists", () => { const home = "/home/nvidia"; const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); @@ -192,7 +243,7 @@ describe("docker-driver-gateway-service", () => { it("restarts the upstream user service with systemctl --user after validating identity", () => { const events: string[] = []; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - events.push(args[1] ?? args[0] ?? ""); + events.push(args[0] === "is-active" ? "is-active" : (args[1] ?? args[0] ?? "")); return args.includes("show") ? spawnResult(0, "", trustedShowOutput()) : spawnResult(); }); @@ -206,7 +257,14 @@ describe("docker-driver-gateway-service", () => { }); expect(result).toMatchObject({ attempted: true, fallbackAllowed: false, started: true }); - expect(events).toEqual(["daemon-reload", "show", "prepare-env", "enable", "restart"]); + expect(events).toEqual([ + "daemon-reload", + "show", + "prepare-env", + "enable", + "restart", + "is-active", + ]); expect(spawnSyncImpl.mock.calls.map(([command, args]) => [command, args])).toEqual([ ["systemctl", ["--user", "daemon-reload"]], [ @@ -215,6 +273,7 @@ describe("docker-driver-gateway-service", () => { ], ["systemctl", ["--user", "enable", "openshell-gateway"]], ["systemctl", ["--user", "restart", "openshell-gateway"]], + ["systemctl", ["--user", "is-active", "--quiet", "openshell-gateway"]], ]); }); @@ -300,6 +359,29 @@ describe("docker-driver-gateway-service", () => { expect(result.reason).toContain("No such file or directory"); }); + it("does not report service startup success when the restarted service is inactive", () => { + const result = startOpenShellGatewayUserService({ + commandExists: () => true, + env: {}, + existsSync: () => true, + platform: "linux", + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args.includes("show") + ? spawnResult(0, "", trustedShowOutput()) + : args.includes("is-active") + ? spawnResult(3, "inactive") + : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + started: false, + }); + expect(result.reason).toContain("is-active --quiet openshell-gateway failed"); + }); + it("falls back instead of trusting an unverified service identity", () => { const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { if (args.includes("show")) { @@ -409,6 +491,60 @@ describe("docker-driver-gateway-service", () => { expect(events).toEqual(["register", "sleep", "register", "ready", "clear", "verify"]); }); + it("accepts package-managed service health when CLI metadata is healthy and direct gRPC probe is unavailable", async () => { + const clearDockerDriverGatewayRuntimeFiles = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles, + exitOnFailure: false, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => false, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + started: true, + }), + verifySandboxBridgeGatewayReachableOrExit: vi.fn(), + }), + ).resolves.toBe(true); + + expect(clearDockerDriverGatewayRuntimeFiles).toHaveBeenCalledOnce(); + }); + + it("accepts package-managed service health when direct gRPC probe is healthy and CLI status is unavailable", async () => { + const clearDockerDriverGatewayRuntimeFiles = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles, + exitOnFailure: false, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "gateway" ? GATEWAY_INFO : ""), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + started: true, + }), + verifySandboxBridgeGatewayReachableOrExit: vi.fn(), + }), + ).resolves.toBe(true); + + expect(clearDockerDriverGatewayRuntimeFiles).toHaveBeenCalledOnce(); + }); + it("preserves bounded immediate package-service probes when the interval is zero", async () => { const clock = createVirtualClock(); let registerCount = 0; @@ -485,7 +621,7 @@ describe("docker-driver-gateway-service", () => { isDockerDriverGatewayReady: async () => false, now: clock.now, registerDockerDriverGatewayEndpoint: () => true, - runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + runCaptureOpenshell: (args) => (args[0] === "status" ? "Error: Connection refused" : ""), sleepSeconds: clock.advance, skipSandboxBridgeReachability: false, startOpenShellGatewayUserService: () => ({ diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 39e49ebef76..93d9be0ba6f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -42,7 +42,7 @@ export interface OpenShellGatewayUserServiceStartResult { export interface InstallNemoclawOpenShellGatewayUserServiceOptions extends Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > { chmodSync?: (filePath: string, mode: number) => void; gatewayBin: string | null; @@ -123,8 +123,26 @@ export function getOpenShellGatewayUserServiceBinaryPaths(): string[] { return ["/usr/local/bin/openshell-gateway", "/usr/bin/openshell-gateway"]; } -export function getNemoclawOpenShellGatewayUserServicePath(home = os.homedir()): string { - return path.join(home, ".config", "systemd", "user", "openshell-gateway.service"); +function effectiveHome(home: string | undefined, env: NodeJS.ProcessEnv | undefined): string { + return home ?? env?.HOME ?? os.homedir(); +} + +export function getOpenShellUserConfigHome(home = os.homedir(), env?: NodeJS.ProcessEnv): string { + const configured = env?.XDG_CONFIG_HOME?.trim(); + if (configured && path.isAbsolute(configured)) return path.normalize(configured); + return path.join(home, ".config"); +} + +export function getNemoclawOpenShellGatewayUserServicePath( + home = os.homedir(), + env?: NodeJS.ProcessEnv, +): string { + return path.join( + getOpenShellUserConfigHome(home, env), + "systemd", + "user", + "openshell-gateway.service", + ); } export function getNemoclawOpenShellGatewayUserServiceBinaryPaths(home = os.homedir()): string[] { @@ -174,21 +192,26 @@ function hasUpstreamOpenShellGatewayUserService( export function hasNemoclawOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { if ((opts.platform ?? process.platform) !== "linux") return false; + const env = opts.env ?? process.env; const existsSync = opts.existsSync ?? fs.existsSync; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(opts.home); + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); return ( - existsSync(servicePath) && isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, opts) + existsSync(servicePath) && + isNemoclawManagedOpenShellGatewayUserServiceUnit(servicePath, { + readFileSync: opts.readFileSync, + }) ); } function resolveOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): OpenShellGatewayUserServiceTarget | null { if ((opts.platform ?? process.platform) !== "linux") return null; @@ -200,8 +223,9 @@ function resolveOpenShellGatewayUserService( }; } if (hasNemoclawOpenShellGatewayUserService(opts)) { - const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const env = opts.env ?? process.env; + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); return { serviceName: OPENSHELL_GATEWAY_USER_SERVICE, trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), @@ -214,7 +238,7 @@ function resolveOpenShellGatewayUserService( export function hasOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "existsSync" | "home" | "platform" | "readFileSync" + "env" | "existsSync" | "home" | "platform" | "readFileSync" > = {}, ): boolean { return resolveOpenShellGatewayUserService(opts) !== null; @@ -357,11 +381,14 @@ export function buildNemoclawOpenShellGatewayUserService(gatewayBin: string): st "[Unit]", "Description=OpenShell Gateway", "Documentation=https://github.com/NVIDIA/OpenShell", + "After=default.target", "", "[Service]", "Type=simple", "StateDirectory=openshell/gateway", + "Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls", "EnvironmentFile=-%E/openshell/gateway.env", + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, `ExecStart=${gatewayBin}`, "Restart=on-failure", "RestartSec=5s", @@ -379,8 +406,8 @@ export function installNemoclawOpenShellGatewayUserService( ): InstallNemoclawOpenShellGatewayUserServiceResult { const platform = opts.platform ?? process.platform; if (platform !== "linux") return { installed: false, reason: "not a Linux host" }; - const home = opts.home ?? os.homedir(); - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const home = effectiveHome(opts.home, opts.env); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, opts.env); const existsSync = opts.existsSync ?? fs.existsSync; if (hasUpstreamOpenShellGatewayUserService(opts)) { if ( @@ -463,9 +490,7 @@ export function installNemoclawOpenShellGatewayUserService( function isBenignGatewayUserServiceInstallSkip(reason: string | undefined): boolean { return ( - reason === "not a Linux host" || - reason === "upstream OpenShell gateway service is installed" || - reason === "OpenShell gateway binary not found" + reason === "not a Linux host" || reason === "upstream OpenShell gateway service is installed" ); } @@ -492,10 +517,13 @@ export function startOpenShellGatewayUserService( if (platform !== "linux") { return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; } + const env = opts.env ?? process.env; + const home = effectiveHome(opts.home, opts.env); const existsSync = opts.existsSync ?? fs.existsSync; const service = resolveOpenShellGatewayUserService({ + env, existsSync, - home: opts.home, + home, platform, readFileSync: opts.readFileSync, }); @@ -508,7 +536,6 @@ export function startOpenShellGatewayUserService( }; } - const env = opts.env ?? process.env; const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); if (!commandExists("systemctl")) { return { @@ -571,6 +598,21 @@ export function startOpenShellGatewayUserService( } } + const active = runSystemctlUser(["is-active", "--quiet", service.serviceName], { + env, + spawnSyncImpl, + }); + if (!active.ok) { + const reason = `systemctl --user is-active --quiet ${service.serviceName} failed: ${active.reason}`; + return { + attempted: true, + fallbackAllowed: userManagerLooksUnavailable(active.reason ?? ""), + reason, + serviceName: service.serviceName, + started: false, + }; + } + return { attempted: true, fallbackAllowed: false, @@ -628,18 +670,28 @@ export async function startPackageManagedDockerDriverGateway({ const waitOptions = createGatewayHealthWaitOptions(pollCount, pollInterval, now, (ms) => sleepSecondsImpl(ms / 1000), ); + let lastReadiness = { + cliHealthy: false, + grpcHealthy: false, + registered: false, + }; const healthy = waitOptions !== null && (await waitUntilAsync(async () => { - if (!registerDockerDriverGatewayEndpoint()) return false; + const registered = registerDockerDriverGatewayEndpoint(); + if (!registered) { + lastReadiness = { cliHealthy: false, grpcHealthy: false, registered }; + return false; + } const status = runCaptureOpenshell(["status"], { ignoreError: true }); const namedInfo = runCaptureOpenshell(["gateway", "info", "-g", gatewayName], { ignoreError: true, }); const currentInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - return ( - isGatewayHealthy(status, namedInfo, currentInfo) && (await isDockerDriverGatewayReady()) - ); + const cliHealthy = isGatewayHealthy(status, namedInfo, currentInfo); + const grpcHealthy = await isDockerDriverGatewayReady(); + lastReadiness = { cliHealthy, grpcHealthy, registered }; + return cliHealthy || grpcHealthy; }, waitOptions)); if (healthy) { clearDockerDriverGatewayRuntimeFiles(); @@ -655,6 +707,9 @@ export async function startPackageManagedDockerDriverGateway({ pollInterval, )}.`; console.error(` ${message}`); + console.error( + ` Last readiness check: endpoint registered=${lastReadiness.registered ? "yes" : "no"}, OpenShell CLI health=${lastReadiness.cliHealthy ? "yes" : "no"}, direct gRPC health=${lastReadiness.grpcHealthy ? "yes" : "no"}.`, + ); console.error(" Check: systemctl --user status openshell-gateway"); if (exitOnFailure) process.exit(1); throw new Error(message); diff --git a/src/lib/onboard/gateway-binding.test.ts b/src/lib/onboard/gateway-binding.test.ts index b2ec0797d7a..ad7094d037e 100644 --- a/src/lib/onboard/gateway-binding.test.ts +++ b/src/lib/onboard/gateway-binding.test.ts @@ -60,6 +60,7 @@ describe("dynamic gateway runtime helpers", () => { expect(probeDockerDriverGatewayHttpReady).toHaveBeenLastCalledWith( undefined, "http://127.0.0.1:8080/openshell.v1.OpenShell/Health", + undefined, ); expect(probeGatewayTcpReady).toHaveBeenLastCalledWith(8080, 250); expect(getGatewayClusterImageDrift).toHaveBeenLastCalledWith({ gatewayName: "nemoclaw" }); @@ -78,6 +79,14 @@ describe("dynamic gateway runtime helpers", () => { expect(getGatewayClusterImageDrift).toHaveBeenLastCalledWith({ gatewayName: "nemoclaw-8081", }); + + const env = { OPENSHELL_LOCAL_TLS_DIR: "/tmp/nemoclaw-test-tls" }; + await helpers.isDockerDriverGatewayHttpReady(25, undefined, env); + expect(probeDockerDriverGatewayHttpReady).toHaveBeenLastCalledWith( + 25, + "http://127.0.0.1:8081/openshell.v1.OpenShell/Health", + env, + ); }); it("preserves explicit probe URLs and injects the bound default wait probe", async () => { diff --git a/src/lib/onboard/gateway-binding.ts b/src/lib/onboard/gateway-binding.ts index f387a47dee9..de3a43ace7d 100644 --- a/src/lib/onboard/gateway-binding.ts +++ b/src/lib/onboard/gateway-binding.ts @@ -256,11 +256,16 @@ export function createDynamicGatewayRuntimeHelpers(deps: DynamicGatewayRuntimeDe const targetUrl = url ?? `${deps.getDockerDriverGatewayEndpoint(deps.getGatewayPort())}/`; return deps.probeGatewayHttpReady(timeoutMs, targetUrl, method, signal); }; - const isDockerDriverGatewayHttpReady = (timeoutMs?: number, url?: string) => + const isDockerDriverGatewayHttpReady = ( + timeoutMs?: number, + url?: string, + env?: NodeJS.ProcessEnv, + ) => deps.probeDockerDriverGatewayHttpReady( timeoutMs, url ?? `${deps.getDockerDriverGatewayEndpoint(deps.getGatewayPort())}/openshell.v1.OpenShell/Health`, + env, ); const waitForGatewayHttpReady = ( opts: import("./gateway-http-readiness").WaitForGatewayHttpReadyOpts = {}, diff --git a/src/lib/onboard/gateway-http-readiness.test.ts b/src/lib/onboard/gateway-http-readiness.test.ts index cd94c943834..72ef284ecb0 100644 --- a/src/lib/onboard/gateway-http-readiness.test.ts +++ b/src/lib/onboard/gateway-http-readiness.test.ts @@ -2,11 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import http from "node:http"; +import fs from "node:fs"; import type { AddressInfo } from "node:net"; +import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; -import { isGatewayHttpReady } from "./gateway-http-readiness"; +import { isDockerDriverGatewayHttpReady, isGatewayHttpReady } from "./gateway-http-readiness"; const servers: http.Server[] = []; @@ -84,3 +86,27 @@ describe("isGatewayHttpReady abort handling", () => { await expect(probe).resolves.toBe(false); }); }); + +describe("isDockerDriverGatewayHttpReady TLS env", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("uses the supplied gateway env when loading Docker-driver mTLS client files", async () => { + const tlsDir = path.join("/tmp", "nemoclaw-probe-tls"); + const readPaths: string[] = []; + const readFileSync = vi.spyOn(fs, "readFileSync").mockImplementation((filePath) => { + readPaths.push(String(filePath)); + throw new Error("missing test TLS material"); + }); + + await expect( + isDockerDriverGatewayHttpReady(1, "https://127.0.0.1:1/openshell.v1.OpenShell/Health", { + OPENSHELL_LOCAL_TLS_DIR: tlsDir, + }), + ).resolves.toBe(false); + + expect(readFileSync).toHaveBeenCalled(); + expect(readPaths[0]).toBe(path.join(tlsDir, "ca.crt")); + }); +}); diff --git a/src/lib/onboard/gateway-http-readiness.ts b/src/lib/onboard/gateway-http-readiness.ts index edf27a001f6..3d3ea9a0fa7 100644 --- a/src/lib/onboard/gateway-http-readiness.ts +++ b/src/lib/onboard/gateway-http-readiness.ts @@ -124,17 +124,19 @@ function isGatewayHttpReadyImpl( export function isDockerDriverGatewayHttpReady( timeoutMs = ISGATEWAY_HTTP_READY_DEFAULT_TIMEOUT_MS, url = `${getGatewayHttpsEndpoint(GATEWAY_PORT)}/openshell.v1.OpenShell/Health`, + env: NodeJS.ProcessEnv = process.env, ): Promise { return withTraceSpan( "nemoclaw.gateway.docker_driver_http_probe", { timeout_ms: timeoutMs, url }, - () => isDockerDriverGatewayHttpReadyImpl(timeoutMs, url), + () => isDockerDriverGatewayHttpReadyImpl(timeoutMs, url, env), ); } function isDockerDriverGatewayHttpReadyImpl( timeoutMs = ISGATEWAY_HTTP_READY_DEFAULT_TIMEOUT_MS, url = `${getGatewayHttpsEndpoint(GATEWAY_PORT)}/openshell.v1.OpenShell/Health`, + env: NodeJS.ProcessEnv = process.env, ): Promise { const effectiveTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 @@ -187,7 +189,7 @@ function isDockerDriverGatewayHttpReadyImpl( try { const origin = `${parsed.protocol}//${parsed.host}`; - const connectOptions = dockerDriverGatewayHttp2ConnectOptions(parsed); + const connectOptions = dockerDriverGatewayHttp2ConnectOptions(parsed, env); if (parsed.protocol === "https:" && !connectOptions) return settle(false); client = http2.connect(origin, connectOptions); client.on("error", () => settle(false)); @@ -224,9 +226,10 @@ function isDockerDriverGatewayHttpReadyImpl( function dockerDriverGatewayHttp2ConnectOptions( parsed: URL, + env: NodeJS.ProcessEnv = process.env, ): http2.SecureClientSessionOptions | undefined { if (parsed.protocol !== "https:") return undefined; - const localTlsDir = process.env.OPENSHELL_LOCAL_TLS_DIR; + const localTlsDir = env.OPENSHELL_LOCAL_TLS_DIR; if (!localTlsDir) return undefined; try { return { diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 3202ffd6893..1f9c71505c8 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -50,12 +50,73 @@ describe("install.sh OpenShell gateway service", () => { const unit = fs.readFileSync(servicePath, "utf-8"); expect(result.status).toBe(0); expect(unit).toContain("# NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"); + expect(unit).toContain("After=default.target"); + expect(unit).toContain("Environment=OPENSHELL_LOCAL_TLS_DIR=%h/.local/state/openshell/tls"); + expect(unit).toContain( + `ExecStartPre=${gatewayBin} generate-certs --output-dir \${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal --server-san localhost --server-san 127.0.0.1`, + ); expect(unit).toContain(`ExecStart=${gatewayBin}`); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } }); + it("reconciles the service when OpenShell already exists in if-missing mode", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); + const eventsPath = path.join(tmp, "events.log"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + 'command_exists() { [[ "$1" == openshell ]]; }', + `spin() { printf 'spin\\n' >>${JSON.stringify(eventsPath)}; return 1; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.readFileSync(eventsPath, "utf-8")).toBe("prefer\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("uses absolute XDG_CONFIG_HOME for the Linux user service path", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const configHome = path.join(tmp, "xdg-config"); + const gatewayBin = path.join(tmp, ".local", "bin", "openshell-gateway"); + const servicePath = path.join(configHome, "systemd", "user", "openshell-gateway.service"); + fs.mkdirSync(path.dirname(gatewayBin), { recursive: true }); + writeExecutable(gatewayBin, "#!/usr/bin/env bash\nexit 0\n"); + + try { + const result = runInstallHelper( + tmp, + [ + "upstream_openshell_gateway_user_service_installed() { return 1; }", + `resolve_openshell_gateway_bin_for_service() { printf '%s\\n' ${JSON.stringify(gatewayBin)}; }`, + "install_nemoclaw_openshell_gateway_user_service", + ].join("\n"), + { XDG_CONFIG_HOME: configHome }, + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); + expect(fs.existsSync(path.join(tmp, ".config", "systemd", "user"))).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("skips service staging for relative gateway binary paths", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); const servicePath = path.join(tmp, ".config", "systemd", "user", "openshell-gateway.service"); From 3ccb69437a268fd6d45bdb46f786ad1a77a7bee4 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 18:42:53 +0530 Subject: [PATCH 18/24] fix(uninstall): remove xdg openshell gateway config --- .../run-plan-gateway-service.test.ts | 41 +++++++++++-------- src/lib/actions/uninstall/run-plan.ts | 16 +++++--- src/lib/onboard.ts | 4 +- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 755d3a338b7..060449f808b 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -8,6 +8,7 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { + getOpenShellUserConfigHome, getNemoclawOpenShellGatewayUserServicePath, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER, OPENSHELL_GATEWAY_USER_SERVICE, @@ -19,8 +20,8 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } -function writeManagedService(home: string): string { - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); +function writeManagedService(home: string, env?: NodeJS.ProcessEnv): string { + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); fs.mkdirSync(path.dirname(servicePath), { recursive: true }); fs.writeFileSync( servicePath, @@ -35,8 +36,8 @@ function writeManagedService(home: string): string { return servicePath; } -function writeGatewayEnv(home: string): string { - const envPath = path.join(home, ".config", "openshell", "gateway.env"); +function writeGatewayEnv(home: string, env?: NodeJS.ProcessEnv): string { + const envPath = path.join(getOpenShellUserConfigHome(home, env), "openshell", "gateway.env"); fs.mkdirSync(path.dirname(envPath), { recursive: true }); fs.writeFileSync(envPath, "OPENSHELL_SERVER_PORT=8080\n"); return envPath; @@ -44,9 +45,13 @@ function writeGatewayEnv(home: string): string { describe("uninstall OpenShell gateway user service", () => { it("keeps OpenShell service and host gateway process when OpenShell is kept", () => { - const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const servicePath = writeManagedService(tmpHome); - const envPath = writeGatewayEnv(tmpHome); + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const tmpHome = path.join(tmpRoot, "home"); + const xdgConfigHome = path.join(tmpRoot, "xdg-config"); + fs.mkdirSync(tmpHome, { recursive: true }); + const env = { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; + const servicePath = writeManagedService(tmpHome, env); + const envPath = writeGatewayEnv(tmpHome, env); const run = vi.fn((_command: string, _args: string[]) => ok()); try { @@ -54,8 +59,8 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: true }, { commandExists: () => true, - env: { HOME: tmpHome } as NodeJS.ProcessEnv, - existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + env, + existsSync: (target) => String(target).startsWith(tmpRoot) && fs.existsSync(target), isTty: false, platform: "linux", rmSync: fs.rmSync, @@ -72,14 +77,18 @@ describe("uninstall OpenShell gateway user service", () => { ); expect(run.mock.calls.some(([command]) => command === "pgrep")).toBe(false); } finally { - fs.rmSync(tmpHome, { recursive: true, force: true }); + fs.rmSync(tmpRoot, { recursive: true, force: true }); } }); it("removes the NemoClaw-managed Linux user service on full uninstall", () => { - const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); - const servicePath = writeManagedService(tmpHome); - const envPath = writeGatewayEnv(tmpHome); + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-gateway-service-")); + const tmpHome = path.join(tmpRoot, "home"); + const xdgConfigHome = path.join(tmpRoot, "xdg-config"); + fs.mkdirSync(tmpHome, { recursive: true }); + const env = { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; + const servicePath = writeManagedService(tmpHome, env); + const envPath = writeGatewayEnv(tmpHome, env); const runCalls: string[][] = []; try { @@ -87,8 +96,8 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command === "systemctl", - env: { HOME: tmpHome } as NodeJS.ProcessEnv, - existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), + env, + existsSync: (target) => String(target).startsWith(tmpRoot) && fs.existsSync(target), isTty: false, platform: "linux", rmSync: fs.rmSync, @@ -111,7 +120,7 @@ describe("uninstall OpenShell gateway user service", () => { OPENSHELL_GATEWAY_USER_SERVICE, ]); } finally { - fs.rmSync(tmpHome, { recursive: true, force: true }); + fs.rmSync(tmpRoot, { recursive: true, force: true }); } }); diff --git a/src/lib/actions/uninstall/run-plan.ts b/src/lib/actions/uninstall/run-plan.ts index 498a77accef..4a4c0ac0531 100644 --- a/src/lib/actions/uninstall/run-plan.ts +++ b/src/lib/actions/uninstall/run-plan.ts @@ -24,6 +24,7 @@ import { } from "../../domain/uninstall/paths"; import { buildUninstallPlan, type UninstallPlan } from "../../domain/uninstall/plan"; import { + getOpenShellUserConfigHome, getNemoclawOpenShellGatewayUserServicePath, NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE, OPENSHELL_GATEWAY_USER_SERVICE, @@ -1037,12 +1038,15 @@ export function buildRunPlan( ): { paths: UninstallPaths; plan: UninstallPlan } { const env = { ...process.env, ...(deps.env ?? {}) }; const home = env.HOME || os.homedir(); - const paths = defaultUninstallPaths({ - home, - repoRoot: path.resolve(__dirname, "..", "..", ".."), - tmpDir: env.TMPDIR, - xdgBinHome: env.XDG_BIN_HOME, - }); + const paths = { + ...defaultUninstallPaths({ + home, + repoRoot: path.resolve(__dirname, "..", "..", ".."), + tmpDir: env.TMPDIR, + xdgBinHome: env.XDG_BIN_HOME, + }), + openshellConfigDir: path.join(getOpenShellUserConfigHome(home, env), "openshell"), + }; const plan = buildUninstallPlan(paths, { deleteModels: options.deleteModels, gatewayName: options.gatewayName, diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 18fda5d204e..230e7ce1597 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2010,9 +2010,7 @@ async function startDockerDriverGateway({ ignoreError: true, }); const activeGatewayInfo = runCaptureOpenshell(["gateway", "info"], { ignoreError: true }); - // Port availability and listener enumeration are not atomic. The cutover - // rechecks health before adoption, reaps every observed duplicate, and - // requires a fresh strict bind proof after reaping before launch. + // Cutover rechecks health, reaps duplicates, and requires strict bind proof before launch. const portListenerScan = getDockerDriverGatewayPortListenerScan( await checkGatewayPortAvailable(), { gatewayBin: identityGatewayBin }, From 977c9295b8f2edddad555e197791f9635e42a909 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 18:55:26 +0530 Subject: [PATCH 19/24] test(onboard): isolate gateway xdg env tests --- .../run-plan-gateway-service.test.ts | 29 ++++++++++++------- .../docker-driver-gateway-env-service.test.ts | 11 ++++++- .../onboard/docker-driver-gateway-env.test.ts | 11 +++++-- .../docker-driver-gateway-service.test.ts | 22 ++++++++++---- 4 files changed, 53 insertions(+), 20 deletions(-) diff --git a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts index 060449f808b..636534573fe 100644 --- a/src/lib/actions/uninstall/run-plan-gateway-service.test.ts +++ b/src/lib/actions/uninstall/run-plan-gateway-service.test.ts @@ -20,6 +20,10 @@ function ok(stdout = ""): RunResult { return { status: 0, stdout, stderr: "" }; } +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + function writeManagedService(home: string, env?: NodeJS.ProcessEnv): string { const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); fs.mkdirSync(path.dirname(servicePath), { recursive: true }); @@ -49,7 +53,7 @@ describe("uninstall OpenShell gateway user service", () => { const tmpHome = path.join(tmpRoot, "home"); const xdgConfigHome = path.join(tmpRoot, "xdg-config"); fs.mkdirSync(tmpHome, { recursive: true }); - const env = { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; + const env = homeEnv(tmpHome, xdgConfigHome); const servicePath = writeManagedService(tmpHome, env); const envPath = writeGatewayEnv(tmpHome, env); const run = vi.fn((_command: string, _args: string[]) => ok()); @@ -86,7 +90,7 @@ describe("uninstall OpenShell gateway user service", () => { const tmpHome = path.join(tmpRoot, "home"); const xdgConfigHome = path.join(tmpRoot, "xdg-config"); fs.mkdirSync(tmpHome, { recursive: true }); - const env = { HOME: tmpHome, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; + const env = homeEnv(tmpHome, xdgConfigHome); const servicePath = writeManagedService(tmpHome, env); const envPath = writeGatewayEnv(tmpHome, env); const runCalls: string[][] = []; @@ -134,7 +138,7 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command === "systemctl", - env: { HOME: tmpHome } as NodeJS.ProcessEnv, + env: homeEnv(tmpHome), error: (line) => errors.push(line), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, @@ -180,7 +184,7 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, - env: { HOME: tmpHome } as NodeJS.ProcessEnv, + env: homeEnv(tmpHome), error: (line) => errors.push(line), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, @@ -215,15 +219,18 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command === "systemctl", - env: { HOME: tmpHome } as NodeJS.ProcessEnv, + env: homeEnv(tmpHome), error: (line) => errors.push(line), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, platform: "linux", - rmSync: vi.fn((target: fs.PathLike) => { - if (String(target) === servicePath) throw new Error("permission denied"); - fs.rmSync(target, { recursive: true, force: true }); - }) as typeof fs.rmSync, + rmSync: vi.fn((target: fs.PathLike) => + String(target) === servicePath + ? (() => { + throw new Error("permission denied"); + })() + : fs.rmSync(target, { recursive: true, force: true }), + ) as typeof fs.rmSync, run: vi.fn(() => ok()), runDocker: () => ok(""), }, @@ -250,7 +257,7 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: (command) => command === "systemctl", - env: { HOME: tmpHome } as NodeJS.ProcessEnv, + env: homeEnv(tmpHome), error: (line) => errors.push(line), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, @@ -285,7 +292,7 @@ describe("uninstall OpenShell gateway user service", () => { { assumeYes: true, deleteModels: false, keepOpenShell: false }, { commandExists: () => true, - env: { HOME: tmpHome } as NodeJS.ProcessEnv, + env: homeEnv(tmpHome), existsSync: (target) => String(target).startsWith(tmpHome) && fs.existsSync(target), isTty: false, platform: "darwin", diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index ffdedee5f95..4586e7f0786 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -9,9 +9,14 @@ import { describe, expect, it, vi } from "vitest"; import { writeSafeGatewayAuthConfig } from "../../../test/support/docker-driver-gateway-env-test-support"; import { startPackageManagedDockerDriverGatewayWithEnvOverride } from "./docker-driver-gateway-env"; +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("package-managed Docker-driver gateway env service", () => { it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const env = homeEnv(tempHome); const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); const servicePath = path.join( tempHome, @@ -28,6 +33,7 @@ describe("package-managed Docker-driver gateway env service", () => { await expect( startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env, exitOnFailure: false, gatewayBin, gatewayEnv: { @@ -65,6 +71,7 @@ describe("package-managed Docker-driver gateway env service", () => { it("uses one XDG config root for the service unit and gateway env", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); const configHome = path.join(tempHome, "xdg-config"); + const env = homeEnv(tempHome, configHome); const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); const servicePath = path.join(configHome, "systemd", "user", "openshell-gateway.service"); const envFile = path.join(configHome, "openshell", "gateway.env"); @@ -75,7 +82,7 @@ describe("package-managed Docker-driver gateway env service", () => { await expect( startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), - env: { XDG_CONFIG_HOME: configHome }, + env, exitOnFailure: false, gatewayBin, gatewayEnv: { @@ -133,6 +140,7 @@ describe("package-managed Docker-driver gateway env service", () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); const startService = vi.fn(); + const env = homeEnv(tempHome); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); try { for (const key of [ @@ -151,6 +159,7 @@ describe("package-managed Docker-driver gateway env service", () => { expect(() => startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env, exitOnFailure: false, gatewayEnv: { OPENSHELL_BIND_ADDRESS: "127.0.0.1", diff --git a/src/lib/onboard/docker-driver-gateway-env.test.ts b/src/lib/onboard/docker-driver-gateway-env.test.ts index f903e30d99f..02ecccf2f89 100644 --- a/src/lib/onboard/docker-driver-gateway-env.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env.test.ts @@ -14,6 +14,10 @@ import { writeDockerGatewayDebEnvOverride, } from "./docker-driver-gateway-env"; +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("buildDockerDriverGatewayEnv", () => { it("sets Docker-driver gateway networking from NemoClaw configuration", () => { const env = buildDockerDriverGatewayEnv({ @@ -147,7 +151,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); const envFileContent = fs.readFileSync(envFile, "utf-8"); @@ -175,7 +179,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); expect(wrote).toBe(false); @@ -201,7 +205,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { env: { HOME: tempHome }, platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); expect(wrote).toBe(true); @@ -232,6 +236,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { await expect( startPackageManagedDockerDriverGatewayWithEnvOverride({ clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: homeEnv(tempHome), exitOnFailure: false, gatewayEnv, gatewayName: "nemoclaw", diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 2e058c63d9f..ab94a37ce1a 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -56,6 +56,10 @@ function spawnResult(status = 0, stderr = "", stdout = ""): SpawnSyncLikeResult }; } +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("docker-driver-gateway-service", () => { it("detects the upstream OpenShell user service only on Linux", () => { const existsSync = (candidate: string) => @@ -92,12 +96,14 @@ describe("docker-driver-gateway-service", () => { it("ignores stale per-user service units so standalone fallback remains available", () => { const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); const existsSync = vi.fn((candidate: string) => candidate === servicePath); expect( hasOpenShellGatewayUserService({ existsSync, + env, home, platform: "linux", readFileSync: () => `# not ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`, @@ -107,7 +113,8 @@ describe("docker-driver-gateway-service", () => { it("detects and installs a NemoClaw-managed user service on Linux only", () => { const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; const chmodSync = vi.fn(); const mkdirSync = vi.fn(); @@ -116,6 +123,7 @@ describe("docker-driver-gateway-service", () => { expect( installNemoclawOpenShellGatewayUserService({ chmodSync, + env, existsSync: () => false, gatewayBin, home, @@ -141,6 +149,7 @@ describe("docker-driver-gateway-service", () => { expect( hasNemoclawOpenShellGatewayUserService({ existsSync: (candidate) => candidate === servicePath, + env, home, platform: "linux", readFileSync: () => buildNemoclawOpenShellGatewayUserService(gatewayBin), @@ -173,7 +182,8 @@ describe("docker-driver-gateway-service", () => { it("removes a NemoClaw user override when an upstream service exists", () => { const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); const rmSync = vi.fn(); expect( @@ -181,6 +191,7 @@ describe("docker-driver-gateway-service", () => { existsSync: (candidate) => candidate === "/usr/lib/systemd/user/openshell-gateway.service" || candidate === servicePath, + env, gatewayBin: null, home, platform: "linux", @@ -219,7 +230,8 @@ describe("docker-driver-gateway-service", () => { it("restarts the NemoClaw-managed user service after validating its identity", () => { const home = "/home/nvidia"; - const servicePath = getNemoclawOpenShellGatewayUserServicePath(home); + const env = homeEnv(home); + const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); const gatewayBin = "/home/nvidia/.local/bin/openshell-gateway"; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => args.includes("show") @@ -230,7 +242,7 @@ describe("docker-driver-gateway-service", () => { expect( startOpenShellGatewayUserService({ commandExists: (command) => command === "systemctl", - env: {}, + env, existsSync: (candidate) => candidate === servicePath, home, platform: "linux", From 7ae6ef4eb1d9a9bab2e25f6d8f4ce733b80d6349 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 19:11:43 +0530 Subject: [PATCH 20/24] test(onboard): isolate installer gateway xdg paths --- .../docker-driver-gateway-env-deb-override.test.ts | 8 ++++++-- test/install-openshell-gateway-service.test.ts | 1 + 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts index 5b9d79b6a01..10b497107fb 100644 --- a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts @@ -12,6 +12,10 @@ import { writeDockerGatewayDebEnvOverride, } from "./docker-driver-gateway-env"; +function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { + return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; +} + describe("buildDockerGatewayDebEnvFile", () => { it("replaces all managed gateway env keys and preserves unrelated values", () => { const next = buildDockerGatewayDebEnvFile( @@ -114,7 +118,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); const envFileContent = fs.readFileSync(envFile, "utf-8"); @@ -142,7 +146,7 @@ describe("writeDockerGatewayDebEnvOverride", () => { () => ({ OPENSHELL_BIND_ADDRESS: "127.0.0.1", }), - { platform: "linux" }, + { env: homeEnv(tempHome), platform: "linux" }, ); expect(wrote).toBe(false); diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 1f9c71505c8..31afc27dc4b 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -22,6 +22,7 @@ function runInstallHelper(tmp: string, body: string, env: NodeJS.ProcessEnv = {} ...process.env, HOME: tmp, PATH: TEST_SYSTEM_PATH, + XDG_CONFIG_HOME: "", NEMOCLAW_REPO_ROOT: path.dirname(INSTALLER), ...env, }, From 5abb9b9b1535b3f443842fe897bb8db77ed4bcc7 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 20:49:47 +0530 Subject: [PATCH 21/24] fix(onboard): use openshell homebrew service on macos --- ci/platform-matrix.json | 6 +- docs/get-started/prerequisites.mdx | 2 +- docs/reference/architecture.mdx | 3 +- docs/reference/commands.mdx | 4 +- docs/reference/platform-support.mdx | 4 +- docs/reference/troubleshooting.mdx | 13 +- scripts/check-installer-hash.sh | 35 ++- scripts/checks/extract-installer-pins.mts | 20 +- scripts/install-openshell.sh | 138 +++++++++- scripts/install.sh | 16 +- .../docker-driver-gateway-service.test.ts | 68 ++++- .../onboard/docker-driver-gateway-service.ts | 172 ++++++++++-- src/lib/onboard/openshell-install.ts | 2 +- .../install-openshell-gateway-service.test.ts | 56 ++++ test/install-openshell-version-check.test.ts | 252 +++++++++++------- test/installer-hash-check.test.ts | 65 ++++- 16 files changed, 700 insertions(+), 156 deletions(-) diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index f903e2ffc8f..484c9449c9a 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -1,7 +1,7 @@ { "$comment": "Single source of truth for NemoClaw launch claims and platform support. Covers platforms, inference providers, supported agents, messaging integrations, and deployment paths. Scripts read this to generate README and docs tables. QA/CI update platform/provider rows; the engineering owner reviews other rows. Docs are derived.", "version": "1.1", - "updated": "2026-07-12", + "updated": "2026-07-15", "project_status": { "stage": "alpha", @@ -39,7 +39,7 @@ "status": "caveated", "prd_priority": "P0", "ci_tested": true, - "notes": "Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight." + "notes": "Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight." }, { "name": "DGX Spark", @@ -229,7 +229,7 @@ { "name": "Intel Mac (macOS x86_64)", "status": "unsupported", - "notes": "OpenShell does not publish macOS x86_64 standalone gateway assets. Install hard-fails on x86_64 macOS (`scripts/install-openshell.sh:663`). See issue #954 (closed)." + "notes": "The supported macOS OpenShell Homebrew gateway service path is Apple Silicon only. Install hard-fails on x86_64 macOS. See issue #954 (closed)." }, { "name": "Non-Ubuntu/Debian Linux distros", diff --git a/docs/get-started/prerequisites.mdx b/docs/get-started/prerequisites.mdx index b8b28670bde..678c11f7a55 100644 --- a/docs/get-started/prerequisites.mdx +++ b/docs/get-started/prerequisites.mdx @@ -92,7 +92,7 @@ The table comes from [`ci/platform-matrix.json`](https://github.com/NVIDIA/NemoC | OS | Container runtime | Status | Notes | |----|-------------------|--------|-------| | Linux | Docker | Tested | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | -| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | +| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | | DGX Spark | Docker | Tested | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | Windows WSL2 | Docker Desktop (WSL backend) | Tested with limitations | Requires WSL2 with Docker Desktop backend. | {/* platform-matrix:end */} diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 1013cd55cc8..d1207e37f5a 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -91,7 +91,8 @@ Arbitrary per-user units, partial units, and user-manager or bus outages do not If NemoClaw cannot write or remove its marked user unit, it reports the filesystem failure and keeps the standalone fallback available. That compatibility fallback remains until supported upgrade paths no longer include pre-service OpenShell installs and the service-backed handoff has direct nightly coverage. On Apple Silicon macOS, the upstream OpenShell daemon model is the Homebrew service. -NemoClaw does not install or remove that Homebrew service; tarball-installed OpenShell binaries continue to use the standalone Docker-driver gateway process. +The installer installs OpenShell through the upstream Homebrew formula, and onboard restarts the `openshell` Homebrew service before checking gateway health. +If the Homebrew formula or service is unavailable, NemoClaw can still use the standalone Docker-driver gateway process as a compatibility fallback. In either case, NemoClaw creates the sandbox as a Docker container. In both Docker-driver modes, the sandbox is a Docker container, not a Kubernetes pod. Entrypoint supervisors create the in-container `/tmp/nemoclaw-gateway-local` marker only when they actually launch an in-container gateway, and they normally keep it present while that supervisor is active. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 4ed4b858d44..a207ce4998d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3429,8 +3429,8 @@ Set them before running `$$nemoclaw onboard`. | `NEMOCLAW_SANDBOX_BASE_LOCAL_BUILD` | unset or `auto` (default); `1`, `true`, `yes`, or `on` to enable; `0`, `false`, `no`, or `off` to disable | Controls whether base-image resolution may build a compatible image locally. The default allows builds during normal CLI runs and disables them when `NODE_ENV=test` or `VITEST=true`. When source inputs or a missing/incompatible release-version base require a fresh build, disabling local builds makes resolution fail instead of using an unproven image. | | `NEMOCLAW_DOCKER_GPU_PATCH` | unset, `auto`, `fallback`, `1`, or `0`; other legacy nonzero values remain accepted through `v0.0.x` and will be removed in `v0.1.0` | Selects Linux Docker-driver GPU routing. Unset, `auto`, or `0` uses native OpenShell GPU injection on ordinary native Linux. `fallback` explicitly opts into one native attempt followed by one bounded compatibility retry when trusted host evidence identifies a GPU-routing failure. `1` and legacy nonzero values select the compatibility patch from the outset. Docker Desktop WSL and Jetson/Tegra use the compatibility path by default; Docker Desktop WSL ignores `0`, while Jetson/Tegra accepts `0` only as a troubleshooting override that bypasses device-group propagation. | | `NEMOCLAW_OPENSHELL_GATEWAY_CONTAINER_PATCH` | `1` to enable; disabled by default | This setting explicitly opts into the Linux gateway compatibility container for an older host ABI or a diagnostic run; use it only on a trusted local host because it uses host networking and mounts the Docker socket read-only even though the socket still exposes the privileged Docker API; prefer OpenShell 0.0.72's directly supported glibc 2.28+ path; see the [OpenShell 0.0.72 compatibility review](/user-guide/openclaw/security/openshell-0.0.72-compatibility-review#source-of-truth-boundaries) for details. | -| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Linux Docker-driver gateway startup. The marked user service accepts only NemoClaw's trusted install paths (`~/.local/bin/openshell-gateway`, `/usr/local/bin/openshell-gateway`, or `/usr/bin/openshell-gateway`); other absolute paths use the standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | -| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by Linux Docker-driver gateway startup, including the marked user service environment and standalone fallback. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_GATEWAY_BIN` | path | Advanced override for the `openshell-gateway` binary used by Docker-driver gateway startup when NemoClaw stages its Linux marked user service or uses the standalone fallback. The marked user service accepts only NemoClaw's trusted install paths (`~/.local/bin/openshell-gateway`, `/usr/local/bin/openshell-gateway`, or `/usr/bin/openshell-gateway`); other absolute paths use the standalone fallback. The macOS Homebrew service uses the Homebrew formula's gateway binary. Defaults to the binary next to `openshell`, then common install paths. | +| `NEMOCLAW_OPENSHELL_SANDBOX_BIN` | path | Advanced override for the `openshell-sandbox` binary used by Linux Docker-driver gateway startup, including the marked user service environment and standalone fallback. The macOS Homebrew service uses the Homebrew formula's driver layout. Defaults to the binary next to `openshell`, then common install paths. | | `NEMOCLAW_OPENSHELL_GATEWAY_STATE_DIR` | path | Advanced override for the Linux Docker-driver gateway SQLite state directory and standalone-fallback PID file. Defaults to `~/.local/state/nemoclaw/openshell-docker-gateway`. | | `NEMOCLAW_AUTO_FIX_FIREWALL` | `1` to enable | Opts in to automatic UFW remediation when Linux Docker-driver sandbox containers cannot reach the host gateway after a proven TCP failure. NemoClaw runs `sudo -n` only, validates the narrow Docker bridge subnet → gateway IP:port rule before invoking UFW, re-probes after applying it, and otherwise falls back to the printed manual command. | diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index e02d2cab64b..12ba49c6ea2 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -79,7 +79,7 @@ For the onboarding-time supported set without deferred rows, refer to [Prerequis | OS | Container runtime | Status | PRD priority | CI | Notes | |----|-------------------|--------|--------------|----|-------| | Linux | Docker | Tested | P0 | Yes | Primary tested path. Ubuntu 24.04 has host-level onboarding validation. A digest-pinned Ubuntu 26.04 userspace lane builds the CLI and runs preflight, installer, and platform contracts on eligible main pushes; Docker-host, AppArmor, Landlock, and live onboarding validation on 26.04 remain pending. Other distros (Ubuntu 22.04, Fedora, Rocky, Alma, NixOS, Arch) may work but are not validated. | -| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | P0 | Yes | Start the container runtime (Colima or Docker Desktop) before running the installer. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | +| macOS (Apple Silicon) | Colima, Docker Desktop | Tested with limitations | P0 | Yes | Start the container runtime (Colima or Docker Desktop) before running the installer. OpenShell is installed through Homebrew and the gateway should appear in `brew services list` as `openshell`. Homebrew Colima users must install both Colima and the Docker CLI (`brew install colima docker`) before `docker info` can work. Xcode Command Line Tools (`xcode-select --install`) are typically required for Node native modules during install. NemoClaw recommends them but does not enforce them during preflight. | | DGX Spark | Docker | Tested | P1 | Yes | Use the standard installer and `$$nemoclaw onboard`. For an end-to-end walkthrough with local inference, see the [NVIDIA Spark playbook](https://build.nvidia.com/spark/nemoclaw). | | Windows WSL2 | Docker Desktop (WSL backend) | Tested with limitations | P1 | No | Requires WSL2 with Docker Desktop backend. | | DGX Station | Docker | Deferred | P1 | No | The PRD marks this platform as P1. Workstation form-factor with NVIDIA GPUs and the same Docker + NVIDIA Container Toolkit + CDI requirements as DGX Spark. Onboard path not yet validated end-to-end on the hardware; vLLM defaults to `deepseek-ai/DeepSeek-V4-Flash` for this host class and will move out of `deferred` once the hardware run is signed off. | @@ -162,7 +162,7 @@ They are listed here so launch material, sales conversations, and support triage | Item | Status | Why | |------|--------|-----| | Podman / other container runtimes | Unsupported | Onboard surfaces an explicit unsupported-runtime error for Podman (`src/lib/onboard/fatal-runtime-preflight.ts` prints the rejection; `src/lib/onboard/preflight.ts` flags the unsupported runtime upstream). Only Docker Engine, Docker Desktop, and Colima are supported. See issue #420 (closed). | -| Intel Mac (macOS x86_64) | Unsupported | OpenShell does not publish macOS x86_64 standalone gateway assets. Install hard-fails on x86_64 macOS (`scripts/install-openshell.sh:663`). See issue #954 (closed). | +| Intel Mac (macOS x86_64) | Unsupported | The supported macOS OpenShell Homebrew gateway service path is Apple Silicon only. Install hard-fails on x86_64 macOS. See issue #954 (closed). | | Non-Ubuntu/Debian Linux distros | Unsupported | Installer assumes `apt-get`. Fedora/Rocky/Alma/Arch/NixOS are not validated and the installer's package-manager probes do not cover them. See open issue #899 (Fedora hang). | | Native Kubernetes or OpenShift deployments | Unsupported | NemoClaw runs the sandbox as a Docker container, not a Kubernetes pod. The default Docker-driver topology does not embed k3s. Operator-managed K8s/OpenShift deployments are out of scope; see issue #407 (community OpenShift through agent-sandbox CRD). | | Air-gapped / offline installs | Unsupported | Onboard assumes network reachability for package fetches, container pulls, and provider validation. See open issues #4872 and #2218 (production-deployment epic covering air-gapped support, China network guidance, multi-host topology). | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 4be9151c12d..920f61c1b2b 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -848,9 +848,16 @@ Follow these steps to reconnect. - **Linux:** start Docker if it is not already running (`sudo systemctl start docker`) - **macOS:** open Docker Desktop or start Colima (`colima start`) -1. Check the managed OpenShell gateway service on Linux tarball installs. +1. Check the managed OpenShell gateway service. - NemoClaw installs a marked user `openshell-gateway.service` on Linux tarball installs. + On Apple Silicon macOS, OpenShell is installed through Homebrew and the gateway is a Homebrew service: + + ```bash + brew services list + brew services restart openshell + ``` + + On Linux tarball installs, NemoClaw installs a marked user `openshell-gateway.service`. The unit is written under `$XDG_CONFIG_HOME/systemd/user` when `XDG_CONFIG_HOME` is absolute, otherwise under `~/.config/systemd/user`. The service generates the local OpenShell mTLS bundle before starting and then reads NemoClaw's `openshell/gateway.env` overrides. The systemd user manager starts it after reboot, or at the next user session when lingering is not enabled. @@ -861,7 +868,7 @@ Follow these steps to reconnect. systemctl --user restart openshell-gateway ``` - On macOS, non-systemd Linux hosts, or hosts where the user service cannot be reached, continue with the NemoClaw recovery step below. + On non-systemd Linux hosts or hosts where the user service cannot be reached, continue with the NemoClaw recovery step below. 1. Check sandbox state. diff --git a/scripts/check-installer-hash.sh b/scripts/check-installer-hash.sh index c26cf106fab..fab5adc7169 100755 --- a/scripts/check-installer-hash.sh +++ b/scripts/check-installer-hash.sh @@ -6,7 +6,7 @@ # still match the immutable upstream checksum manifests. # # Checked artifacts: -# 1. OpenShell archives — scripts/install-openshell.sh release-asset table +# 1. OpenShell archives/formula — scripts/install-openshell.sh release-asset tables # 2. Brev OpenShell CLI — scripts/brev-launchable-ci-cpu.sh release-asset table # # Usage: @@ -85,7 +85,7 @@ sha256_file() { check_openshell_release_assets() { local installer="${REPO_ROOT}/scripts/install-openshell.sh" local brev_installer="${REPO_ROOT}/scripts/brev-launchable-ci-cpu.sh" - local release_base workspace manifests spec manifest expected actual source asset pinned upstream + local release_base workspace manifests spec manifest expected actual source asset pinned upstream formula_asset local matches required_manifest required_matches local pin_records parser_error parser_errors parsed_version release_version="" record_extra local allowlist_entry allowlist_version allowlist_extra @@ -144,8 +144,8 @@ check_openshell_release_assets() { esac done <<<"$pin_records" - if [[ "$count" -ne 8 ]]; then - echo " STALE: expected 8 pinned OpenShell v${release_version:-unknown} assets, found ${count}." + if [[ "$count" -ne 9 ]]; then + echo " STALE: expected 9 pinned OpenShell v${release_version:-unknown} assets, found ${count}." failures=$((failures + 1)) fi if [[ "$brev_count" -ne 2 ]]; then @@ -221,6 +221,29 @@ check_openshell_release_assets() { done while IFS=$'\t' read -r parsed_version source asset pinned record_extra; do + if [[ "$asset" == "openshell.rb" ]]; then + formula_asset="${workspace}/${asset}" + if ! fetch_file "${release_base}/${asset}" "$formula_asset"; then + echo " STALE: unable to download ${source} ${asset}." + failures=$((failures + 1)) + continue + fi + if ! actual=$(sha256_file "$formula_asset"); then + echo " STALE: unable to hash ${source} ${asset}." + failures=$((failures + 1)) + continue + fi + if [[ "$actual" == "$pinned" ]]; then + published_count=$((published_count + 1)) + echo " OK: ${source} ${asset} (${pinned})" + else + echo " STALE: ${source} ${asset} digest does not match the pinned v${release_version} release asset." + echo " pinned: ${pinned}" + echo " upstream: ${actual}" + failures=$((failures + 1)) + fi + continue + fi matches=$(awk -v asset="$asset" '$2 == asset { count++ } END { print count + 0 }' "$manifests") upstream=$(awk -v asset="$asset" '$2 == asset { print $1; exit }' "$manifests") if [[ "$matches" -eq 1 && "$pinned" == "$upstream" ]]; then @@ -235,8 +258,8 @@ check_openshell_release_assets() { fi done <<<"$pin_records" - if [[ "$published_count" -ne 10 ]]; then - echo " STALE: expected all 10 pinned asset references in the v${release_version} checksum manifests, matched ${published_count}." + if [[ "$published_count" -ne 11 ]]; then + echo " STALE: expected all 11 pinned asset references for v${release_version}, matched ${published_count}." failures=$((failures + 1)) fi return "$failures" diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 2e897b4bca4..cd1e31742e6 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -48,7 +48,7 @@ const MAX_INSTALLER_INPUT_BYTES = 1024 * 1024; // release; the later pin PR may then change release data without authorizing // any operational installer change. A mismatch reports the candidate hash. const TRUSTED_INSTALLER_TEMPLATE_SHA256 = - "a101f002bd8e02aa7b38960ddcb76c9fca419bc3766f6870446f6a7e99e14d78"; + "7db8198d4888ed32ee3be8e15e9e215a11cb368f13c19b536496e96cd762c3e1"; const TRUSTED_BREV_TEMPLATE_SHA256 = "c0a4ddf25a02a9fe02b2df53a60942ea887610f04d4ce16a121b6e79a5aeff1a"; const EXPECTED_INSTALLER_ASSETS = [ @@ -61,6 +61,7 @@ const EXPECTED_INSTALLER_ASSETS = [ "openshell-sandbox-x86_64-unknown-linux-gnu.tar.gz", "openshell-sandbox-aarch64-unknown-linux-gnu.tar.gz", ] as const; +const EXPECTED_INSTALLER_FORMULA_ASSETS = ["openshell.rb"] as const; const EXPECTED_BREV_ASSETS = [ "openshell-x86_64-unknown-linux-musl.tar.gz", "openshell-aarch64-unknown-linux-musl.tar.gz", @@ -927,13 +928,22 @@ function runCli(): void { functionName: "openshell_pinned_sha256", sourceLabel: "installer", }); + const installerFormulaPins = extractInstallerPins(installerSource, { + functionName: "openshell_formula_pinned_sha256", + sourceLabel: "installer", + }); const brevPins = extractInstallerPins(brevInstallerSource, { functionName: "openshell_cli_pinned_sha256", sourceLabel: "Brev launchable", }); assertExactAssetSet(installerPins, EXPECTED_INSTALLER_ASSETS, "installer pin table"); + assertExactAssetSet( + installerFormulaPins, + EXPECTED_INSTALLER_FORMULA_ASSETS, + "installer formula pin table", + ); assertExactAssetSet(brevPins, EXPECTED_BREV_ASSETS, "Brev pin table"); - const pins = [...installerPins, ...brevPins]; + const pins = [...installerPins, ...installerFormulaPins, ...brevPins]; const releaseVersions = [...new Set(pins.map((pin) => pin.releaseVersion))].sort(); if (releaseVersions.length !== 1) { fail( @@ -949,7 +959,11 @@ function runCli(): void { } assertTrustedTemplate( installerSource, - ["openshell_pinned_sha256", "pinned_sandbox_build_version"], + [ + "openshell_pinned_sha256", + "openshell_formula_pinned_sha256", + "pinned_sandbox_build_version", + ], [ /^MIN_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, /^MAX_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, diff --git a/scripts/install-openshell.sh b/scripts/install-openshell.sh index 0c0bf559eb6..0fce4de05a9 100755 --- a/scripts/install-openshell.sh +++ b/scripts/install-openshell.sh @@ -82,6 +82,9 @@ if [ "$RESOLVED_CHANNEL" = "dev" ]; then warn "Dev channel install skips SHA-256 verification. Use only in trusted environments." fi +HOMEBREW_TAP="nvidia/openshell" +HOMEBREW_FORMULA_NAME="openshell" + # Honour the TS installer's blueprint-derived env overrides only on the stable # channel — the dev channel installs from the `dev` tag and uses DEV_MIN_VERSION # instead, so a malformed override should not abort a dev install (#3446 review). @@ -175,6 +178,18 @@ openshell_checksum_line() { awk -v asset="$asset" '$2 == asset { print; found=1; exit } END { if (!found) exit 1 }' "$checksum_file" } +openshell_formula_pinned_sha256() { + local release_tag="$1" asset="$2" + case "${release_tag}:${asset}" in + v0.0.72:openshell.rb) + printf '%s\n' "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3" + ;; + *) + return 1 + ;; + esac +} + # A pinned digest authenticates bytes, but it does not make extraction safe. # Every consumed OpenShell archive must contain exactly the one regular binary # selected by its asset name. This rejects absolute/parent paths, extra or @@ -603,6 +618,107 @@ repair_existing_macos_vm_driver() { return 1 } +macos_homebrew_formula_installed() { + [ "$OS" = "Darwin" ] || return 1 + command -v brew >/dev/null 2>&1 || return 1 + brew list --formula "$HOMEBREW_FORMULA_NAME" >/dev/null 2>&1 +} + +restart_macos_homebrew_gateway_service() { + [ "$OS" = "Darwin" ] || return 0 + command -v brew >/dev/null 2>&1 || return 1 + info "restarting OpenShell Homebrew service..." + if brew services restart "$HOMEBREW_FORMULA_NAME"; then + return 0 + fi + warn "could not restart the OpenShell Homebrew service" + info "restart it later with: brew services restart ${HOMEBREW_FORMULA_NAME}" + info "then register it with: openshell gateway add https://127.0.0.1:17670 --local --name openshell" + return 0 +} + +download_openshell_formula() { + local release_tag="$1" output="$2" output_dir + output_dir="$(dirname "$output")" + if command -v gh >/dev/null 2>&1; then + if GH_PROMPT_DISABLED=1 GH_TOKEN="${GH_TOKEN:-${GITHUB_TOKEN:-}}" gh release download "$release_tag" --repo NVIDIA/OpenShell \ + --pattern "openshell.rb" --dir "$output_dir" --clobber 2>/dev/null; then + [ -f "$output" ] && return 0 + fi + warn "gh CLI formula download failed (auth may not be configured) — falling back to curl" + rm -f "$output" + fi + curl -fL -sS "https://github.com/NVIDIA/OpenShell/releases/download/${release_tag}/openshell.rb" \ + -o "$output" +} + +homebrew_formula_path() { + local tap="$1" formula="$2" tap_dir formula_dir + if ! brew tap-info "$tap" >/dev/null 2>&1; then + info "creating local Homebrew tap ${tap}..." >&2 + brew tap-new --no-git "$tap" >/dev/null + fi + + tap_dir="$(brew --repository "$tap" 2>/dev/null || true)" + [ -n "$tap_dir" ] || fail "could not locate Homebrew tap ${tap}" + + formula_dir="${tap_dir}/Formula" + mkdir -p "$formula_dir" + printf '%s/%s.rb\n' "$formula_dir" "$formula" +} + +install_macos_homebrew_formula() { + local tmpdir formula_file tap_formula_file formula_ref expected_sha actual_sha brew_prefix openshell_bin + [ "$OS" = "Darwin" ] || return 1 + [ "$ARCH_LABEL" = "aarch64" ] || fail "OpenShell ${PIN_VERSION} supports the Homebrew gateway service only on Apple Silicon macOS." + command -v brew >/dev/null 2>&1 || fail "Homebrew is required to install the OpenShell macOS gateway service. Install Homebrew and retry." + + tmpdir="$(mktemp -d)" + OPENSHELL_HOMEBREW_FORMULA_TMPDIR="$tmpdir" + trap 'rm -rf "${OPENSHELL_HOMEBREW_FORMULA_TMPDIR:-}"' EXIT + formula_file="${tmpdir}/openshell.rb" + + info "Downloading OpenShell Homebrew formula..." + download_openshell_formula "$RELEASE_TAG" "$formula_file" \ + || fail "failed to download OpenShell Homebrew formula for ${RELEASE_TAG}" + chmod 0644 "$formula_file" + + if [ "$RELEASE_TAG" != "dev" ]; then + expected_sha="$(openshell_formula_pinned_sha256 "$RELEASE_TAG" "openshell.rb")" \ + || fail "No NemoClaw-pinned SHA-256 for OpenShell $RELEASE_TAG Homebrew formula" + actual_sha="$(file_sha256 "$formula_file")" \ + || fail "No SHA-256 tool available (sha256sum/shasum)" + [ "$actual_sha" = "$expected_sha" ] \ + || fail "OpenShell Homebrew formula checksum does not match NemoClaw-pinned $RELEASE_TAG digest" + fi + + tap_formula_file="$(homebrew_formula_path "$HOMEBREW_TAP" "$HOMEBREW_FORMULA_NAME")" + info "staging Homebrew formula in tap ${HOMEBREW_TAP}..." + cp "$formula_file" "$tap_formula_file" + chmod 0644 "$tap_formula_file" + + formula_ref="${HOMEBREW_TAP}/${HOMEBREW_FORMULA_NAME}" + if brew list --formula "$HOMEBREW_FORMULA_NAME" >/dev/null 2>&1; then + info "reinstalling OpenShell with Homebrew..." + brew reinstall --formula "$formula_ref" + else + info "installing OpenShell with Homebrew..." + brew install --formula "$formula_ref" + fi + + restart_macos_homebrew_gateway_service || true + + brew_prefix="$(brew --prefix 2>/dev/null || true)" + openshell_bin="${brew_prefix}/bin/openshell" + [ -n "$brew_prefix" ] && [ -x "$openshell_bin" ] \ + || openshell_bin="$(command -v openshell 2>/dev/null || true)" + [ -n "$openshell_bin" ] && [ -x "$openshell_bin" ] \ + || fail "Homebrew completed but the openshell binary was not found on PATH." + require_openshell_messaging_features "$openshell_bin" + info "$("$openshell_bin" --version 2>&1 || echo openshell) installed" + exit 0 +} + validate_explicit_component_override gateway "${NEMOCLAW_OPENSHELL_GATEWAY_BIN:-}" validate_explicit_component_override sandbox "${NEMOCLAW_OPENSHELL_SANDBOX_BIN:-}" @@ -617,8 +733,15 @@ if command -v openshell >/dev/null 2>&1; then && printf '%s\n' "$INSTALLED_VERSION_OUTPUT" | grep -qi 'dev'; then if required_driver_bins_present "$ACTIVE_OPENSHELL_BIN" && openshell_has_required_messaging_features "$ACTIVE_OPENSHELL_BIN"; then if [ "$FORCE_INSTALL" != "1" ]; then - info "openshell already installed: $INSTALLED_VERSION_OUTPUT (dev channel)" - exit 0 + if [ "$OS" = "Darwin" ] && ! macos_homebrew_formula_installed; then + warn "openshell $INSTALLED_VERSION_OUTPUT is installed without the Homebrew gateway service — installing OpenShell with Homebrew..." + else + if [ "$OS" = "Darwin" ]; then + restart_macos_homebrew_gateway_service || true + fi + info "openshell already installed: $INSTALLED_VERSION_OUTPUT (dev channel)" + exit 0 + fi fi warn "Current OpenShell dev build requested — refreshing the moving dev release instead of reusing the installed binary." else @@ -639,7 +762,12 @@ if command -v openshell >/dev/null 2>&1; then warn "openshell $INSTALLED_VERSION is missing Docker-driver binaries — reinstalling pinned OpenShell ${PIN_VERSION}..." elif ! openshell_has_required_messaging_features "$ACTIVE_OPENSHELL_BIN"; then fail "${OPENSHELL_FEATURE_CHECK_ERROR:-openshell $INSTALLED_VERSION is missing required messaging credential rewrite and MCP L7 policy support. Install an OpenShell build that includes provider aliases, WebSocket text rewrite, request-body credential rewrite, and MCP/JSON-RPC L7 policy enforcement.}" + elif [ "$OS" = "Darwin" ] && ! macos_homebrew_formula_installed; then + warn "openshell $INSTALLED_VERSION is installed without the Homebrew gateway service — reinstalling pinned OpenShell ${PIN_VERSION} with Homebrew..." else + if [ "$OS" = "Darwin" ]; then + restart_macos_homebrew_gateway_service || true + fi info "openshell already installed: $INSTALLED_VERSION (>= $MIN_VERSION, <= $MAX_VERSION, messaging rewrite, MCP L7, and policy --base capable)" exit 0 fi @@ -651,6 +779,10 @@ fi info "Installing OpenShell from release '$RELEASE_TAG'..." +if [ "$OS" = "Darwin" ]; then + install_macos_homebrew_formula +fi + case "$OS" in Darwin) case "$ARCH_LABEL" in @@ -676,7 +808,7 @@ case "$OS" in CHECKSUM_FILES+=("openshell-gateway-checksums-sha256.txt") ;; x86_64) - fail "OpenShell ${PIN_VERSION} does not publish macOS x86_64 standalone gateway assets." + fail "OpenShell ${PIN_VERSION} supports the macOS Homebrew gateway service only on Apple Silicon." ;; esac ;; diff --git a/scripts/install.sh b/scripts/install.sh index 8b9376f2035..e7a5fc06ae5 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1129,6 +1129,12 @@ upstream_openshell_gateway_user_service_installed() { || [[ -f /lib/systemd/user/openshell-gateway.service ]] } +macos_openshell_homebrew_gateway_service_installed() { + [[ "$(uname -s)" == "Darwin" ]] || return 1 + command -v brew >/dev/null 2>&1 || return 1 + brew list --formula openshell >/dev/null 2>&1 +} + resolve_openshell_gateway_bin_for_service() { local gateway_bin="${NEMOCLAW_OPENSHELL_GATEWAY_BIN:-}" if [[ -n "$gateway_bin" && -x "$gateway_bin" ]]; then @@ -1255,9 +1261,13 @@ maybe_install_openshell_during_install() { return 0 fi if [[ "$mode" == "if-missing" ]] && command_exists openshell; then - prefer_user_local_openshell - install_nemoclaw_openshell_gateway_user_service - return 0 + if [[ "$(uname -s)" == "Darwin" ]] && ! macos_openshell_homebrew_gateway_service_installed; then + info "OpenShell CLI exists but the macOS Homebrew gateway service is missing." + else + prefer_user_local_openshell + install_nemoclaw_openshell_gateway_user_service + return 0 + fi fi spin "Installing OpenShell CLI" bash "${NEMOCLAW_SOURCE_ROOT}/scripts/install-openshell.sh" prefer_user_local_openshell diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index ab94a37ce1a..1304ca63436 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -61,12 +61,27 @@ function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { } describe("docker-driver-gateway-service", () => { - it("detects the upstream OpenShell user service only on Linux", () => { + it("detects the platform OpenShell gateway service", () => { const existsSync = (candidate: string) => candidate === "/usr/lib/systemd/user/openshell-gateway.service"; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => + args.join(" ") === "list --formula openshell" ? spawnResult() : spawnResult(1, "unexpected"), + ); expect(hasOpenShellGatewayUserService({ existsSync, platform: "linux" })).toBe(true); expect(hasOpenShellGatewayUserService({ existsSync, platform: "darwin" })).toBe(false); + expect( + hasOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + platform: "darwin", + spawnSyncImpl, + }), + ).toBe(true); + expect(spawnSyncImpl).toHaveBeenCalledWith( + "brew", + ["list", "--formula", "openshell"], + expect.objectContaining({ encoding: "utf-8" }), + ); expect(getOpenShellGatewayUserServicePaths()).toEqual([ "/usr/local/lib/systemd/user/openshell-gateway.service", "/usr/lib/systemd/user/openshell-gateway.service", @@ -289,6 +304,57 @@ describe("docker-driver-gateway-service", () => { ]); }); + it("restarts the macOS Homebrew gateway service", () => { + const events: string[] = []; + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + events.push(args.join(" ")); + return spawnResult(); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + prepareServiceEnv: () => events.push("prepare-env"), + spawnSyncImpl, + }); + + expect(result).toEqual({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: true, + statusCommand: "brew services info openshell", + }); + expect(events).toEqual([ + "list --formula openshell", + "prepare-env", + "services restart openshell", + ]); + }); + + it("does not fall back when the macOS Homebrew service restart fails", () => { + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args[0] === "services" ? spawnResult(1, "launchctl failed") : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + statusCommand: "brew services info openshell", + }); + expect(result.reason).toContain("launchctl failed"); + }); + it("allows standalone fallback when the user systemd manager is unavailable", () => { const result = startOpenShellGatewayUserService({ commandExists: () => true, diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 93d9be0ba6f..7368e223d2b 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -16,6 +16,7 @@ import { import { isDockerDriverGatewayHttpReady } from "./gateway-http-readiness"; export const OPENSHELL_GATEWAY_USER_SERVICE = "openshell-gateway"; +export const OPENSHELL_GATEWAY_HOMEBREW_SERVICE = "openshell"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; @@ -34,8 +35,10 @@ export interface OpenShellGatewayUserServiceOptions { export interface OpenShellGatewayUserServiceStartResult { attempted: boolean; fallbackAllowed: boolean; + manager?: "homebrew" | "systemd"; reason?: string; serviceName?: string; + statusCommand?: string; started: boolean; } @@ -106,7 +109,9 @@ interface OpenShellGatewayUserServiceIdentity { } interface OpenShellGatewayUserServiceTarget { + manager: "homebrew" | "systemd"; serviceName: string; + statusCommand: string; trustedBinaryPaths: string[]; trustedUnitPaths: string[]; } @@ -189,6 +194,25 @@ function hasUpstreamOpenShellGatewayUserService( return getOpenShellGatewayUserServicePaths().some((candidate) => existsSync(candidate)); } +function hasHomebrewOpenShellGatewayService( + opts: Pick< + OpenShellGatewayUserServiceOptions, + "commandExists" | "env" | "platform" | "spawnSyncImpl" + > = {}, +): boolean { + const platform = opts.platform ?? process.platform; + if (platform !== "darwin") return false; + const env = opts.env ?? process.env; + const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + if (!commandExists("brew")) return false; + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const result = runBrew(["list", "--formula", OPENSHELL_GATEWAY_HOMEBREW_SERVICE], { + env, + spawnSyncImpl, + }); + return result.ok; +} + export function hasNemoclawOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, @@ -211,13 +235,26 @@ export function hasNemoclawOpenShellGatewayUserService( function resolveOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "commandExists" | "env" | "existsSync" | "home" | "platform" | "readFileSync" | "spawnSyncImpl" > = {}, ): OpenShellGatewayUserServiceTarget | null { - if ((opts.platform ?? process.platform) !== "linux") return null; + const platform = opts.platform ?? process.platform; + if (platform === "darwin") { + if (!hasHomebrewOpenShellGatewayService(opts)) return null; + return { + manager: "homebrew", + serviceName: OPENSHELL_GATEWAY_HOMEBREW_SERVICE, + statusCommand: `brew services info ${OPENSHELL_GATEWAY_HOMEBREW_SERVICE}`, + trustedBinaryPaths: [], + trustedUnitPaths: [], + }; + } + if (platform !== "linux") return null; if (hasUpstreamOpenShellGatewayUserService(opts)) { return { + manager: "systemd", serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + statusCommand: `systemctl --user status ${OPENSHELL_GATEWAY_USER_SERVICE}`, trustedBinaryPaths: getOpenShellGatewayUserServiceBinaryPaths(), trustedUnitPaths: getOpenShellGatewayUserServicePaths(), }; @@ -227,7 +264,9 @@ function resolveOpenShellGatewayUserService( const home = effectiveHome(opts.home, opts.env); const servicePath = getNemoclawOpenShellGatewayUserServicePath(home, env); return { + manager: "systemd", serviceName: OPENSHELL_GATEWAY_USER_SERVICE, + statusCommand: `systemctl --user status ${OPENSHELL_GATEWAY_USER_SERVICE}`, trustedBinaryPaths: getNemoclawOpenShellGatewayUserServiceBinaryPaths(home), trustedUnitPaths: [servicePath], }; @@ -238,7 +277,7 @@ function resolveOpenShellGatewayUserService( export function hasOpenShellGatewayUserService( opts: Pick< OpenShellGatewayUserServiceOptions, - "env" | "existsSync" | "home" | "platform" | "readFileSync" + "commandExists" | "env" | "existsSync" | "home" | "platform" | "readFileSync" | "spawnSyncImpl" > = {}, ): boolean { return resolveOpenShellGatewayUserService(opts) !== null; @@ -285,6 +324,26 @@ function runSystemctlUser( return { ok: true, stdout: text(result.stdout) }; } +function runBrew( + args: string[], + opts: Required>, +): { ok: boolean; reason?: string; stdout?: string } { + const result = opts.spawnSyncImpl("brew", args, { + encoding: "utf-8", + env: opts.env, + stdio: ["ignore", "pipe", "pipe"], + } satisfies SpawnSyncOptions); + if (result.error) { + return { ok: false, reason: result.error.message }; + } + if (result.status !== 0) { + const detail = + text(result.stderr).trim() || text(result.stdout).trim() || `exit ${String(result.status)}`; + return { ok: false, reason: detail }; + } + return { ok: true, stdout: text(result.stdout) }; +} + function parseSystemctlShowProperties(output: string): Record { const properties: Record = {}; for (const line of output.split(/\r?\n/)) { @@ -514,18 +573,27 @@ export function startOpenShellGatewayUserService( opts: OpenShellGatewayUserServiceOptions = {}, ): OpenShellGatewayUserServiceStartResult { const platform = opts.platform ?? process.platform; - if (platform !== "linux") { - return { attempted: false, fallbackAllowed: true, started: false, reason: "not a Linux host" }; + if (platform !== "linux" && platform !== "darwin") { + return { + attempted: false, + fallbackAllowed: true, + started: false, + reason: "unsupported service platform", + }; } const env = opts.env ?? process.env; const home = effectiveHome(opts.home, opts.env); const existsSync = opts.existsSync ?? fs.existsSync; + const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; const service = resolveOpenShellGatewayUserService({ + commandExists, env, existsSync, home, platform, readFileSync: opts.readFileSync, + spawnSyncImpl, }); if (!service) { return { @@ -536,17 +604,69 @@ export function startOpenShellGatewayUserService( }; } - const commandExists = opts.commandExists ?? ((command) => defaultCommandExists(command, env)); + if (service.manager === "homebrew") { + if (!commandExists("brew")) { + return { + attempted: true, + fallbackAllowed: true, + manager: service.manager, + reason: "brew is not available", + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + try { + opts.prepareServiceEnv?.(); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: `failed to prepare OpenShell gateway service environment: ${detail}`, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + const result = runBrew(["services", "restart", service.serviceName], { env, spawnSyncImpl }); + if (!result.ok) { + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: `brew services restart ${service.serviceName} failed: ${result.reason}`, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + serviceName: service.serviceName, + started: true, + statusCommand: service.statusCommand, + }; + } + if (!commandExists("systemctl")) { return { attempted: true, fallbackAllowed: true, + manager: service.manager, started: false, reason: "systemctl is not available", + serviceName: service.serviceName, + statusCommand: service.statusCommand, }; } - const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; for (const args of [["daemon-reload"]]) { const result = runSystemctlUser(args, { env, spawnSyncImpl }); if (!result.ok) { @@ -554,8 +674,11 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), + manager: service.manager, reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } } @@ -565,8 +688,11 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: identity.fallbackAllowed, + manager: service.manager, reason: identity.reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } @@ -577,8 +703,11 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: false, + manager: service.manager, reason: `failed to prepare OpenShell gateway service environment: ${detail}`, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } @@ -592,8 +721,11 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: userManagerLooksUnavailable(result.reason ?? ""), + manager: service.manager, reason, + serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } } @@ -607,17 +739,21 @@ export function startOpenShellGatewayUserService( return { attempted: true, fallbackAllowed: userManagerLooksUnavailable(active.reason ?? ""), + manager: service.manager, reason, serviceName: service.serviceName, started: false, + statusCommand: service.statusCommand, }; } return { attempted: true, fallbackAllowed: false, + manager: service.manager, serviceName: service.serviceName, started: true, + statusCommand: service.statusCommand, }; } @@ -642,7 +778,7 @@ export async function startPackageManagedDockerDriverGateway({ }: PackageManagedDockerDriverGatewayOptions): Promise { if (!hasOpenShellGatewayUserServiceImpl()) return false; - console.log(" Starting OpenShell Docker-driver gateway via user service..."); + console.log(" Starting OpenShell Docker-driver gateway via package-managed service..."); const serviceStart = startOpenShellGatewayUserServiceImpl({ prepareServiceEnv: prepareOpenShellGatewayUserServiceEnv, }); @@ -650,15 +786,16 @@ export async function startPackageManagedDockerDriverGateway({ const detail = serviceStart.reason ? ` (${serviceStart.reason})` : ""; if (serviceStart.fallbackAllowed) { console.warn( - ` OpenShell gateway user service is unavailable${detail}; using standalone fallback.`, + ` OpenShell gateway package-managed service is unavailable${detail}; using standalone fallback.`, ); return false; } - const message = `OpenShell gateway user service failed to start${detail}.`; + const message = `OpenShell gateway service failed to start${detail}.`; console.error(` ${message}`); console.error( - ` Check: systemctl --user status ${ - serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE + ` Check: ${ + serviceStart.statusCommand ?? + `systemctl --user status ${serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE}` }`, ); if (exitOnFailure) process.exit(1); @@ -698,11 +835,11 @@ export async function startPackageManagedDockerDriverGateway({ await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { skip: skipSandboxBridgeReachability, }); - console.log(" ✓ OpenShell gateway user service is healthy"); + console.log(" ✓ OpenShell gateway package-managed service is healthy"); return true; } - const message = `OpenShell gateway user service started but did not become healthy within the configured ${formatGatewayHealthWaitLimit( + const message = `OpenShell gateway service started but did not become healthy within the configured ${formatGatewayHealthWaitLimit( pollCount, pollInterval, )}.`; @@ -710,7 +847,12 @@ export async function startPackageManagedDockerDriverGateway({ console.error( ` Last readiness check: endpoint registered=${lastReadiness.registered ? "yes" : "no"}, OpenShell CLI health=${lastReadiness.cliHealthy ? "yes" : "no"}, direct gRPC health=${lastReadiness.grpcHealthy ? "yes" : "no"}.`, ); - console.error(" Check: systemctl --user status openshell-gateway"); + console.error( + ` Check: ${ + serviceStart.statusCommand ?? + `systemctl --user status ${serviceStart.serviceName ?? OPENSHELL_GATEWAY_USER_SERVICE}` + }`, + ); if (exitOnFailure) process.exit(1); throw new Error(message); } diff --git a/src/lib/onboard/openshell-install.ts b/src/lib/onboard/openshell-install.ts index 4c13d70ff6a..27e873aee49 100644 --- a/src/lib/onboard/openshell-install.ts +++ b/src/lib/onboard/openshell-install.ts @@ -200,7 +200,7 @@ export function ensureOpenshellForOnboard(deps: OpenShellInstallDeps): OpenShell } else if (needsDockerDriverBinaries) { const required = platform === "linux" ? "gateway and sandbox" : "gateway"; deps.log( - ` OpenShell standalone gateway onboarding requires the ${required} binaries. Reinstalling...`, + ` OpenShell Docker-driver gateway onboarding requires the ${required} binaries. Reinstalling...`, ); } else if (needsMessagingFeatures) { deps.log( diff --git a/test/install-openshell-gateway-service.test.ts b/test/install-openshell-gateway-service.test.ts index 31afc27dc4b..f2650777a8e 100644 --- a/test/install-openshell-gateway-service.test.ts +++ b/test/install-openshell-gateway-service.test.ts @@ -91,6 +91,62 @@ describe("install.sh OpenShell gateway service", () => { } }); + it("skips OpenShell reinstall on macOS when the Homebrew service is present", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const eventsPath = path.join(tmp, "events.log"); + + try { + const result = runInstallHelper( + tmp, + [ + 'uname() { [[ "${1:-}" == "-s" ]] && printf "Darwin\\n" || printf "arm64\\n"; }', + 'command_exists() { [[ "$1" == openshell ]]; }', + 'brew() { [[ "$*" == "list --formula openshell" ]]; }', + `spin() { printf 'spin\\n' >>${JSON.stringify(eventsPath)}; return 1; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + `install_nemoclaw_openshell_gateway_user_service() { printf 'service\\n' >>${JSON.stringify(eventsPath)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(fs.readFileSync(eventsPath, "utf-8")).toBe("prefer\nservice\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("installs OpenShell on macOS when only the CLI exists and the Homebrew service is missing", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); + const eventsPath = path.join(tmp, "events.log"); + + try { + const result = runInstallHelper( + tmp, + [ + 'uname() { [[ "${1:-}" == "-s" ]] && printf "Darwin\\n" || printf "arm64\\n"; }', + 'command_exists() { [[ "$1" == openshell ]]; }', + 'brew() { [[ "$*" == "list --formula openshell" ]] && return 1; return 0; }', + `spin() { printf 'spin:%s\\n' "$*" >>${JSON.stringify(eventsPath)}; return 0; }`, + `prefer_user_local_openshell() { printf 'prefer\\n' >>${JSON.stringify(eventsPath)}; }`, + `install_nemoclaw_openshell_gateway_user_service() { printf 'service\\n' >>${JSON.stringify(eventsPath)}; }`, + "maybe_install_openshell_during_install if-missing", + ].join("\n"), + ); + + expect(result.status).toBe(0); + expect(result.stdout).toContain( + "OpenShell CLI exists but the macOS Homebrew gateway service is missing.", + ); + const events = fs.readFileSync(eventsPath, "utf-8"); + expect(events).toContain("spin:Installing OpenShell CLI bash "); + expect(events).toContain("/scripts/install-openshell.sh\n"); + expect(events).toContain("prefer\nservice\n"); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + it("uses absolute XDG_CONFIG_HOME for the Linux user service path", () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-install-gateway-service-")); const configHome = path.join(tmp, "xdg-config"); diff --git a/test/install-openshell-version-check.test.ts b/test/install-openshell-version-check.test.ts index a4c4fb2651e..4a47bb5acb3 100644 --- a/test/install-openshell-version-check.test.ts +++ b/test/install-openshell-version-check.test.ts @@ -13,6 +13,7 @@ import { buildRebuildHermesChildEnv } from "./e2e/live/rebuild-hermes-env.ts"; const SCRIPT = path.join(import.meta.dirname, "..", "scripts", "install-openshell.sh"); const PINNED_OPEN_SHELL_SHA256 = { cliDarwinArm64: "117b5354cc42d80bc4d5e070ea5ac4e341208ff6d3c29b516d8a9c80e2310f8d", + formula: "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3", cliLinuxArm64: "a5ff01a3240d73c72ec1700eda6cc6c752a86cf50c5dd1b5bdc459f544d03045", cliLinuxX64: "37836c3b50383e03249c5e16512c1806e591fba8451408a84fb2f628ddb318c4", gatewayDarwinArm64: "8c07362107393eb5f4ae4b9ee9f4257fd53862c51ad8dd96f2fe31bb6d8d7ffb", @@ -55,6 +56,7 @@ function runWithInstalledVersion( sandboxBinaryDigest?: string; driverVersionExit?: number; driverReadable?: boolean; + homebrewFormula?: boolean; os?: string; arch?: string; } = {}, @@ -166,6 +168,7 @@ exit 1`, ); if ((options.os ?? "Linux") === "Darwin") { + const homebrewFormula = options.homebrewFormula ?? true; writeExecutable( path.join(fakeBin, "codesign"), `#!/usr/bin/env bash @@ -182,6 +185,23 @@ fi if [ -n "$state" ]; then : > "$state" fi +exit 0`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +case "$*" in + "list --formula openshell") + exit ${homebrewFormula ? "0" : "1"} + ;; + "services restart openshell") + exit 0 + ;; + "--prefix") + printf '%s\\n' ${JSON.stringify(tmp)} + exit 0 + ;; +esac exit 0`, ); } @@ -422,23 +442,12 @@ describe("install-openshell.sh version check", { timeout: 15_000 }, () => { ); }); - it.each([ - { archiveShape: "safe", status: 0, unsafe: false }, - { archiveShape: "absolute", status: 1, unsafe: true }, - { archiveShape: "traversal", status: 1, unsafe: true }, - { archiveShape: "duplicate", status: 1, unsafe: true }, - { archiveShape: "extra", status: 1, unsafe: true }, - { archiveShape: "symlink", status: 1, unsafe: true }, - { archiveShape: "hardlink", status: 1, unsafe: true }, - { archiveShape: "device", status: 1, unsafe: true }, - { archiveShape: "late-traversal", status: 1, unsafe: true }, - ] as const)("$archiveShape macOS arm64 archives are checked before extraction", (expected) => { - const { archiveShape } = expected; - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-assets-")); + it("fails closed when the macOS Homebrew formula does not match the pinned digest", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-formula-")); try { const fakeBin = path.join(tmp, "bin"); const downloadLog = path.join(tmp, "downloads.log"); - const tarLog = path.join(tmp, "tar.log"); + const brewLog = path.join(tmp, "brew.log"); fs.mkdirSync(fakeBin); writeExecutable( @@ -452,106 +461,147 @@ if [ "\${1:-}" = "-m" ]; then echo "arm64"; else echo "Darwin"; fi`, if [ "\${1:-}" = "--version" ]; then echo "openshell 0.0.36"; exit 0; fi exit 99`, ); - writeExecutable( - path.join(fakeBin, "gh"), - `#!/usr/bin/env bash -exit 1`, - ); + writeExecutable(path.join(fakeBin, "gh"), "#!/usr/bin/env bash\nexit 1\n"); writeExecutable( path.join(fakeBin, "curl"), `#!/usr/bin/env bash echo "$@" >> ${JSON.stringify(downloadLog)} out="" while [ "$#" -gt 0 ]; do - if [ "$1" = "-o" ]; then - shift - out="$1" - fi + if [ "$1" = "-o" ]; then shift; out="$1"; fi shift || true done -if [ -n "$out" ]; then - case "$(basename "$out")" in - openshell-checksums-sha256.txt) - printf '%s\n' \ - '${PINNED_OPEN_SHELL_SHA256.cliDarwinArm64} openshell-aarch64-apple-darwin.tar.gz' > "$out" - ;; - openshell-gateway-checksums-sha256.txt) - printf '%s\n' \ - '${PINNED_OPEN_SHELL_SHA256.gatewayDarwinArm64} openshell-gateway-aarch64-apple-darwin.tar.gz' > "$out" - ;; - *) - : > "$out" - ;; - esac -fi +[ -n "$out" ] || exit 1 +printf '%s\\n' 'class Openshell < Formula' > "$out" exit 0`, ); writeExecutable( path.join(fakeBin, "sha256sum"), `#!/usr/bin/env bash -cat >/dev/null -echo "checksum OK" +printf '%s %s\\n' '${ZERO_SHA256}' "$1"`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +printf '%s\\n' "$*" >> ${JSON.stringify(brewLog)} exit 0`, ); + + const result = spawnSync("bash", [SCRIPT], { + env: { + ...process.env, + HOME: tmp, + NEMOCLAW_OPENSHELL_CHANNEL: "stable", + PATH: `${fakeBin}:/usr/bin:/bin`, + }, + encoding: "utf8", + }); + + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(1); + expect(result.stderr).toContain( + "OpenShell Homebrew formula checksum does not match NemoClaw-pinned v0.0.72 digest", + ); + expect(fs.readFileSync(downloadLog, "utf-8")).toContain("openshell.rb"); + expect(fs.existsSync(brewLog) ? fs.readFileSync(brewLog, "utf-8") : "").toBe(""); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + it("installs macOS OpenShell through the Homebrew formula and restarts the service", () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openshell-macos-formula-")); + try { + const fakeBin = path.join(tmp, "bin"); + const homebrewPrefix = path.join(tmp, "homebrew"); + const tapRepo = path.join(tmp, "tap"); + const downloadLog = path.join(tmp, "downloads.log"); + const brewLog = path.join(tmp, "brew.log"); + fs.mkdirSync(fakeBin); + fs.mkdirSync(path.join(homebrewPrefix, "bin"), { recursive: true }); + writeExecutable( - path.join(fakeBin, "tar"), + path.join(fakeBin, "uname"), `#!/usr/bin/env bash -printf '%s\\n' "$*" >> ${JSON.stringify(tarLog)} -case "$*" in -*openshell-gateway*) name="openshell-gateway" ;; -*) name="openshell" ;; -esac -case "\${1:-}" in --tzf) - case ${JSON.stringify(archiveShape)} in - absolute) printf '/tmp/%s\\n' "$name" ;; - traversal) printf '../%s\\n' "$name" ;; - duplicate) printf '%s\\n%s\\n' "$name" "$name" ;; - extra) printf '%s\\nunexpected\\n' "$name" ;; - late-traversal) - if [ "$name" = "openshell-gateway" ]; then printf '../%s\\n' "$name"; else printf '%s\\n' "$name"; fi - ;; - *) printf '%s\\n' "$name" ;; - esac - exit 0 - ;; --tvzf) - case ${JSON.stringify(archiveShape)} in - symlink) printf 'lrwxrwxrwx 0/0 0 2026-01-01 00:00 %s -> target\\n' "$name" ;; - hardlink) printf 'hrwxr-xr-x 0/0 0 2026-01-01 00:00 %s link to target\\n' "$name" ;; - device) printf 'crw-rw-rw- 0/0 1,3 2026-01-01 00:00 %s\\n' "$name" ;; - *) printf '%s\\n' "-rwxr-xr-x 0/0 1 2026-01-01 00:00 $name" ;; - esac - exit 0 - ;; -esac -outdir="" -prev="" -for arg in "$@"; do - if [ "$prev" = "-C" ]; then - outdir="$arg" - break +if [ "\${1:-}" = "-m" ]; then echo "arm64"; else echo "Darwin"; fi`, + ); + writeExecutable( + path.join(fakeBin, "openshell"), + `#!/usr/bin/env bash +if [ "\${1:-}" = "--version" ]; then echo "openshell 0.0.36"; exit 0; fi +exit 99`, + ); + writeExecutable(path.join(fakeBin, "gh"), "#!/usr/bin/env bash\nexit 1\n"); + writeExecutable( + path.join(fakeBin, "curl"), + `#!/usr/bin/env bash +echo "$@" >> ${JSON.stringify(downloadLog)} +out="" +while [ "$#" -gt 0 ]; do + if [ "$1" = "-o" ]; then + shift; out="$1" fi - prev="$arg" + shift || true done -[ -n "$outdir" ] || exit 1 -printf '#!/usr/bin/env bash\nexit 0\n' > "$outdir/$name" -chmod 755 "$outdir/$name" +[ -n "$out" ] || exit 1 +cat > "$out" <<'EOF' +class Openshell < Formula + def post_install + entitlements.write <<~XML + + XML + end +end +EOF exit 0`, ); writeExecutable( - path.join(fakeBin, "install"), + path.join(fakeBin, "sha256sum"), `#!/usr/bin/env bash -dest="\${@: -1}" -mkdir -p "$(dirname "$dest")" - cat > "$dest" <<'EOF' +printf '%s %s\\n' '${PINNED_OPEN_SHELL_SHA256.formula}' "$1"`, + ); + writeExecutable( + path.join(fakeBin, "brew"), + `#!/usr/bin/env bash +printf '%s\\n' "$*" >> ${JSON.stringify(brewLog)} +case "$*" in + "tap-info nvidia/openshell") + exit 1 + ;; + "tap-new --no-git nvidia/openshell") + mkdir -p ${JSON.stringify(path.join(tapRepo, "Formula"))} + exit 0 + ;; + "--repository nvidia/openshell") + printf '%s\\n' ${JSON.stringify(tapRepo)} + exit 0 + ;; + "list --formula openshell") + exit 1 + ;; + "install --formula nvidia/openshell/openshell") + cat > ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell"))} <<'EOF' #!/usr/bin/env bash if [ "\${1:-}" = "--version" ]; then echo "openshell ${REQUIRED_OPENSHELL_VERSION}"; exit 0; fi # ${OPENSHELL_FEATURE_MARKERS} exit 0 EOF -chmod +x "$dest" -exit 0`, + cat > ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell-gateway"))} <<'EOF' +#!/usr/bin/env bash +if [ "\${1:-}" = "--version" ]; then echo "openshell-gateway ${REQUIRED_OPENSHELL_VERSION}"; exit 0; fi +exit 0 +EOF + chmod 755 ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell"))} ${JSON.stringify(path.join(homebrewPrefix, "bin", "openshell-gateway"))} + exit 0 + ;; + "services restart openshell") + exit 0 + ;; + "--prefix") + printf '%s\\n' ${JSON.stringify(homebrewPrefix)} + exit 0 + ;; +esac +exit 1`, ); const result = spawnSync("bash", [SCRIPT], { @@ -565,20 +615,22 @@ exit 0`, encoding: "utf8", }); - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(expected.status); - expect(result.stderr.includes("Unsafe OpenShell archive")).toBe(expected.unsafe); - const installedVersion = spawnSync(path.join(fakeBin, "openshell"), ["--version"], { - encoding: "utf8", - }).stdout.trim(); - expect(installedVersion).toBe( - expected.unsafe ? "openshell 0.0.36" : `openshell ${REQUIRED_OPENSHELL_VERSION}`, - ); - expect(/^xzf /m.test(fs.readFileSync(tarLog, "utf8"))).toBe(!expected.unsafe); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); const downloads = fs.readFileSync(downloadLog, "utf-8"); - expect(downloads).toContain("openshell-aarch64-apple-darwin.tar.gz"); - expect(downloads).toContain("openshell-gateway-aarch64-apple-darwin.tar.gz"); - expect(downloads).not.toContain("openshell-driver-vm-aarch64-apple-darwin.tar.gz"); - expect(downloads).toContain("openshell-gateway-checksums-sha256.txt"); + expect(downloads).toContain("openshell.rb"); + expect(downloads).not.toContain("openshell-aarch64-apple-darwin.tar.gz"); + const brewEvents = fs.readFileSync(brewLog, "utf-8").trim().split("\n"); + expect(brewEvents).toEqual([ + "tap-info nvidia/openshell", + "tap-new --no-git nvidia/openshell", + "--repository nvidia/openshell", + "list --formula openshell", + "install --formula nvidia/openshell/openshell", + "services restart openshell", + "--prefix", + ]); + const stagedFormula = fs.readFileSync(path.join(tapRepo, "Formula", "openshell.rb"), "utf-8"); + expect(stagedFormula).toContain("entitlements.write <<~XML"); } finally { fs.rmSync(tmp, { recursive: true, force: true }); } @@ -1049,7 +1101,7 @@ exit 0`, expect(result.stdout).toContain("Installing OpenShell from release 'dev'"); }); - it("reuses a macOS dev build with its required standalone gateway", () => { + it("reuses a macOS dev build with its required Homebrew gateway service", () => { const result = runWithInstalledVersion( "0.0.72-dev.8+g7bce1223d", { diff --git a/test/installer-hash-check.test.ts b/test/installer-hash-check.test.ts index dc9394088df..c16dec7fa2f 100644 --- a/test/installer-hash-check.test.ts +++ b/test/installer-hash-check.test.ts @@ -54,6 +54,8 @@ const ASSET_DIGESTS = new Map([ ], ]); const ASSETS = [...ASSET_DIGESTS.keys()]; +const FORMULA_ASSET = "openshell.rb"; +const FORMULA_DIGEST = "4b75a7e3a7630eb8954d73ca828b394d5e0646adbaa4b087b2435329d53b61b3"; const UNPUBLISHED_ASSET = "openshell-sandbox-aarch64-unknown-linux-gnu-unpublished.tar.gz"; const OFFICIAL_UNEXPECTED_INSTALLER_ASSET = "openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz"; const OFFICIAL_UNEXPECTED_INSTALLER_DIGEST = @@ -432,6 +434,7 @@ function renderPinFunction( assets: string[], openshellVersion: string, formatting: PinFormatting, + digestMap: ReadonlyMap = ASSET_DIGESTS, ): string { const functionOpening = formatting === "mixed-whitespace" ? `${functionName}\t( )\t{` : `${functionName}() {`; @@ -447,7 +450,7 @@ function renderPinFunction( : ' case "${release_tag}:${asset}" in'; const cases = assets .map((asset) => { - const digest = ASSET_DIGESTS.get(asset) ?? "missing"; + const digest = digestMap.get(asset) ?? "missing"; const pattern = formatting === "quote-styles" ? ` 'v${openshellVersion}:${asset}')` @@ -481,13 +484,20 @@ function replacePinFunction( replacement: string, ): string { const start = source.indexOf(`${functionName}() {`); - const next = source.indexOf(`\n${nextFunctionName}() {`, start); + let next = source.indexOf(`\n${nextFunctionName}() {`, start); + if (next === -1) { + next = source.indexOf(`\n${nextFunctionName}`, start); + } expect(start, `${functionName} template start`).not.toBe(-1); expect(next, `${functionName} template end`).not.toBe(-1); return `${source.slice(0, start)}${replacement}${source.slice(next)}`; } -function renderInstallerTemplate(openshellVersion: string, pinFunction: string): string { +function renderInstallerTemplate( + openshellVersion: string, + pinFunction: string, + formulaPinFunction: string, +): string { const selected = INSTALLER_TEMPLATE.replace( /^MIN_VERSION="[0-9]+\.[0-9]+\.[0-9]+"$/m, `MIN_VERSION="${openshellVersion}"`, @@ -497,12 +507,18 @@ function renderInstallerTemplate(openshellVersion: string, pinFunction: string): /^DEV_MIN_VERSION="[0-9]+\.[0-9]+\.[0-9]+"$/m, `DEV_MIN_VERSION="${openshellVersion}"`, ); - const withPinFunction = replacePinFunction( + const withArchivePinFunction = replacePinFunction( selected, "openshell_pinned_sha256", "openshell_checksum_line", pinFunction, ); + const withPinFunction = replacePinFunction( + withArchivePinFunction, + "openshell_formula_pinned_sha256", + "# A pinned digest authenticates bytes", + formulaPinFunction, + ); const sandboxFunctionStart = withPinFunction.indexOf("pinned_sandbox_build_version() {"); const sandboxFunctionEnd = withPinFunction.indexOf( "\ncomponent_build_version() {", @@ -562,6 +578,13 @@ function createFixture( renderInstallerTemplate( openshellVersion, renderPinFunction("openshell_pinned_sha256", ASSETS, openshellVersion, formatting), + renderPinFunction( + "openshell_formula_pinned_sha256", + [FORMULA_ASSET], + openshellVersion, + formatting, + new Map([[FORMULA_ASSET, FORMULA_DIGEST]]), + ), ), ); fs.writeFileSync( @@ -610,16 +633,34 @@ case "$url" in *) printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-gateway-checksums-sha256.txt")}' >"$output" ;; esac ;; - openshell-sandbox-checksums-sha256.txt) - printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-sandbox-checksums-sha256.txt")}' >"$output" - ;; - esac + openshell-sandbox-checksums-sha256.txt) + printf '%s' '${CHECKSUM_MANIFESTS.get("openshell-sandbox-checksums-sha256.txt")}' >"$output" + ;; + openshell.rb) + printf '%s\n' 'class Openshell < Formula; end' >"$output" + ;; + esac + ;; + *) exit 22 ;; + esac + `, + ); + fs.chmodSync(path.join(binDir, "curl"), 0o755); + fs.writeFileSync( + path.join(binDir, "sha256sum"), + `#!/usr/bin/env bash +set -euo pipefail +case "\${1:-}" in + */openshell.rb) + printf '%s %s\\n' '${FORMULA_DIGEST}' "$1" + ;; + *) + /usr/bin/sha256sum "$@" ;; - *) exit 22 ;; esac `, ); - fs.chmodSync(path.join(binDir, "curl"), 0o755); + fs.chmodSync(path.join(binDir, "sha256sum"), 0o755); return fixtureRoot; } @@ -983,7 +1024,7 @@ describe("installer hash verification", () => { expect(result.status).not.toBe(0); expect(result.stdout).toContain("Checking OpenShell v0.0.72 release assets"); - expect(result.stdout).toContain("14 OpenShell release-asset check(s) failed"); + expect(result.stdout).toContain("15 OpenShell release-asset check(s) failed"); expect(result.stdout).not.toContain("All installer hashes are current"); }); @@ -992,7 +1033,7 @@ describe("installer hash verification", () => { expect(result.status).toBe(1); expect(result.stdout).toContain("digest does not match the pinned v0.0.72 release asset"); - expect(result.stdout).toContain("expected all 10 pinned asset references"); + expect(result.stdout).toContain("expected all 11 pinned asset references"); expect(result.stdout).not.toContain("All installer hashes are current"); }); From 6660bf046a12fbb15e17aeae222fadc76b690e5a Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 23:22:32 +0700 Subject: [PATCH 22/24] fix(onboard): propagate Docker host to gateway service Signed-off-by: San Dang --- ...er-driver-gateway-env-deb-override.test.ts | 20 +++ .../docker-driver-gateway-env-service.test.ts | 78 ++++++++- src/lib/onboard/docker-driver-gateway-env.ts | 31 +++- .../docker-driver-gateway-service.test.ts | 160 +++++++++++++++++- .../onboard/docker-driver-gateway-service.ts | 106 +++++++++++- 5 files changed, 389 insertions(+), 6 deletions(-) diff --git a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts index 10b497107fb..245f8f80abc 100644 --- a/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-deb-override.test.ts @@ -24,6 +24,7 @@ describe("buildDockerGatewayDebEnvFile", () => { "OPENSHELL_BIND_ADDRESS=127.0.0.1", "OPENSHELL_SERVER_PORT=8080", "OPENSHELL_DOCKER_SUPERVISOR_IMAGE=old", + "DOCKER_HOST=unix:///tmp/old-docker.sock", ].join("\n"), { OPENSHELL_DRIVERS: "docker", @@ -39,6 +40,7 @@ describe("buildDockerGatewayDebEnvFile", () => { OPENSHELL_DOCKER_SUPERVISOR_IMAGE: "new", OPENSHELL_GATEWAY_CONFIG: "/tmp/openshell-gateway.toml", OPENSHELL_VM_DRIVER_STATE_DIR: "/tmp/old-vm-driver", + DOCKER_HOST: "unix:///tmp/new-docker.sock", }, ); @@ -48,8 +50,10 @@ describe("buildDockerGatewayDebEnvFile", () => { expect(next).toContain("OPENSHELL_DOCKER_SUPERVISOR_IMAGE=new\n"); expect(next).toContain("OPENSHELL_GATEWAY_CONFIG=/tmp/openshell-gateway.toml\n"); expect(next).toContain("OPENSHELL_VM_DRIVER_STATE_DIR=/tmp/old-vm-driver\n"); + expect(next).toContain("DOCKER_HOST='unix:///tmp/new-docker.sock'\n"); expect(next).not.toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1"); expect(next).not.toContain("OPENSHELL_DOCKER_SUPERVISOR_IMAGE=old"); + expect(next).not.toContain("DOCKER_HOST=unix:///tmp/old-docker.sock"); }); it("removes stale VM driver env keys when writing a Docker-driver env file", () => { @@ -67,6 +71,22 @@ describe("buildDockerGatewayDebEnvFile", () => { expect(next).toBe("OPENSHELL_DRIVERS=docker\n"); }); + it("removes a stale Docker endpoint when the current runtime uses the default socket", () => { + const next = buildDockerGatewayDebEnvFile("DOCKER_HOST=unix:///tmp/old-docker.sock\n", { + OPENSHELL_DRIVERS: "docker", + }); + + expect(next).toBe("OPENSHELL_DRIVERS=docker\n"); + }); + + it("quotes Docker socket paths for both service env readers", () => { + const dockerHost = "unix:///Users/José Doe/.colima/$(literal)/docker.sock"; + + expect(buildDockerGatewayDebEnvFile("", { DOCKER_HOST: dockerHost })).toBe( + `DOCKER_HOST='${dockerHost}'\n`, + ); + }); + it("removes stale auth-disable env so OpenShell 0.0.72 TOML auth policy stays authoritative", () => { const next = buildDockerGatewayDebEnvFile( [ diff --git a/src/lib/onboard/docker-driver-gateway-env-service.test.ts b/src/lib/onboard/docker-driver-gateway-env-service.test.ts index 4586e7f0786..179ba32d9a4 100644 --- a/src/lib/onboard/docker-driver-gateway-env-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-env-service.test.ts @@ -16,7 +16,8 @@ function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { describe("package-managed Docker-driver gateway env service", () => { it("writes the service env only when package-managed startup prepares the service", async () => { const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); - const env = homeEnv(tempHome); + const dockerHost = `unix://${path.join(tempHome, ".colima", "default", "docker.sock")}`; + const env = { ...homeEnv(tempHome), DOCKER_HOST: dockerHost }; const gatewayBin = path.join(tempHome, ".local", "bin", "openshell-gateway"); const servicePath = path.join( tempHome, @@ -28,6 +29,7 @@ describe("package-managed Docker-driver gateway env service", () => { const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); try { await expect( @@ -61,9 +63,81 @@ describe("package-managed Docker-driver gateway env service", () => { expect(fs.readFileSync(servicePath, "utf-8")).toContain(`ExecStart=${gatewayBin}`); expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_BIND_ADDRESS=127.0.0.1\n"); expect(fs.readFileSync(envFile, "utf-8")).toContain("OPENSHELL_SERVER_PORT=18080\n"); + expect(fs.readFileSync(envFile, "utf-8")).toContain(`DOCKER_HOST='${dockerHost}'\n`); } finally { existsSpy.mockRestore(); homedirSpy.mockRestore(); + platformSpy.mockRestore(); + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + + it.each([ + "tcp://attacker.example:2375", + "ssh://docker.example", + "unix://relative/docker.sock", + "unix:///tmp/docker's.sock", + ])("rejects unsafe package-service Docker endpoint %s", async (dockerHost) => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const envFile = path.join(tempHome, ".config", "openshell", "gateway.env"); + const startService = vi.fn((opts?: { prepareServiceEnv?: () => void }) => { + opts?.prepareServiceEnv?.(); + return { attempted: true, fallbackAllowed: false, started: true }; + }); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { ...homeEnv(tempHome), DOCKER_HOST: dockerHost }, + exitOnFailure: false, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: () => "", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: startService, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).rejects.toThrow(/only safely serializable absolute unix:\/\/ Docker sockets are supported/); + + expect(startService).toHaveBeenCalledOnce(); + expect(fs.existsSync(envFile)).toBe(false); + } finally { + fs.rmSync(tempHome, { recursive: true, force: true }); + } + }); + + it("leaves remote Docker endpoints to standalone fallback when no package service exists", async () => { + const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-gateway-env-")); + const startService = vi.fn(); + + try { + await expect( + startPackageManagedDockerDriverGatewayWithEnvOverride({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + env: { ...homeEnv(tempHome), DOCKER_HOST: "ssh://docker.example" }, + exitOnFailure: false, + gatewayEnv: { + OPENSHELL_BIND_ADDRESS: "127.0.0.1", + OPENSHELL_GATEWAY_CONFIG: writeSafeGatewayAuthConfig(tempHome), + }, + gatewayName: "nemoclaw", + hasOpenShellGatewayUserService: () => false, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: () => "", + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: startService, + verifySandboxBridgeGatewayReachableOrExit: async () => undefined, + }), + ).resolves.toBe(false); + + expect(startService).not.toHaveBeenCalled(); + } finally { fs.rmSync(tempHome, { recursive: true, force: true }); } }); @@ -77,6 +151,7 @@ describe("package-managed Docker-driver gateway env service", () => { const envFile = path.join(configHome, "openshell", "gateway.env"); const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(false); const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(tempHome); + const platformSpy = vi.spyOn(process, "platform", "get").mockReturnValue("linux"); try { await expect( @@ -113,6 +188,7 @@ describe("package-managed Docker-driver gateway env service", () => { } finally { existsSpy.mockRestore(); homedirSpy.mockRestore(); + platformSpy.mockRestore(); fs.rmSync(tempHome, { recursive: true, force: true }); } }); diff --git a/src/lib/onboard/docker-driver-gateway-env.ts b/src/lib/onboard/docker-driver-gateway-env.ts index 9755f47930a..19d9b43263a 100644 --- a/src/lib/onboard/docker-driver-gateway-env.ts +++ b/src/lib/onboard/docker-driver-gateway-env.ts @@ -28,6 +28,7 @@ import { export { getGatewayHttpsEndpoint, startPackageManagedDockerDriverGateway }; export const DOCKER_DRIVER_GATEWAY_RUNTIME_ENV_KEYS = [ + "DOCKER_HOST", "OPENSHELL_DRIVERS", "OPENSHELL_BIND_ADDRESS", "OPENSHELL_SERVER_PORT", @@ -245,9 +246,27 @@ function formatEnvironmentFileAssignment(key: string, value: string): string { if (/[\0\r\n]/.test(value)) { throw new Error(`Invalid OpenShell gateway env value for ${key}: contains a line break`); } + if (key === "DOCKER_HOST") { + const dockerHost = normalizePackageServiceDockerHost(value); + if (!dockerHost) throw new Error("Invalid empty DOCKER_HOST for the OpenShell gateway service"); + return `${key}='${dockerHost}'`; + } return `${key}=${value}`; } +function normalizePackageServiceDockerHost(value: string | undefined): string | undefined { + const candidate = String(value || "").trim(); + if (!candidate) return undefined; + const prefix = "unix://"; + const socketPath = candidate.startsWith(prefix) ? candidate.slice(prefix.length) : ""; + if (path.isAbsolute(socketPath) && !/[\0\r\n']/.test(socketPath)) { + return candidate; + } + throw new Error( + "Invalid DOCKER_HOST for the OpenShell gateway service; only safely serializable absolute unix:// Docker sockets are supported.", + ); +} + function readTextFileIfPresent(filePath: string): string { try { return fs.readFileSync(filePath, "utf-8"); @@ -319,7 +338,15 @@ export function startPackageManagedDockerDriverGatewayWithEnvOverride( hasOpenShellGatewayUserService: options.hasOpenShellGatewayUserService ?? (() => hasOpenShellGatewayUserService({ env, home: effectiveHome })), - prepareOpenShellGatewayUserServiceEnv: () => - writeDockerGatewayDebEnvOverrideFile(() => gatewayEnv, { env, home: effectiveHome }), + prepareOpenShellGatewayUserServiceEnv: () => { + const serviceGatewayEnv = { ...gatewayEnv }; + delete serviceGatewayEnv.DOCKER_HOST; + const dockerHost = normalizePackageServiceDockerHost(env.DOCKER_HOST); + if (dockerHost) serviceGatewayEnv.DOCKER_HOST = dockerHost; + writeDockerGatewayDebEnvOverrideFile(() => serviceGatewayEnv, { + env, + home: effectiveHome, + }); + }, }); } diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 1304ca63436..9d3b9782512 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -69,7 +69,13 @@ describe("docker-driver-gateway-service", () => { ); expect(hasOpenShellGatewayUserService({ existsSync, platform: "linux" })).toBe(true); - expect(hasOpenShellGatewayUserService({ existsSync, platform: "darwin" })).toBe(false); + expect( + hasOpenShellGatewayUserService({ + commandExists: () => false, + existsSync, + platform: "darwin", + }), + ).toBe(false); expect( hasOpenShellGatewayUserService({ commandExists: (command) => command === "brew", @@ -308,6 +314,21 @@ describe("docker-driver-gateway-service", () => { const events: string[] = []; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { events.push(args.join(" ")); + if (args.join(" ") === "services info --json openshell") { + return spawnResult( + 0, + "", + JSON.stringify([ + { + exit_code: 0, + loaded: true, + name: "openshell", + running: true, + status: "started", + }, + ]), + ); + } return spawnResult(); }); @@ -331,16 +352,151 @@ describe("docker-driver-gateway-service", () => { "list --formula openshell", "prepare-env", "services restart openshell", + "services info --json openshell", ]); }); + it("waits briefly for a restarted macOS Homebrew service to begin running", () => { + let statusChecks = 0; + const sleepSeconds = vi.fn(); + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + if (args.join(" ") !== "services info --json openshell") return spawnResult(); + statusChecks += 1; + return spawnResult( + 0, + "", + JSON.stringify([ + { + exit_code: statusChecks === 1 ? null : 0, + loaded: true, + name: "openshell", + running: statusChecks > 1, + status: "started", + }, + ]), + ); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds, + spawnSyncImpl, + }); + + expect(result).toMatchObject({ manager: "homebrew", started: true }); + expect(statusChecks).toBe(2); + expect(sleepSeconds).toHaveBeenCalledOnce(); + expect(sleepSeconds).toHaveBeenCalledWith(0.25); + }); + + it("rejects a macOS Homebrew service that exits after a successful restart", () => { + const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { + if (args.join(" ") === "services info --json openshell") { + return spawnResult( + 0, + "", + JSON.stringify([ + { + exit_code: 1, + loaded: true, + name: "openshell", + running: false, + status: "error", + }, + ]), + ); + } + return spawnResult(); + }); + + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds: vi.fn(), + spawnSyncImpl, + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + }); + expect(result.reason).toMatch(/not running.*status=error.*exit_code=1/); + }); + + it("rechecks Homebrew service liveness before the sandbox bridge probe", async () => { + const verifySandboxBridgeGatewayReachableOrExit = vi.fn(); + + await expect( + startPackageManagedDockerDriverGateway({ + clearDockerDriverGatewayRuntimeFiles: vi.fn(), + exitOnFailure: false, + gatewayName: "nemoclaw", + getHomebrewServiceRunningState: () => ({ + ok: false, + reason: "brew services info --json openshell reports exit_code=1", + }), + hasOpenShellGatewayUserService: () => true, + healthPollCount: 1, + healthPollInterval: 0, + isDockerDriverGatewayReady: async () => true, + registerDockerDriverGatewayEndpoint: () => true, + runCaptureOpenshell: (args) => (args[0] === "status" ? STATUS_CONNECTED : GATEWAY_INFO), + skipSandboxBridgeReachability: false, + startOpenShellGatewayUserService: () => ({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + started: true, + statusCommand: "brew services info openshell", + }), + verifySandboxBridgeGatewayReachableOrExit, + }), + ).rejects.toThrow(/service stopped after startup.*exit_code=1/); + + expect(verifySandboxBridgeGatewayReachableOrExit).not.toHaveBeenCalled(); + }); + + it.each([ + "not json", + "[]", + ])("fails closed when Homebrew service status is unusable: %s", (stdout) => { + const result = startOpenShellGatewayUserService({ + commandExists: (command) => command === "brew", + env: {}, + platform: "darwin", + sleepSeconds: vi.fn(), + spawnSyncImpl: vi.fn((_command: string, args: string[]) => + args.join(" ") === "services info --json openshell" + ? spawnResult(0, "", stdout) + : spawnResult(), + ), + }); + + expect(result).toMatchObject({ + attempted: true, + fallbackAllowed: false, + manager: "homebrew", + serviceName: "openshell", + started: false, + }); + expect(result.reason).toContain("brew services info --json openshell"); + }); + it("does not fall back when the macOS Homebrew service restart fails", () => { const result = startOpenShellGatewayUserService({ commandExists: (command) => command === "brew", env: {}, platform: "darwin", spawnSyncImpl: vi.fn((_command: string, args: string[]) => - args[0] === "services" ? spawnResult(1, "launchctl failed") : spawnResult(), + args.join(" ") === "services restart openshell" + ? spawnResult(1, "launchctl failed") + : spawnResult(), ), }); diff --git a/src/lib/onboard/docker-driver-gateway-service.ts b/src/lib/onboard/docker-driver-gateway-service.ts index 7368e223d2b..2291eb7437f 100644 --- a/src/lib/onboard/docker-driver-gateway-service.ts +++ b/src/lib/onboard/docker-driver-gateway-service.ts @@ -6,7 +6,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { sleepSeconds, waitUntilAsync } from "../core/wait"; +import { sleepSeconds, waitUntil, waitUntilAsync } from "../core/wait"; import { isGatewayHealthy } from "../state/gateway"; import { envInt } from "./env"; import { @@ -20,6 +20,8 @@ export const OPENSHELL_GATEWAY_HOMEBREW_SERVICE = "openshell"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER = "NEMOCLAW_MANAGED_OPENSHELL_GATEWAY=1"; export const NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER_LINE = `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}`; +const HOMEBREW_SERVICE_STATUS_POLL_ATTEMPTS = 5; +const HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS = 0.25; export interface OpenShellGatewayUserServiceOptions { commandExists?: (command: string) => boolean; @@ -29,6 +31,7 @@ export interface OpenShellGatewayUserServiceOptions { platform?: NodeJS.Platform; prepareServiceEnv?: () => void; readFileSync?: (filePath: string, encoding: BufferEncoding) => string; + sleepSeconds?: (seconds: number) => void; spawnSyncImpl?: SpawnSyncLike; } @@ -84,6 +87,7 @@ export interface PackageManagedDockerDriverGatewayOptions { clearDockerDriverGatewayRuntimeFiles: () => void; exitOnFailure: boolean; gatewayName: string; + getHomebrewServiceRunningState?: () => { ok: boolean; reason?: string }; hasOpenShellGatewayUserService?: () => boolean; healthPollCount?: number; healthPollInterval?: number; @@ -344,6 +348,75 @@ function runBrew( return { ok: true, stdout: text(result.stdout) }; } +function parseHomebrewServiceRunningState( + output: string, + serviceName: string, +): { ok: boolean; reason?: string } { + let parsed: unknown; + try { + parsed = JSON.parse(output); + } catch { + return { ok: false, reason: "returned invalid JSON" }; + } + if (!Array.isArray(parsed)) return { ok: false, reason: "returned a non-array response" }; + const service = parsed.find( + (entry): entry is Record => + typeof entry === "object" && entry !== null && entry.name === serviceName, + ); + if (!service) return { ok: false, reason: `did not report service ${serviceName}` }; + if (service.loaded === true && service.running === true) return { ok: true }; + return { + ok: false, + reason: `${serviceName} is not running (loaded=${String(service.loaded ?? "")}, running=${String(service.running ?? "")}, status=${String(service.status ?? "")}, exit_code=${String(service.exit_code ?? "")})`, + }; +} + +function readHomebrewServiceRunningState( + opts: Pick & { + serviceName?: string; + } = {}, +): { ok: boolean; reason?: string } { + const env = opts.env ?? process.env; + const spawnSyncImpl = opts.spawnSyncImpl ?? spawnSync; + const serviceName = opts.serviceName ?? OPENSHELL_GATEWAY_HOMEBREW_SERVICE; + const statusArgs = ["services", "info", "--json", serviceName]; + const status = runBrew(statusArgs, { env, spawnSyncImpl }); + if (!status.ok) { + return { ok: false, reason: `brew ${statusArgs.join(" ")} failed: ${status.reason}` }; + } + const running = parseHomebrewServiceRunningState(status.stdout ?? "", serviceName); + if (!running.ok) { + return { ok: false, reason: `brew ${statusArgs.join(" ")} ${running.reason}` }; + } + return { ok: true }; +} + +function waitForHomebrewServiceRunning( + opts: Pick & { + serviceName?: string; + } = {}, +): { ok: boolean; reason?: string } { + const sleepSecondsImpl = opts.sleepSeconds ?? sleepSeconds; + let latest: { ok: boolean; reason?: string } = { + ok: false, + reason: "Homebrew service status was not checked", + }; + const running = waitUntil( + () => { + latest = readHomebrewServiceRunningState(opts); + return latest.ok; + }, + { + backoffFactor: 1, + initialIntervalMs: HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS * 1000, + maxAttempts: HOMEBREW_SERVICE_STATUS_POLL_ATTEMPTS, + maxIntervalMs: HOMEBREW_SERVICE_STATUS_POLL_INTERVAL_SECONDS * 1000, + sleep: (ms) => sleepSecondsImpl(ms / 1000), + }, + ); + return running ? { ok: true } : latest; +} + function parseSystemctlShowProperties(output: string): Record { const properties: Record = {}; for (const line of output.split(/\r?\n/)) { @@ -645,6 +718,24 @@ export function startOpenShellGatewayUserService( }; } + const running = waitForHomebrewServiceRunning({ + env, + serviceName: service.serviceName, + sleepSeconds: opts.sleepSeconds, + spawnSyncImpl, + }); + if (!running.ok) { + return { + attempted: true, + fallbackAllowed: false, + manager: service.manager, + reason: running.reason, + serviceName: service.serviceName, + started: false, + statusCommand: service.statusCommand, + }; + } + return { attempted: true, fallbackAllowed: false, @@ -761,6 +852,8 @@ export async function startPackageManagedDockerDriverGateway({ clearDockerDriverGatewayRuntimeFiles, exitOnFailure, gatewayName, + getHomebrewServiceRunningState: + getHomebrewServiceRunningStateImpl = readHomebrewServiceRunningState, hasOpenShellGatewayUserService: hasOpenShellGatewayUserServiceImpl = hasOpenShellGatewayUserService, healthPollCount, @@ -831,6 +924,17 @@ export async function startPackageManagedDockerDriverGateway({ return cliHealthy || grpcHealthy; }, waitOptions)); if (healthy) { + if (serviceStart.manager === "homebrew") { + const running = getHomebrewServiceRunningStateImpl(); + if (!running.ok) { + const detail = running.reason ? ` (${running.reason})` : ""; + const message = `OpenShell gateway service stopped after startup${detail}.`; + console.error(` ${message}`); + console.error(` Check: ${serviceStart.statusCommand}`); + if (exitOnFailure) process.exit(1); + throw new Error(message); + } + } clearDockerDriverGatewayRuntimeFiles(); await verifySandboxBridgeGatewayReachableOrExit(exitOnFailure, { skip: skipSandboxBridgeReachability, From fac3cd786ce35602f148b5083462a514cfab7120 Mon Sep 17 00:00:00 2001 From: San Dang Date: Wed, 15 Jul 2026 23:33:03 +0700 Subject: [PATCH 23/24] test(ci): keep service checks linear Signed-off-by: San Dang --- .../docker-driver-gateway-service.test.ts | 89 +++++++++---------- test/installer-hash-check.test.ts | 16 ++-- 2 files changed, 49 insertions(+), 56 deletions(-) diff --git a/src/lib/onboard/docker-driver-gateway-service.test.ts b/src/lib/onboard/docker-driver-gateway-service.test.ts index 9d3b9782512..107d0f55af7 100644 --- a/src/lib/onboard/docker-driver-gateway-service.test.ts +++ b/src/lib/onboard/docker-driver-gateway-service.test.ts @@ -56,6 +56,30 @@ function spawnResult(status = 0, stderr = "", stdout = ""): SpawnSyncLikeResult }; } +function homebrewServiceStatusResult({ + exitCode = 0, + running = true, + status = "started", +}: { + exitCode?: number | null; + running?: boolean; + status?: string; +} = {}): SpawnSyncLikeResult { + return spawnResult( + 0, + "", + JSON.stringify([ + { + exit_code: exitCode, + loaded: true, + name: "openshell", + running, + status, + }, + ]), + ); +} + function homeEnv(home: string, xdgConfigHome = ""): NodeJS.ProcessEnv { return { HOME: home, XDG_CONFIG_HOME: xdgConfigHome } as NodeJS.ProcessEnv; } @@ -313,23 +337,11 @@ describe("docker-driver-gateway-service", () => { it("restarts the macOS Homebrew gateway service", () => { const events: string[] = []; const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - events.push(args.join(" ")); - if (args.join(" ") === "services info --json openshell") { - return spawnResult( - 0, - "", - JSON.stringify([ - { - exit_code: 0, - loaded: true, - name: "openshell", - running: true, - status: "started", - }, - ]), - ); - } - return spawnResult(); + const command = args.join(" "); + events.push(command); + return command === "services info --json openshell" + ? homebrewServiceStatusResult() + : spawnResult(); }); const result = startOpenShellGatewayUserService({ @@ -360,21 +372,15 @@ describe("docker-driver-gateway-service", () => { let statusChecks = 0; const sleepSeconds = vi.fn(); const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - if (args.join(" ") !== "services info --json openshell") return spawnResult(); - statusChecks += 1; - return spawnResult( - 0, - "", - JSON.stringify([ - { - exit_code: statusChecks === 1 ? null : 0, - loaded: true, - name: "openshell", - running: statusChecks > 1, - status: "started", - }, - ]), - ); + const isStatusCheck = args.join(" ") === "services info --json openshell"; + const result = isStatusCheck + ? homebrewServiceStatusResult({ + exitCode: statusChecks === 0 ? null : 0, + running: statusChecks > 0, + }) + : spawnResult(); + statusChecks += Number(isStatusCheck); + return result; }); const result = startOpenShellGatewayUserService({ @@ -393,22 +399,9 @@ describe("docker-driver-gateway-service", () => { it("rejects a macOS Homebrew service that exits after a successful restart", () => { const spawnSyncImpl = vi.fn((_command: string, args: string[]) => { - if (args.join(" ") === "services info --json openshell") { - return spawnResult( - 0, - "", - JSON.stringify([ - { - exit_code: 1, - loaded: true, - name: "openshell", - running: false, - status: "error", - }, - ]), - ); - } - return spawnResult(); + return args.join(" ") === "services info --json openshell" + ? homebrewServiceStatusResult({ exitCode: 1, running: false, status: "error" }) + : spawnResult(); }); const result = startOpenShellGatewayUserService({ diff --git a/test/installer-hash-check.test.ts b/test/installer-hash-check.test.ts index c16dec7fa2f..ebdc1b1a490 100644 --- a/test/installer-hash-check.test.ts +++ b/test/installer-hash-check.test.ts @@ -480,14 +480,11 @@ function renderPinFunction( function replacePinFunction( source: string, functionName: string, - nextFunctionName: string, + nextMarker: string, replacement: string, ): string { const start = source.indexOf(`${functionName}() {`); - let next = source.indexOf(`\n${nextFunctionName}() {`, start); - if (next === -1) { - next = source.indexOf(`\n${nextFunctionName}`, start); - } + const next = source.indexOf(`\n${nextMarker}`, start); expect(start, `${functionName} template start`).not.toBe(-1); expect(next, `${functionName} template end`).not.toBe(-1); return `${source.slice(0, start)}${replacement}${source.slice(next)}`; @@ -510,7 +507,7 @@ function renderInstallerTemplate( const withArchivePinFunction = replacePinFunction( selected, "openshell_pinned_sha256", - "openshell_checksum_line", + "openshell_checksum_line() {", pinFunction, ); const withPinFunction = replacePinFunction( @@ -540,7 +537,7 @@ function renderBrevTemplate(openshellVersion: string, pinFunction: string): stri return replacePinFunction( selected, "openshell_cli_pinned_sha256", - "openshell_checksum_line", + "openshell_checksum_line() {", pinFunction, ); } @@ -655,7 +652,10 @@ case "\${1:-}" in printf '%s %s\\n' '${FORMULA_DIGEST}' "$1" ;; *) - /usr/bin/sha256sum "$@" + case "$(uname -s)" in + Darwin) /usr/bin/shasum -a 256 "$@" ;; + *) /usr/bin/sha256sum "$@" ;; + esac ;; esac `, From dc2b685d5bf47faffd59b77601805f39b43eb4f9 Mon Sep 17 00:00:00 2001 From: San Dang Date: Thu, 16 Jul 2026 00:25:06 +0700 Subject: [PATCH 24/24] test(docs): align reboot recovery platform paths Signed-off-by: San Dang --- test/reboot-recovery-docs.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/reboot-recovery-docs.test.ts b/test/reboot-recovery-docs.test.ts index 4f317150c86..620379aa069 100644 --- a/test/reboot-recovery-docs.test.ts +++ b/test/reboot-recovery-docs.test.ts @@ -20,12 +20,13 @@ function section(markdown: string, heading: string): string { } describe("reboot recovery documentation", () => { - it("routes Linux users through the managed OpenShell service before onboard resume", () => { + it("routes macOS and Linux through managed OpenShell services before onboard resume", () => { const reboot = section(troubleshooting, "### Reconnect after a host reboot"); + expect(reboot).toContain("brew services restart openshell"); expect(reboot).toContain("openshell-gateway.service"); expect(reboot).toContain("systemctl --user restart openshell-gateway"); - expect(reboot).toContain("macOS, non-systemd Linux hosts"); + expect(reboot).toContain("non-systemd Linux hosts"); expect(reboot.indexOf("systemctl --user restart openshell-gateway")).toBeLessThan( reboot.indexOf("$$nemoclaw onboard --resume"), );