Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion docs/reference/commands.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1779,7 +1779,12 @@ NemoClaw preserves the per-gateway PID file and runtime marker so you can inspec
Stop only the listener that matches the target gateway, then rerun `destroy` to converge cleanup.
When the default-port gateway runs under the packaged OpenShell gateway service, gateway cleanup stops that service before it reaps host processes, so the gateway port is released instead of being rebound by the service manager.
The service is stopped, not disabled or removed, and the next onboarding run starts it again.
If the service cannot be stopped, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal.
On headless Linux, the packaged service can exist while its `systemd` user manager is unavailable and the gateway runs through the standalone fallback.
For this recognized manager-unavailable failure only, `destroy` uses the per-gateway PID file when the service is not enabled for automatic activation.
If the recorded PID is live, its command line must match the exact gateway name and port before `destroy` stops it.
If the recorded process has exited, `destroy` continues only after it verifies that the gateway port is free.
If a live PID does not prove gateway ownership or the port remains occupied, `destroy` exits non-zero and preserves the runtime evidence for inspection.
For any other service stop failure, `destroy` exits non-zero after sandbox and registry deletion, prints the status command for the service, and skips gateway and volume removal.
If the OpenShell gateway is unreachable and the sandbox has no managed MCP ownership state, `--force` removes only NemoClaw's local registry entry and local artifacts.
Gateway-side deletion remains unconfirmed, shared host-service and gateway teardown are skipped, and the sandbox and retained volume may still exist if the gateway returns.
Start the gateway with `$$nemoclaw <name> status` and retry destroy when you need a confirmed deletion.
Expand Down
131 changes: 130 additions & 1 deletion src/lib/actions/sandbox/destroy-gateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,10 @@ function packagedServiceOwner({
};
}

function serviceStopResult(stopped: boolean, reason?: string) {
function serviceStopResult(stopped: boolean, reason?: string, standaloneFallbackAllowed = false) {
return {
attempted: true,
standaloneFallbackAllowed,
manager: "systemd" as const,
serviceName: "nemoclaw-openshell-gateway",
statusCommand: "systemctl --user status nemoclaw-openshell-gateway",
Expand Down Expand Up @@ -344,6 +345,134 @@ describe("cleanupGatewayAfterLastSandbox", () => {
expect(mocks.dockerRemoveVolumesByPrefix).not.toHaveBeenCalled();
});

it("stops the recorded standalone gateway when the systemd user manager is unavailable", () => {
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(os, "homedir").mockReturnValue("/home/tester");
mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner);
mocks.stopHostGatewayProcesses.mockReturnValueOnce({
...idleHostReaperResult(),
stopped: [4242],
});
const clearGatewayRuntimeFiles = vi.fn();
const isGatewayPortFree = vi.fn(() => true);
const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" }));

cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, {
clearGatewayRuntimeFiles,
isGatewayPortFree,
stopOpenShellGatewayUserService: () =>
serviceStopResult(
false,
"systemctl --user stop failed: Failed to connect to bus: No medium found",
true,
),
});

expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledWith(
{},
expect.objectContaining({
clearRuntimeFiles: false,
openShellGatewayName: "nemoclaw",
openShellGatewayPort: 8080,
usePgrepFallback: false,
}),
);
expect(isGatewayPortFree).toHaveBeenCalledWith(8080);
expect(clearGatewayRuntimeFiles).toHaveBeenCalledWith(
"/home/tester/.local/state/nemoclaw/openshell-docker-gateway",
"/home/tester/.local/state/nemoclaw/openshell-docker-gateway/openshell-gateway.pid",
);
expect(runOpenshell).toHaveBeenCalledWith(["gateway", "remove", "nemoclaw"], {
ignoreError: true,
stdio: ["ignore", "pipe", "pipe"],
});
});

it("fails closed when a headless service stop has no recorded standalone owner", () => {
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(os, "homedir").mockReturnValue("/home/tester");
mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner);
const isGatewayPortFree = vi.fn(() => true);
const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" }));

expect(() =>
cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, {
isGatewayPortFree,
stopOpenShellGatewayUserService: () =>
serviceStopResult(false, "Failed to connect to bus: No medium found", true),
}),
).toThrow(/no recorded standalone gateway process proved ownership/);
expect(isGatewayPortFree).not.toHaveBeenCalled();
expect(runOpenshell).not.toHaveBeenCalledWith(
["gateway", "remove", "nemoclaw"],
expect.anything(),
);
});

it("fails closed when the gateway port stays occupied after headless fallback cleanup", () => {
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(os, "homedir").mockReturnValue("/home/tester");
mocks.resolveGatewayTeardownAuthority.mockImplementationOnce(packagedServiceOwner);
mocks.stopHostGatewayProcesses.mockReturnValueOnce({
...idleHostReaperResult(),
stopped: [4242],
});
const clearGatewayRuntimeFiles = vi.fn();
const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" }));

expect(() =>
cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, {
clearGatewayRuntimeFiles,
isGatewayPortFree: () => false,
stopOpenShellGatewayUserService: () =>
serviceStopResult(false, "Failed to connect to bus: No medium found", true),
}),
).toThrow(/gateway port 8080 remains occupied/);
expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled();
expect(runOpenshell).not.toHaveBeenCalledWith(
["gateway", "remove", "nemoclaw"],
expect.anything(),
);
});

it("retries headless fallback cleanup after volume removal fails", () => {
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(os, "homedir").mockReturnValue("/home/tester");
mocks.resolveGatewayTeardownAuthority.mockImplementation(packagedServiceOwner);
mocks.stopHostGatewayProcesses
.mockReturnValueOnce({
...idleHostReaperResult(),
stopped: [4242],
})
.mockReturnValueOnce({
...idleHostReaperResult(),
skippedDeadPids: [4242],
});
mocks.dockerRemoveVolumesByPrefix.mockImplementationOnce(() => {
throw new Error("injected volume cleanup failure");
});
const clearGatewayRuntimeFiles = vi.fn();
const isGatewayPortFree = vi.fn(() => true);
const runOpenshell = vi.fn(() => ({ status: 0, stdout: "", stderr: "" }));
const deps = {
clearGatewayRuntimeFiles,
isGatewayPortFree,
stopOpenShellGatewayUserService: () =>
serviceStopResult(false, "Failed to connect to bus: No medium found", true),
};

expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).toThrow(
"injected volume cleanup failure",
);
expect(clearGatewayRuntimeFiles).not.toHaveBeenCalled();

expect(() => cleanupGatewayAfterLastSandbox("nemoclaw", runOpenshell, deps)).not.toThrow();
expect(mocks.stopHostGatewayProcesses).toHaveBeenCalledTimes(2);
expect(isGatewayPortFree).toHaveBeenCalledTimes(2);
expect(clearGatewayRuntimeFiles).toHaveBeenCalledOnce();
expect(mocks.dockerRemoveVolumesByPrefix).toHaveBeenCalledTimes(2);
});

it("leaves the service manager alone for a standalone NemoClaw gateway (#7904)", () => {
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
vi.spyOn(os, "homedir").mockReturnValue("/home/tester");
Expand Down
56 changes: 51 additions & 5 deletions src/lib/actions/sandbox/destroy-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ import {
type GatewayTeardownAuthorityResolver,
resolveGatewayTeardownAuthority,
} from "../../onboard/gateway-teardown-authority";
import { stopHostGatewayProcesses } from "../../onboard/host-gateway-process";
import {
clearHostGatewayRuntimeFiles,
isHostPortFree,
stopHostGatewayProcesses,
} from "../../onboard/host-gateway-process";
import { stopStaleDashboardListeners } from "../../onboard/stale-gateway-cleanup";

export type DestroyRunOpenshell = (
Expand All @@ -28,6 +32,8 @@ export type DestroyRunOpenshell = (
const DASHBOARD_FORWARD_PORT = String(DASHBOARD_PORT);

export interface CleanupGatewayDeps {
clearGatewayRuntimeFiles?: typeof clearHostGatewayRuntimeFiles;
isGatewayPortFree?: typeof isHostPortFree;
resolveGatewayTeardownAuthority?: GatewayTeardownAuthorityResolver;
stopOpenShellGatewayUserService?: typeof stopOpenShellGatewayUserService;
}
Expand Down Expand Up @@ -107,14 +113,19 @@ export function cleanupGatewayAfterLastSandbox(
// ports the live openshell tracks; this catches orphans whose openshell
// record was lost across upgrades or failed onboards.
stopStaleDashboardListeners();
let packagedServiceFallbackReason: string | null = null;
if (!externallySupervised && owner.source === "packaged-service") {
const stopService = deps.stopOpenShellGatewayUserService ?? stopOpenShellGatewayUserService;
const serviceStop = stopService();
if (serviceStop.attempted && !serviceStop.stopped) {
throw new Error(
`Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` +
`Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`,
);
if (serviceStop.standaloneFallbackAllowed) {
packagedServiceFallbackReason = serviceStop.reason ?? "user service manager unavailable";
} else {
throw new Error(
`Failed to stop the packaged OpenShell gateway service '${serviceStop.serviceName}' that owns gateway '${gatewayName}': ${serviceStop.reason}. ` +
`Check: ${serviceStop.statusCommand}. Stop the service, then rerun destroy.`,
);
}
}
}
if (!externallySupervised && (process.platform === "linux" || process.platform === "darwin")) {
Expand All @@ -132,6 +143,7 @@ export function cleanupGatewayAfterLastSandbox(
openShellGatewayPort?: number;
preserveRuntimeFilesOnNonMatching: true;
usePgrepFallback: false;
clearRuntimeFiles?: boolean;
stateDir?: string;
pidFile?: string;
} = {
Expand All @@ -142,6 +154,16 @@ export function cleanupGatewayAfterLastSandbox(
stopOptions.pidFile = path.join(perGatewayState.stateDir, "openshell-gateway.pid");
stopOptions.openShellGatewayName = gatewayName;
stopOptions.openShellGatewayPort = perGatewayState.port;
if (packagedServiceFallbackReason !== null) {
// A package can be installed even when its user manager is unavailable.
// Destroy cannot repair the missing systemd user session. Remove this
// branch when supported onboarding no longer starts a standalone gateway
// after this service-manager failure.
// In that exact start fallback, the standalone launcher wrote this
// per-gateway PID evidence. Preserve it until every later cleanup step
// succeeds so a retry can prove the same ownership again.
stopOptions.clearRuntimeFiles = false;
}
const stopResult = stopHostGatewayProcesses({}, stopOptions);
const unverifiablePids = [...new Set(stopResult.skippedNonMatchingPids)];
if (unverifiablePids.length > 0) {
Expand All @@ -159,6 +181,23 @@ export function cleanupGatewayAfterLastSandbox(
`Failed to stop the owned host gateway process(es) for '${gatewayName}': ${failedPids.join(", ")}.${remediation}`,
);
}
if (packagedServiceFallbackReason !== null) {
const ownedStandalonePidProven =
stopResult.stopped.length > 0 || stopResult.skippedDeadPids.length > 0;
if (!ownedStandalonePidProven) {
throw new Error(
`Failed to stop the packaged OpenShell gateway service for '${gatewayName}' because ${packagedServiceFallbackReason}, and no recorded standalone gateway process proved ownership. ` +
"Restore the user service manager or stop the verified gateway listener, then rerun destroy.",
);
}
const portFree = deps.isGatewayPortFree ?? isHostPortFree;
if (!portFree(perGatewayState.port)) {
throw new Error(
`Refusing cleanup because gateway port ${String(perGatewayState.port)} remains occupied after the recorded standalone gateway process for '${gatewayName}' exited or was stopped. ` +
"Inspect the remaining listener, stop only the matching gateway process, then rerun destroy.",
);
}
}
}
/**
* SOURCE_OF_TRUTH
Expand Down Expand Up @@ -206,4 +245,11 @@ export function cleanupGatewayAfterLastSandbox(
dockerRemoveVolumesByPrefix(`openshell-cluster-${gatewayName}`, {
ignoreError: true,
});
if (packagedServiceFallbackReason !== null) {
const clearRuntimeFiles = deps.clearGatewayRuntimeFiles ?? clearHostGatewayRuntimeFiles;
clearRuntimeFiles(
perGatewayState.stateDir,
path.join(perGatewayState.stateDir, "openshell-gateway.pid"),
);
}
}
48 changes: 48 additions & 0 deletions src/lib/onboard/docker-driver-gateway-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ describe("docker-driver-gateway-service", () => {

expect(result).toEqual({
attempted: true,
standaloneFallbackAllowed: false,
manager: "systemd",
serviceName: "nemoclaw-openshell-gateway",
statusCommand: "systemctl --user status nemoclaw-openshell-gateway",
Expand Down Expand Up @@ -626,6 +627,7 @@ describe("docker-driver-gateway-service", () => {

expect(result).toEqual({
attempted: true,
standaloneFallbackAllowed: false,
manager: "homebrew",
serviceName: "openshell",
statusCommand: "brew services info openshell",
Expand Down Expand Up @@ -674,8 +676,54 @@ describe("docker-driver-gateway-service", () => {
])("reports nothing to stop when %s (#7904)", (_case, opts, reason) => {
expect(stopOpenShellGatewayUserService({ commandExists: () => true, ...opts })).toEqual({
attempted: false,
standaloneFallbackAllowed: false,
reason,
stopped: false,
});
});

it("reports standalone fallback eligibility when the systemd user manager is unavailable", () => {
const home = "/home/nvidia";
const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`;

const result = stopOpenShellGatewayUserService({
commandExists: (command) => command === "systemctl",
env: { HOME: home },
existsSync: (candidate) => candidate === servicePath,
home,
lstatSync: nonSymlinkStat,
platform: "linux",
readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`,
spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")),
});

expect(result).toMatchObject({
attempted: true,
standaloneFallbackAllowed: true,
stopped: false,
});
});

it("refuses standalone fallback when the systemd service can activate automatically", () => {
const home = "/home/nvidia";
const servicePath = `${home}/.config/systemd/user/nemoclaw-openshell-gateway.service`;
const activationPath = `${home}/.config/systemd/user/default.target.wants/nemoclaw-openshell-gateway.service`;

const result = stopOpenShellGatewayUserService({
commandExists: (command) => command === "systemctl",
env: { HOME: home },
existsSync: (candidate) => candidate === servicePath || candidate === activationPath,
home,
lstatSync: nonSymlinkStat,
platform: "linux",
readFileSync: () => `# ${NEMOCLAW_OPENSHELL_GATEWAY_USER_SERVICE_MARKER}\n`,
spawnSyncImpl: vi.fn(() => spawnResult(1, "Failed to connect to bus: No medium found")),
});

expect(result).toMatchObject({
attempted: true,
standaloneFallbackAllowed: false,
stopped: false,
});
});
});
Loading
Loading