Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 20 additions & 12 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ function getSandboxReuseState(sandboxName: string | null) {
function repairRecordedSandbox(sandboxName: string | null): void {
if (!sandboxName) return;
note(` [resume] Cleaning up recorded sandbox '${sandboxName}' before recreating it.`);
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
runOpenshell(["sandbox", "delete", sandboxName], { ignoreError: true });
registry.removeSandbox(sandboxName);
}
Expand Down Expand Up @@ -2588,7 +2588,7 @@ function stopLegacyGatewayClusterContainer(): boolean {
}

function retireLegacyGatewayForDockerDriverUpgrade(): void {
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
stopDockerDriverGatewayProcess();
const stoppedLegacyContainer = stopLegacyGatewayClusterContainer();
removeDockerDriverGatewayRegistration();
Expand Down Expand Up @@ -3555,7 +3555,7 @@ async function preflight(
const containerState = verifyGatewayContainerRunning(GATEWAY_NAME);
if (containerState === "missing") {
console.log(" Gateway metadata is stale (container not running). Cleaning up...");
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
gatewayReuseState = destroyGatewayForReuse(
destroyGateway,
" ✓ Stale gateway metadata cleaned up",
Expand Down Expand Up @@ -3589,7 +3589,7 @@ async function preflight(
console.log(
` Gateway container is running but ${getGatewayLocalEndpoint()}/ is not responding. Recreating...`,
);
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
gatewayReuseState = destroyGatewayForReuse(
destroyGateway,
" ✓ Stale gateway cleaned up",
Expand Down Expand Up @@ -3618,7 +3618,7 @@ async function preflight(
gatewayReuseState = "missing";
console.log(" ✓ Previous session cleaned up");
} else {
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
gatewayReuseState = destroyGatewayForReuse(
destroyGateway,
" ✓ Previous session cleaned up",
Expand Down Expand Up @@ -8558,10 +8558,17 @@ function getRunningForwardPorts(forwardListOutput: string | null | undefined): s
return [...ports];
}

function bestEffortForwardStop(port: string | number): void {
runOpenshell(["forward", "stop", String(port)], {
ignoreError: true,
suppressOutput: true,
});
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function stopAllDashboardForwards(): void {
const forwardList = runCaptureOpenshell(["forward", "list"], { ignoreError: true });
for (const port of getRunningForwardPorts(forwardList)) {
runOpenshell(["forward", "stop", port], { ignoreError: true });
bestEffortForwardStop(port);
}
}

Expand Down Expand Up @@ -8616,7 +8623,7 @@ function ensureDashboardForward(
preferredEntry &&
(preferredEntry.sandboxName === sandboxName || !isLiveForwardStatus(preferredEntry.status))
) {
runOpenshell(["forward", "stop", String(preferredPort)], { ignoreError: true });
bestEffortForwardStop(preferredPort);
existingForwards = runCaptureOpenshell(["forward", "list"], { ignoreError: true });
}
let actualPort: number;
Expand Down Expand Up @@ -8672,22 +8679,22 @@ function ensureDashboardForward(
const occupied = getOccupiedPorts(existingForwards);
for (const [port, owner] of occupied.entries()) {
if (owner === sandboxName && Number(port) !== actualPort) {
runOpenshell(["forward", "stop", port], { ignoreError: true });
bestEffortForwardStop(port);
}
}

// Preserve the original URL's hostname (loopback vs remote) but swap to the actual port.
const parsedUrl = new URL(chatUiUrl.includes("://") ? chatUiUrl : `http://${chatUiUrl}`);
parsedUrl.port = String(actualPort);
const actualTarget = getDashboardForwardTarget(parsedUrl.toString());
runOpenshell(["forward", "stop", String(actualPort)], { ignoreError: true });
bestEffortForwardStop(actualPort);
const { result: fwdResult, diagnostic: fwdDiagnostic } = runBackgroundForwardStartWithPortReleaseRetries(
(stdio, timeout) =>
runOpenshell(
["forward", "start", "--background", actualTarget, sandboxName],
{ ignoreError: true, suppressOutput: true, stdio, timeout },
),
() => { sleep(1); runOpenshell(["forward", "stop", String(actualPort)], { ignoreError: true }); },
() => { sleep(1); bestEffortForwardStop(actualPort); },
);
if (fwdResult && fwdResult.status !== 0) {
const looksLikePortConflict = looksLikeForwardPortConflict(fwdDiagnostic);
Expand Down Expand Up @@ -9438,7 +9445,7 @@ async function onboard(opts: OnboardOptions = {}): Promise<void> {
const containerState = verifyGatewayContainerRunning(GATEWAY_NAME);
if (containerState === "missing") {
console.log(" Gateway metadata is stale (container not running). Cleaning up...");
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
gatewayReuseState = destroyGatewayForReuse(
destroyGateway,
" ✓ Stale gateway metadata cleaned up",
Expand Down Expand Up @@ -9477,7 +9484,7 @@ async function onboard(opts: OnboardOptions = {}): Promise<void> {
console.log(
` Gateway container is running but ${getGatewayLocalEndpoint()}/ is not responding. Recreating...`,
);
runOpenshell(["forward", "stop", String(DASHBOARD_PORT)], { ignoreError: true });
bestEffortForwardStop(DASHBOARD_PORT);
gatewayReuseState = destroyGatewayForReuse(
destroyGateway,
" ✓ Stale gateway cleaned up",
Expand Down Expand Up @@ -10253,6 +10260,7 @@ module.exports = {
startGatewayForRecovery,
openshellArgv,
runCaptureOpenshell,
bestEffortForwardStop,
agentSupportsWebSearch,
setupInference,
setupMessagingChannels,
Expand Down
101 changes: 101 additions & 0 deletions test/onboard-forward-stop-quiet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";

import { describe, it } from "vitest";

function parseStdoutJson<T>(stdout: string): T {
const line = stdout.trim().split("\n").pop();
if (!line) {
throw new Error("Expected JSON payload on the last stdout line");
}
return JSON.parse(line);
}

describe("onboard bestEffortForwardStop (#3971)", () => {
it("suppresses the noisy 'No active forward found' warning from openshell forward stop", () => {
const repoRoot = path.join(import.meta.dirname, "..");
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-forward-stop-quiet-"));
const scriptPath = path.join(tmpDir, "forward-stop-quiet.js");
const onboardPath = JSON.stringify(path.join(repoRoot, "dist", "lib", "onboard.js"));

const script = String.raw`
const childProcess = require("child_process");

const stdoutWrites = [];
const stderrWrites = [];
const origStdoutWrite = process.stdout.write.bind(process.stdout);
const origStderrWrite = process.stderr.write.bind(process.stderr);
process.stdout.write = (chunk) => { stdoutWrites.push(String(chunk)); return true; };
process.stderr.write = (chunk) => { stderrWrites.push(String(chunk)); return true; };

const calls = [];
childProcess.spawnSync = (exe, args, opts) => {
calls.push({ exe, args, stdio: opts && opts.stdio });
if (Array.isArray(args) && args.includes("stop")) {
return {
status: 0,
stdout: "",
stderr: "\x1b[33m!\x1b[39m No active forward found for port 18789\n",
error: undefined,
};
}
return { status: 0, stdout: "", stderr: "", error: undefined };
};

const onboard = require(${onboardPath});
onboard.bestEffortForwardStop(18789);

process.stdout.write = origStdoutWrite;
process.stderr.write = origStderrWrite;

const joinedOut = stdoutWrites.join("");
const joinedErr = stderrWrites.join("");
const callStopArgs = calls
.filter((c) => Array.isArray(c.args) && c.args.includes("forward") && c.args.includes("stop"))
.map((c) => c.args);
console.log(JSON.stringify({
stdout: joinedOut,
stderr: joinedErr,
callStopArgs,
}));
`;
fs.writeFileSync(scriptPath, script);

const result = spawnSync(process.execPath, [scriptPath], {
cwd: repoRoot,
encoding: "utf-8",
env: { ...process.env, HOME: tmpDir },
});

assert.equal(result.status, 0, result.stderr);

Check failure on line 76 in test/onboard-forward-stop-quiet.test.ts

View workflow job for this annotation

GitHub Actions / checks

[cli] test/onboard-forward-stop-quiet.test.ts > onboard bestEffortForwardStop (#3971) > suppresses the noisy 'No active forward found' warning from openshell forward stop

AssertionError: Expected values to be strictly equal: 1 !== 0 - Expected + Received - 0 + 1 ❯ test/onboard-forward-stop-quiet.test.ts:76:12

Check failure on line 76 in test/onboard-forward-stop-quiet.test.ts

View workflow job for this annotation

GitHub Actions / unit-vitest-linux

[cli] test/onboard-forward-stop-quiet.test.ts > onboard bestEffortForwardStop (#3971) > suppresses the noisy 'No active forward found' warning from openshell forward stop

AssertionError: Expected values to be strictly equal: 1 !== 0 - Expected + Received - 0 + 1 ❯ test/onboard-forward-stop-quiet.test.ts:76:12
const payload = parseStdoutJson<{
stdout: string;
stderr: string;
callStopArgs: string[][];
}>(result.stdout);

assert.equal(
payload.callStopArgs.length,
1,
`Expected one forward-stop call, got ${payload.callStopArgs.length}`,
);
assert.deepEqual(payload.callStopArgs[0].slice(-3), ["forward", "stop", "18789"]);

assert.ok(
!payload.stdout.includes("No active forward found"),
`stdout leaked openshell warning: ${payload.stdout}`,
);
assert.ok(
!payload.stderr.includes("No active forward found"),
`stderr leaked openshell warning: ${payload.stderr}`,
);

fs.rmSync(tmpDir, { recursive: true, force: true });
});
});
Loading