Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
126 changes: 126 additions & 0 deletions src/lib/tunnel/agent-forward-stop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { describe, expect, it, vi } from "vitest";

import { stopAgentForwardPortsForStop } from "./agent-forward-stop";

function forwardList(entries: Array<{ sandbox: string; port: number; status?: string }>): string {
return [
"SANDBOX BIND PORT PID STATUS",
...entries.map(
(entry, index) =>
`${entry.sandbox} 127.0.0.1 ${String(entry.port)} ${String(1000 + index)} ${
entry.status ?? "running"
}`,
),
].join("\n");
}

describe("stopAgentForwardPortsForStop", () => {
it("stops declared and runtime dashboard forwards with sandbox-scoped commands", () => {
const runOpenshell = vi.fn();
const runCaptureOpenshell = vi.fn(() =>
forwardList([
{ sandbox: "nemohermes", port: 18789 },
{ sandbox: "nemohermes", port: 8642 },
{ sandbox: "nemohermes", port: 18792 },
]),
);
const info = vi.fn<(message: string) => void>();

stopAgentForwardPortsForStop("nemohermes", {
getSessionAgent: () => ({
displayName: "Hermes Agent",
forward_ports: [18789, 8642, "8642", 0, 80, 70000, "not-a-port"],
}),
getAgentDisplayName: (agent) => agent?.displayName ?? "OpenClaw",
getSandbox: () => ({ dashboardPort: 18792 }),
resolveOpenshell: () => "/usr/local/bin/openshell",
runOpenshell,
runCaptureOpenshell,
info,
});

expect(runOpenshell).toHaveBeenCalledTimes(3);
expect(runOpenshell).toHaveBeenNthCalledWith(1, ["forward", "stop", "18789", "nemohermes"], {
ignoreError: true,
suppressOutput: true,
});
expect(runOpenshell).toHaveBeenNthCalledWith(2, ["forward", "stop", "8642", "nemohermes"], {
ignoreError: true,
suppressOutput: true,
});
expect(runOpenshell).toHaveBeenNthCalledWith(3, ["forward", "stop", "18792", "nemohermes"], {
ignoreError: true,
suppressOutput: true,
});
expect(runCaptureOpenshell).toHaveBeenCalledTimes(3);
expect(info.mock.calls.map((call) => call[0]).join("\n")).toContain(
"Stopped Hermes Agent host port forward 8642",
);
});

it("skips OpenClaw or agents without declared forwards", () => {
const resolveOpenshell = vi.fn(() => "/usr/local/bin/openshell");
const runOpenshell = vi.fn();

stopAgentForwardPortsForStop("openclaw-sandbox", {
getSessionAgent: () => null,
resolveOpenshell,
runOpenshell,
});

stopAgentForwardPortsForStop("empty-agent", {
getSessionAgent: () => ({ displayName: "Empty Agent", forward_ports: [] }),
getSandbox: () => null,
resolveOpenshell,
runOpenshell,
});

expect(resolveOpenshell).not.toHaveBeenCalled();
expect(runOpenshell).not.toHaveBeenCalled();
});

it("leaves forwards alone when OpenShell reports a different owner", () => {
const runOpenshell = vi.fn();
const warn = vi.fn<(message: string) => void>();

stopAgentForwardPortsForStop("nemohermes", {
getSessionAgent: () => ({ displayName: "Hermes Agent", forward_ports: [8642] }),
getAgentDisplayName: (agent) => agent?.displayName ?? "OpenClaw",
getSandbox: () => null,
resolveOpenshell: () => "/usr/local/bin/openshell",
runOpenshell,
runCaptureOpenshell: () => forwardList([{ sandbox: "other-sandbox", port: 8642 }]),
warn,
});

expect(runOpenshell).not.toHaveBeenCalled();
expect(warn.mock.calls.map((call) => call[0]).join("\n")).toContain(
"belongs to another sandbox",
);
});

it("does not stop a forward when ownership cannot be enumerated", () => {
const runOpenshell = vi.fn();
const warn = vi.fn<(message: string) => void>();

stopAgentForwardPortsForStop("nemohermes", {
getSessionAgent: () => ({ displayName: "Hermes Agent", forward_ports: [8642] }),
getAgentDisplayName: (agent) => agent?.displayName ?? "OpenClaw",
getSandbox: () => null,
resolveOpenshell: () => "/usr/local/bin/openshell",
runOpenshell,
runCaptureOpenshell: () => {
throw new Error("forward list failed");
},
warn,
});

expect(runOpenshell).not.toHaveBeenCalled();
expect(warn.mock.calls.map((call) => call[0]).join("\n")).toContain(
"Could not enumerate OpenShell forwards",
);
});
});
138 changes: 138 additions & 0 deletions src/lib/tunnel/agent-forward-stop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { spawnSync } from "node:child_process";

import { resolveOpenshell } from "../adapters/openshell/resolve";
import * as agentRuntime from "../agent/runtime";
import {
bestEffortForwardStopForSandbox,
type ForwardListRunner,
type ForwardStopRunner,
} from "../onboard/forward-cleanup";
import * as registry from "../state/registry";

type Reporter = (message: string) => void;

type AgentWithForwards = {
displayName?: string;
forward_ports?: unknown;
};

type SandboxWithDashboardPort = {
dashboardPort?: unknown;
};

type StopAgentForwardPortsDeps = {
getSessionAgent?: (sandboxName?: string) => AgentWithForwards | null;
getAgentDisplayName?: (agent: AgentWithForwards | null) => string;
getSandbox?: (sandboxName: string) => SandboxWithDashboardPort | null;
resolveOpenshell?: () => string | null;
runOpenshell?: ForwardStopRunner;
runCaptureOpenshell?: ForwardListRunner;
info?: Reporter;
warn?: Reporter;
};

function getAgentForwardPorts(agent: AgentWithForwards, dashboardPort: unknown): number[] {
const ports = new Set<number>();
const candidates = [
...(Array.isArray(agent.forward_ports) ? agent.forward_ports : []),
dashboardPort,
];
for (const rawPort of candidates) {
const port =
typeof rawPort === "number"
? rawPort
: typeof rawPort === "string" && /^\d+$/.test(rawPort.trim())
? Number(rawPort.trim())
: NaN;
if (Number.isInteger(port) && port >= 1024 && port <= 65535) {
ports.add(port);
}
}
return [...ports];
}

function makeRunOpenshell(openshell: string): ForwardStopRunner {
return (args, opts) => {
const result = spawnSync(openshell, args, {
encoding: "utf-8",
stdio: opts.suppressOutput ? "ignore" : "inherit",
});
if (!opts.ignoreError && result.status !== 0) {
throw new Error(`openshell ${args.join(" ")} failed`);
}
return result;
};
}

function makeRunCaptureOpenshell(openshell: string): ForwardListRunner {
return (args, opts) => {
const result = spawnSync(openshell, args, {
encoding: "utf-8",
stdio: ["ignore", "pipe", "pipe"],
timeout: opts.timeout,
});
if (result.status !== 0) {
throw new Error(`openshell ${args.join(" ")} failed`);
}
return result.stdout || "";
};
}

export function stopAgentForwardPortsForStop(
sandboxName: string | undefined,
deps: StopAgentForwardPortsDeps = {},
): void {
if (!sandboxName) return;

const getSessionAgent = deps.getSessionAgent ?? agentRuntime.getSessionAgent;
const agent = getSessionAgent(sandboxName);
if (!agent) return;

const getSandbox = deps.getSandbox ?? registry.getSandbox;
const ports = getAgentForwardPorts(agent, getSandbox(sandboxName)?.dashboardPort);
if (ports.length === 0) return;

const displayName = deps.getAgentDisplayName
? deps.getAgentDisplayName(agent)
: agentRuntime.getAgentDisplayName(
agent as Parameters<typeof agentRuntime.getAgentDisplayName>[0],
);
const warn = deps.warn ?? (() => {});
const info = deps.info ?? (() => {});

const openshell = (deps.resolveOpenshell ?? resolveOpenshell)();
if (!openshell) {
warn(`openshell not found - cannot stop ${displayName} host port forwards.`);
return;
}

const runOpenshell = deps.runOpenshell ?? makeRunOpenshell(openshell);
const runCaptureOpenshell = deps.runCaptureOpenshell ?? makeRunCaptureOpenshell(openshell);

for (const port of ports) {
const result = bestEffortForwardStopForSandbox(
runOpenshell,
runCaptureOpenshell,
port,
sandboxName,
);
if (result === "stopped") {
info(
`Stopped ${displayName} host port forward ${String(port)} for sandbox '${sandboxName}'.`,
);
} else if (result === "owned-other") {
warn(
`Keeping ${displayName} host port forward ${String(port)}; it belongs to another sandbox.`,
);
} else if (result === "list-failed") {
warn(
`Could not enumerate OpenShell forwards; skipping ${displayName} host port forward ${String(
port,
)} cleanup.`,
);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
13 changes: 13 additions & 0 deletions src/lib/tunnel/services-gateway-ownership.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";

import type { SandboxEntry } from "../state/registry";
import * as agentForwardStop from "./agent-forward-stop";
import type { ReleaseGatewayPortResult } from "./gateway-port-release";
import type { GatewayStopDeps } from "./gateway-stop";
import * as gatewayStop from "./gateway-stop";
Expand Down Expand Up @@ -189,6 +190,9 @@ describe("stopAll gateway-stop wiring", () => {
const releaseForStop = vi
.spyOn(gatewayStop, "releaseGatewayPortForStop")
.mockImplementation(() => {});
const stopAgentForwards = vi
.spyOn(agentForwardStop, "stopAgentForwardPortsForStop")
.mockImplementation(() => {});
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});

try {
Expand All @@ -197,6 +201,11 @@ describe("stopAll gateway-stop wiring", () => {
rmSync(pidDir, { recursive: true, force: true });
}

expect(stopAgentForwards).toHaveBeenCalledTimes(1);
expect(stopAgentForwards).toHaveBeenCalledWith("alpha", {
info: expect.any(Function),
warn: expect.any(Function),
});
expect(releaseForStop).toHaveBeenCalledTimes(1);
expect(releaseForStop).toHaveBeenCalledWith("alpha", {
info: expect.any(Function),
Expand All @@ -213,6 +222,9 @@ describe("stopAll gateway-stop wiring", () => {
const releaseForStop = vi
.spyOn(gatewayStop, "releaseGatewayPortForStop")
.mockImplementation(() => {});
const stopAgentForwards = vi
.spyOn(agentForwardStop, "stopAgentForwardPortsForStop")
.mockImplementation(() => {});

try {
stopAll({ pidDir, sandboxName: "alpha" });
Expand All @@ -221,5 +233,6 @@ describe("stopAll gateway-stop wiring", () => {
}

expect(releaseForStop).not.toHaveBeenCalled();
expect(stopAgentForwards).not.toHaveBeenCalled();
});
});
Loading
Loading