Skip to content
Merged
179 changes: 179 additions & 0 deletions src/lib/actions/uninstall/run-plan-homebrew-openshell.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// 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 {
type RunResult,
runUninstallPlan as runUninstallPlanBase,
type UninstallRunDeps,
type UninstallRunOptions,
} from "./run-plan";

const FORMULA = "nvidia/openshell/openshell";
const OPENSHELL_EXECUTABLES = new Set([
"openshell",
"openshell-gateway",
"openshell-sandbox",
"openshell-driver-vm",
]);

/** Executables only: the OpenShell config directory shares the `openshell` name. */
function isOpenShellExecutablePath(target: string): boolean {
return (
OPENSHELL_EXECUTABLES.has(path.basename(target)) &&
path.basename(path.dirname(target)) === "bin"
);
}

function removedOpenShellExecutables(removed: string[]): string[] {
return removed.filter(isOpenShellExecutablePath);
}

function ok(stdout = ""): RunResult {
return { status: 0, stdout, stderr: "" };
}

function runUninstallPlan(options: UninstallRunOptions, deps: UninstallRunDeps) {
return runUninstallPlanBase(options, {
resolveGatewayTeardownAuthority: ({ gatewayName, gatewayPort }) => ({
gatewayName,
gatewayPort,
mode: "nemoclaw-managed",
source: gatewayPort === 8080 ? "packaged-service" : "standalone",
endpoint: null,
stateDir: null,
supervisor: null,
requiredCapabilities: [],
}),
...deps,
});
}

/**
* Run a full uninstall and record every host command.
*
* `brewListStatus` decides whether Homebrew reports the NemoClaw formula as
* installed, which is the guard that keeps an unrelated OpenShell installed.
*/
function uninstallWithHomebrew(options: {
brewInstalled: boolean;
brewListStatus?: number;
brewUninstallStatus?: number;
platform: NodeJS.Platform;
}): { calls: string[][]; logs: string[]; removed: string[]; warnings: string[] } {
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-uninstall-brew-"));
// removeFileWithOptionalSudo probes the real parent directory for write
// access, so the XDG bin directory must exist for a deletion to be reachable.
fs.mkdirSync(path.join(tmpHome, ".local", "bin"), { recursive: true });
const calls: string[][] = [];
const logs: string[] = [];
const removed: string[] = [];
const warnings: string[] = [];
// Report every managed OpenShell executable as present so a deletion is
// observable; asserting only the brew argv cannot see a path unlink.
const isOpenShellExecutable = (target: string): boolean =>
isOpenShellExecutablePath(String(target));
try {
runUninstallPlan(
{ assumeYes: true, deleteModels: false, keepOpenShell: false },
{
commandExists: (command) =>
command === "brew" ? options.brewInstalled : command === "openshell",
env: { HOME: tmpHome } as NodeJS.ProcessEnv,
existsSync: (target) => isOpenShellExecutable(target),
isTty: false,
log: (line) => logs.push(line),
platform: options.platform,
rmSync: vi.fn((target: Parameters<typeof fs.rmSync>[0]) => {
removed.push(String(target));
}),
run: (command, args) => {
calls.push([command, ...args]);
if (command === "brew" && args[0] === "list") {
return { status: options.brewListStatus ?? 0, stdout: "", stderr: "" };
}
if (command === "brew" && args[0] === "uninstall") {
return { status: options.brewUninstallStatus ?? 0, stdout: "", stderr: "" };
}
if (command === "openshell" && args[0] === "gateway" && args[1] === "list") {
return ok(JSON.stringify([{ name: "nemoclaw" }]));
}
return ok();
},
// buildRuntime wires runtime.warn from deps.error.
error: (line) => warnings.push(line),
runDocker: () => ok(""),
},
);
} finally {
fs.rmSync(tmpHome, { recursive: true, force: true });
}
return { calls, logs, removed, warnings };
}

function brewArgs(calls: string[][]): string[][] {
return calls.filter((call) => call[0] === "brew");
}

describe("uninstall Homebrew-managed OpenShell", () => {
it("removes the managed formula so no executable stays linked in the Homebrew prefix (#8882)", () => {
const { calls, logs, removed } = uninstallWithHomebrew({
brewInstalled: true,
platform: "darwin",
});

expect(brewArgs(calls)).toEqual([
["brew", "list", "--formula", FORMULA],
["brew", "uninstall", "--formula", FORMULA],
]);
expect(logs).toContain(`Removed Homebrew formula ${FORMULA}`);
expect(removedOpenShellExecutables(removed)).not.toEqual([]);
});

it("keeps an OpenShell that Homebrew did not install from the NemoClaw tap (#8882)", () => {
// A non-zero `brew list` means the fully qualified formula is absent, so an
// OpenShell from another tap or a manual build must survive the uninstall.
const { calls, logs, removed } = uninstallWithHomebrew({
brewInstalled: true,
brewListStatus: 1,
platform: "darwin",
});

expect(brewArgs(calls)).toEqual([["brew", "list", "--formula", FORMULA]]);
expect(logs).not.toContain(`Removed Homebrew formula ${FORMULA}`);
// The ownership decision must also stop the path deletion, or an executable
// owned by another tap is unlinked from /usr/local/bin anyway.
expect(removedOpenShellExecutables(removed)).toEqual([]);
});

it("names the manual command when the formula removal fails (#8882)", () => {
const { removed, warnings } = uninstallWithHomebrew({
brewInstalled: true,
brewUninstallStatus: 1,
platform: "darwin",
});

expect(warnings.join("\n")).toContain(`brew uninstall ${FORMULA}`);
// A stranded formula must keep its executables, not lose them to the loop.
expect(removedOpenShellExecutables(removed)).toEqual([]);
});

it("does not call Homebrew on a platform that installs OpenShell directly (#8882)", () => {
const { calls, removed } = uninstallWithHomebrew({ brewInstalled: true, platform: "linux" });

expect(brewArgs(calls)).toEqual([]);
expect(removedOpenShellExecutables(removed)).not.toEqual([]);
});

it("does not call Homebrew when it is absent from the host (#8882)", () => {
const { calls, removed } = uninstallWithHomebrew({ brewInstalled: false, platform: "darwin" });

expect(brewArgs(calls)).toEqual([]);
expect(removedOpenShellExecutables(removed)).not.toEqual([]);
});
});
78 changes: 66 additions & 12 deletions src/lib/actions/uninstall/run-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,68 @@ function runOptional(
return false;
}

// scripts/install-openshell.sh installs OpenShell on macOS through this
// Homebrew formula, so the executables in the Homebrew prefix are formula
// symlinks rather than files NemoClaw wrote. Deleting those paths would leave
// the formula registered and the Cellar populated, so remove the formula. The
// fully qualified name keeps an OpenShell from any other tap untouched. (#8882)
const OPENSHELL_HOMEBREW_FORMULA = "nvidia/openshell/openshell";

/**
* Remove the NemoClaw-managed formula and report whether the caller may also
* delete the OpenShell executable paths.
*
* Returns "stop" when this host has an OpenShell that the NemoClaw tap does not
* own, or when the formula removal failed. Deleting the paths in either case
* would unlink another tap's executable or strand a still-registered formula.
*/
function removeHomebrewOpenShellFormula(runtime: UninstallRuntime): "continue" | "stop" {
if (runtime.platform !== "darwin") return "continue";
if (!runtime.commandExists("brew")) return "continue";
const installed = runtime.run("brew", ["list", "--formula", OPENSHELL_HOMEBREW_FORMULA], {
env: runtime.env,
stdio: "ignore",
});
if (installed.status !== 0) {
runtime.log(`Keeping OpenShell executables that ${OPENSHELL_HOMEBREW_FORMULA} does not own.`);
return "stop";
}
const removed = runtime.run("brew", ["uninstall", "--formula", OPENSHELL_HOMEBREW_FORMULA], {
env: runtime.env,
stdio: "ignore",
});
if (removed.status === 0) {
runtime.log(`Removed Homebrew formula ${OPENSHELL_HOMEBREW_FORMULA}`);
return "continue";
}
runtime.warn(
`Failed to remove Homebrew formula ${OPENSHELL_HOMEBREW_FORMULA}; kept its executables. Run: brew uninstall ${OPENSHELL_HOMEBREW_FORMULA}`,
);
return "stop";
}

/** Apply every reason to keep managed OpenShell executables, then remove them. */
function removeManagedOpenShellExecutables(
paths: UninstallPaths,
runtime: UninstallRuntime,
reasons: { externallySupervised: boolean; keepOpenShell: boolean },
): void {
if (reasons.keepOpenShell || reasons.externallySupervised) {
runtime.log(
reasons.externallySupervised
? "Keeping OpenShell binaries used by the externally supervised gateway."
: "Keeping OpenShell binaries as requested.",
);
return;
}
if (GATEWAY_PORT !== DEFAULT_GATEWAY_PORT) {
runtime.log("Keeping OpenShell binaries used by the default gateway service.");
return;
}
if (removeHomebrewOpenShellFormula(runtime) !== "continue") return;
for (const target of paths.openshellInstallPaths) removeFileWithOptionalSudo(target, runtime);
}

function deleteSelectedGatewaySandbox(runtime: UninstallRuntime, sandboxName: string): boolean {
const result = runtime.run("openshell", ["sandbox", "delete", sandboxName], {
env: runtime.env,
Expand Down Expand Up @@ -2200,18 +2262,10 @@ function executePlan(
removeManagedSwap(paths, runtime, scopedToSelectedGateway);
if (!scopedToSelectedGateway) {
for (const pattern of paths.runtimeTempGlobs) removeGlob(pattern, runtime);
if (options.keepOpenShell || externallySupervised) {
runtime.log(
externallySupervised
? "Keeping OpenShell binaries used by the externally supervised gateway."
: "Keeping OpenShell binaries as requested.",
);
} else if (GATEWAY_PORT !== DEFAULT_GATEWAY_PORT) {
runtime.log("Keeping OpenShell binaries used by the default gateway service.");
} else {
for (const target of paths.openshellInstallPaths)
removeFileWithOptionalSudo(target, runtime);
}
removeManagedOpenShellExecutables(paths, runtime, {
externallySupervised,
keepOpenShell: options.keepOpenShell,
});
} else {
runtime.log("Sibling gateways remain; kept shared runtime files and OpenShell binaries.");
}
Expand Down
Loading