From ea634b8b0055adbd9b60994a2bcc578b82b10e8c Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 10:06:39 +0700 Subject: [PATCH 01/12] fix(onboard): reuse registered dashboard forward Signed-off-by: San Dang --- src/lib/onboard.ts | 12 ++-- src/lib/onboard/dashboard-forward-control.ts | 8 +++ src/lib/onboard/dashboard.ts | 68 +++++++++++++++---- .../machine/handlers/agent-setup.test.ts | 13 ++++ .../onboard/machine/handlers/agent-setup.ts | 13 +++- ...ard-finalization-dashboard-forward.test.ts | 38 +++++++++++ 6 files changed, 128 insertions(+), 24 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 4ecee3a2c4d..5a445425f31 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3245,13 +3245,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { recordStepFailed, skippedStepMessage, }), - ensureAgentDashboardForward: (name, selectedAgent) => - ensureFinalizationAgentDashboardForward( - name, - selectedAgent, - undefined, - hermesApiPortReservationScope, - ), + ensureAgentDashboardForward: (name, selectedAgent, options) => + ensureFinalizationAgentDashboardForward(name, selectedAgent, { + portReservation: hermesApiPortReservationScope, + preserveRegisteredForward: options?.preserveRegisteredForward === true, + }), persistDashboardPort: (name, port) => registry.updateSandbox(name, { dashboardPort: port }), recordStepSkipped, diff --git a/src/lib/onboard/dashboard-forward-control.ts b/src/lib/onboard/dashboard-forward-control.ts index 7b58fd24393..ea4f66451e1 100644 --- a/src/lib/onboard/dashboard-forward-control.ts +++ b/src/lib/onboard/dashboard-forward-control.ts @@ -5,15 +5,23 @@ export interface DashboardForwardOptions { rollbackSandboxOnFailure?: boolean; gatewayName?: string; allowPortReallocation?: boolean; + /** + * Preserve a bound port only when the caller has durable evidence that this + * onboarding attempt reused the registered sandbox and will run deployment + * verification before reporting success. + */ + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; } export function normalizeDashboardForwardOptions(options: DashboardForwardOptions = {}): { rollbackSandboxOnFailure: boolean; allowPortReallocation: boolean; + preserveRegisteredForward: boolean; } { return { rollbackSandboxOnFailure: options.rollbackSandboxOnFailure === true, allowPortReallocation: options.allowPortReallocation !== false, + preserveRegisteredForward: options.preserveRegisteredForward === true, }; } diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 615e45e0ad7..35d86bd78ab 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -27,6 +27,7 @@ import { } from "./dashboard-forward-control"; import { findAvailableDashboardPort, + findDashboardForwardOwner, getPersistedDashboardPort, getRegistryOccupiedDashboardPorts, isPortBoundOnHost, @@ -140,14 +141,20 @@ export interface OnboardDashboardHelpers { ): Promise; ensureFinalizationDashboardForward( sandboxName: string, - revalidateSandboxIdentity?: (operation: string) => void, + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + }, ): number; ensureFinalizationAgentDashboardForward( sandboxName: string, agent: { name: string; forwardPort?: number | null; forward_ports?: number[] | null } | null, - revalidateSandboxIdentity?: (operation: string) => void, - portReservation?: { - releaseBeforeForward(agentName: string, port: number): Promise | void; + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + portReservation?: { + releaseBeforeForward(agentName: string, port: number): Promise | void; + }; }, ): Promise | number; ensureAgentFixedForward( @@ -379,7 +386,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa options: DashboardForwardOptions = {}, ): number { chatUiUrl ||= `http://127.0.0.1:${CONTROL_UI_PORT}`; - const { rollbackSandboxOnFailure, allowPortReallocation } = + const { rollbackSandboxOnFailure, allowPortReallocation, preserveRegisteredForward } = normalizeDashboardForwardOptions(options); const { revalidateSandboxIdentity } = options; const preferredPort = Number(getDashboardForwardPort(chatUiUrl)); @@ -394,7 +401,19 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa ); const isPortBound = deps.isPortBoundOnHost ?? isPortBoundOnHost; const persistedPort = getPersistedDashboardPort(sandboxName, listSandboxes); + const registryOccupiedPorts = getRegistryOccupiedDashboardPorts(sandboxName, listSandboxes); if (persistedPort === preferredPort && isPortBound(preferredPort)) { + const listedOwner = findDashboardForwardOwner(existingForwards, String(preferredPort)); + if ( + preserveRegisteredForward && + listedOwner === null && + !registryOccupiedPorts.has(String(preferredPort)) + ) { + revalidateSandboxIdentity?.( + `preserve registered dashboard forward ${String(preferredPort)} for sandbox '${sandboxName}'`, + ); + return preferredPort; + } throw new Error( `Registered dashboard port ${String(preferredPort)} is already occupied; it cannot be reallocated or adopted.`, ); @@ -406,7 +425,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa preferredPort, existingForwards, isPortBound, - getRegistryOccupiedDashboardPorts(sandboxName, listSandboxes), + registryOccupiedPorts, ); } catch (err) { if (!rollbackSandboxOnFailure) throw err; @@ -505,20 +524,28 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa * binds the same port on both sides), so when the persisted port cannot be * forwarded this throws instead of reallocating: the resumed gateway only * listens on the persisted port, and a forward on any other port serves - * nothing. Post-verify builds its probe chain and Browser URL from - * `CHAT_UI_URL`, so after the forward starts this writes the bound port to - * `CHAT_UI_URL`. (#8970) + * nothing. A Ready-sandbox reuse may preserve the already-bound registered + * ForwardTcp listener; post-verify remains the authority that accepts the + * delivery chain. Every other occupied-port path still throws. Post-verify + * builds its probe chain and Browser URL from `CHAT_UI_URL`, so after the + * forward is reconciled this writes the bound port to `CHAT_UI_URL`. + * (#8970, #11074) */ function ensureFinalizationDashboardForward( sandboxName: string, - revalidateSandboxIdentity?: (operation: string) => void, + options: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + } = {}, ): number { + const { preserveRegisteredForward = false, revalidateSandboxIdentity } = options; const envUrl = process.env.CHAT_UI_URL; const persistedPort = envUrl ? null : getPersistedDashboardPort(sandboxName, listSandboxes); const requestedUrl = envUrl || (persistedPort === null ? undefined : `http://127.0.0.1:${String(persistedPort)}`); const actualPort = ensureDashboardForward(sandboxName, requestedUrl, { allowPortReallocation: false, + preserveRegisteredForward, ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), }); revalidateSandboxIdentity?.(`publish the dashboard URL for sandbox '${sandboxName}'`); @@ -553,11 +580,19 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa function ensureFinalizationAgentDashboardForward( sandboxName: string, agent: { name: string; forwardPort?: number | null; forward_ports?: number[] | null } | null, - revalidateSandboxIdentity?: (operation: string) => void, - portReservation?: { - releaseBeforeForward(agentName: string, port: number): Promise | void; - }, + options: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + portReservation?: { + releaseBeforeForward(agentName: string, port: number): Promise | void; + }; + } = {}, ): Promise | number { + const { + portReservation, + preserveRegisteredForward = false, + revalidateSandboxIdentity, + } = options; return agent ? ensureAgentDashboardForward(sandboxName, agent, { revalidateSandboxIdentity, @@ -565,7 +600,10 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa ? (port) => portReservation.releaseBeforeForward(agent.name, port) : undefined, }) - : ensureFinalizationDashboardForward(sandboxName, revalidateSandboxIdentity); + : ensureFinalizationDashboardForward(sandboxName, { + revalidateSandboxIdentity, + preserveRegisteredForward, + }); } function ensureAgentFixedForward( diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index c3ad023ec1a..3cc935de420 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -75,6 +75,7 @@ describe("handleAgentSetupState", () => { const { deps, calls } = createDeps(); const agent = { name: "hermes", displayName: "Hermes" }; const session = createSession(); + session.steps.sandbox.status = "skipped"; const result = await handleAgentSetupState({ ...baseOptions(deps, agent), @@ -170,6 +171,18 @@ describe("handleAgentSetupState", () => { }); }); + it("preserves the registered dashboard forward after Ready sandbox reuse (#11074)", async () => { + const { deps, calls } = createDeps(); + const session = createSession(); + session.steps.sandbox.status = "skipped"; + + await handleAgentSetupState({ ...baseOptions(deps), session }); + + expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", null, { + preserveRegisteredForward: true, + }); + }); + it("delegates shared OpenClaw configuration before ready-resume completion", async () => { const { deps, calls } = createDeps({ isOpenclawReady: vi.fn(() => true) }); const revalidateSandboxIdentity = vi.fn(); diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index 0bebdedbc60..dca779c700a 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -28,7 +28,11 @@ export interface AgentSetupStateOptions { context: unknown, ): Promise; agentSetupContext(): unknown; - ensureAgentDashboardForward(sandboxName: string, agent: Agent | null): Promise | number; + ensureAgentDashboardForward( + sandboxName: string, + agent: Agent | null, + options?: { preserveRegisteredForward?: boolean }, + ): Promise | number; persistDashboardPort(sandboxName: string, dashboardPort: number): void; recordStepSkipped(stepName: string): Promise; isOpenclawReady(sandboxName: string): boolean; @@ -101,6 +105,9 @@ export async function handleAgentSetupState({ return { session, stateResult: advanceTo("policies", { metadata: { state: "agent_setup" } }) }; } + // A skipped sandbox step is the durable machine receipt for Ready-sandbox + // reuse. Every other state keeps the strict occupied-port path. + const preserveRegisteredForward = session?.steps.sandbox.status === "skipped"; const resumeOpenclaw = resume && sandboxName && deps.isOpenclawReady(sandboxName); if (resumeOpenclaw) { deps.skippedStepMessage("openclaw", sandboxName); @@ -134,7 +141,9 @@ export async function handleAgentSetupState({ deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } - const dashboardPort = await deps.ensureAgentDashboardForward(sandboxName, null); + const dashboardPort = await (preserveRegisteredForward + ? deps.ensureAgentDashboardForward(sandboxName, null, { preserveRegisteredForward: true }) + : deps.ensureAgentDashboardForward(sandboxName, null)); if (dashboardPort > 0) { deps.persistDashboardPort(sandboxName, dashboardPort); } diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index 6a8eefd0f5d..df38fbe1de2 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -71,6 +71,44 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(launch).not.toHaveBeenCalled(); }); + it("preserves the registered ForwardTcp listener during Ready sandbox reuse (#11074)", () => { + vi.stubEnv("CHAT_UI_URL", undefined); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + isPortBound: (port) => port === 18_790, + }); + + expect( + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toBe(18_790); + expect(launch).not.toHaveBeenCalled(); + expect(process.env.CHAT_UI_URL).toBe("http://127.0.0.1:18790"); + }); + + it("does not preserve a reused port registered to another sandbox (#11074)", () => { + vi.stubEnv("CHAT_UI_URL", undefined); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [ + { name: "reonboard-test", dashboardPort: 18_790 }, + { name: "other-sandbox", dashboardPort: 18_790 }, + ], + }), + isPortBound: (port) => port === 18_790, + }); + + expect(() => + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toThrow(/cannot be reallocated/u); + expect(launch).not.toHaveBeenCalled(); + }); + it("honors an explicit dashboard URL", () => { vi.stubEnv("CHAT_UI_URL", "http://127.0.0.1:19001"); const { helpers, launch } = harness({ From aac0cba820f8443a369ad4926a9a660e98f77b57 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 10:47:33 +0700 Subject: [PATCH 02/12] fix(onboard): verify reused forward ownership Signed-off-by: San Dang --- .../forward-service-ownership.test.ts | 127 +++++++++++ .../openshell/forward-service-ownership.ts | 200 ++++++++++++++++++ src/lib/onboard/dashboard-forward-control.ts | 5 +- src/lib/onboard/dashboard.ts | 12 +- ...ard-finalization-dashboard-forward.test.ts | 32 +++ 5 files changed, 372 insertions(+), 4 deletions(-) create mode 100644 src/lib/adapters/openshell/forward-service-ownership.test.ts create mode 100644 src/lib/adapters/openshell/forward-service-ownership.ts diff --git a/src/lib/adapters/openshell/forward-service-ownership.test.ts b/src/lib/adapters/openshell/forward-service-ownership.test.ts new file mode 100644 index 00000000000..d59484aa5a0 --- /dev/null +++ b/src/lib/adapters/openshell/forward-service-ownership.test.ts @@ -0,0 +1,127 @@ +// 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 { buildForwardServiceArgs, type ForwardServiceTarget } from "./forward-service"; +import { + isForwardServiceListenerOwned, + type ForwardServiceOwnershipDeps, +} from "./forward-service-ownership"; + +const target: ForwardServiceTarget = { + executable: "/usr/local/bin/openshell", + gatewayName: "nemoclaw", + workspace: "default", + sandboxName: "reonboard-test", + localHost: "127.0.0.1", + localPort: 18_790, + targetHost: "127.0.0.1", + targetPort: 18_790, +}; + +function ownership(overrides: Partial = {}) { + return { + currentUid: () => 1_000, + inspectProcess: () => ({ + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + }), + listListenerPids: vi.fn(() => [4_242]), + realpath: (value: string) => value, + sourceEnvironment: { HOME: "/home/operator" }, + ...overrides, + } satisfies ForwardServiceOwnershipDeps; +} + +describe("direct ForwardTcp listener ownership", () => { + it("accepts one stable listener with the exact user, executable, and target argv", () => { + const deps = ownership(); + + expect(isForwardServiceListenerOwned(target, deps)).toBe(true); + expect(deps.listListenerPids).toHaveBeenCalledTimes(2); + }); + + it("accepts the exact ps command line when procfs argv is unavailable", () => { + expect( + isForwardServiceListenerOwned( + target, + ownership({ + inspectProcess: () => ({ + argv: null, + commandLine: [target.executable, ...buildForwardServiceArgs(target)].join(" "), + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + }), + }), + ), + ).toBe(true); + }); + + it.each([ + ["foreign user", { uid: 2_000 }], + ["foreign executable", { executable: "/usr/bin/python3" }], + [ + "foreign target", + { + argv: [ + target.executable, + ...buildForwardServiceArgs({ ...target, sandboxName: "other-sandbox" }), + ], + }, + ], + ])("rejects a %s listener", (_case, replacement) => { + expect( + isForwardServiceListenerOwned( + target, + ownership({ + inspectProcess: () => ({ + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + ...replacement, + }), + }), + ), + ).toBe(false); + }); + + it("rejects an incomplete or changing listener scan", () => { + const listListenerPids = vi.fn<() => readonly number[] | null>(); + listListenerPids.mockReturnValueOnce([4_242]).mockReturnValueOnce([4_243]); + + expect(isForwardServiceListenerOwned(target, ownership({ listListenerPids }))).toBe(false); + expect(isForwardServiceListenerOwned(target, ownership({ listListenerPids: () => null }))).toBe( + false, + ); + }); + + it("rejects a listener when the current user cannot be proven", () => { + expect(isForwardServiceListenerOwned(target, ownership({ currentUid: () => null }))).toBe( + false, + ); + }); + + it("rejects a listener from another OpenShell configuration home", () => { + expect( + isForwardServiceListenerOwned( + target, + ownership({ + inspectProcess: () => ({ + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/other" }, + executable: target.executable, + uid: 1_000, + }), + }), + ), + ).toBe(false); + }); +}); diff --git a/src/lib/adapters/openshell/forward-service-ownership.ts b/src/lib/adapters/openshell/forward-service-ownership.ts new file mode 100644 index 00000000000..b70a505a7aa --- /dev/null +++ b/src/lib/adapters/openshell/forward-service-ownership.ts @@ -0,0 +1,200 @@ +// 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 { buildOpenShellSubprocessEnv } from "./resolve-shared"; +import { + buildForwardServiceArgs, + type ForwardServiceTarget, + validateForwardServiceTarget, +} from "./forward-service"; + +const PROBE_TIMEOUT_MS = 1_000; +const PROBE_MAX_BUFFER_BYTES = 16 * 1024; + +export interface ForwardServiceProcessSnapshot { + readonly argv: readonly string[] | null; + readonly commandLine: string | null; + readonly environment: Readonly> | null; + readonly executable: string | null; + readonly uid: number | null; +} + +export interface ForwardServiceOwnershipDeps { + readonly currentUid?: () => number | null; + readonly inspectProcess?: (pid: number) => ForwardServiceProcessSnapshot | null; + readonly listListenerPids?: (port: number) => readonly number[] | null; + readonly realpath?: (value: string) => string | null; + readonly sourceEnvironment?: NodeJS.ProcessEnv; +} + +function probeExecutable(candidates: readonly string[]): string | null { + return candidates.find((candidate) => fs.existsSync(candidate)) ?? null; +} + +function runProbe(executable: string, args: readonly string[]) { + return spawnSync(executable, [...args], { + encoding: "utf8", + env: buildOpenShellSubprocessEnv(), + maxBuffer: PROBE_MAX_BUFFER_BYTES, + stdio: ["ignore", "pipe", "ignore"], + timeout: PROBE_TIMEOUT_MS, + }); +} + +function listListenerPids(port: number): readonly number[] | null { + const lsof = probeExecutable(["/usr/sbin/lsof", "/usr/bin/lsof"]); + if (!lsof) return null; + const result = runProbe(lsof, ["-nP", `-iTCP:${String(port)}`, "-sTCP:LISTEN", "-Fp"]); + if (result.error || result.status !== 0) return null; + const pids = new Set(); + for (const line of result.stdout.split(/\r?\n/u)) { + const match = /^p([1-9]\d*)$/u.exec(line.trim()); + if (match) pids.add(Number(match[1])); + } + return [...pids]; +} + +function processUid(pid: number): number | null { + try { + const uid = fs.statSync(`/proc/${String(pid)}`).uid; + if (Number.isSafeInteger(uid) && uid >= 0) return uid; + } catch { + // Fall through to ps on hosts without procfs. + } + const ps = probeExecutable(["/bin/ps", "/usr/bin/ps"]); + if (!ps) return null; + const result = runProbe(ps, ["-p", String(pid), "-o", "uid="]); + const uid = Number(result.status === 0 ? result.stdout.trim() : ""); + return Number.isSafeInteger(uid) && uid >= 0 ? uid : null; +} + +function processExecutable(pid: number): string | null { + try { + return fs.realpathSync.native(`/proc/${String(pid)}/exe`); + } catch { + // Fall through to lsof on hosts without procfs. + } + const lsof = probeExecutable(["/usr/sbin/lsof", "/usr/bin/lsof"]); + if (!lsof) return null; + const result = runProbe(lsof, ["-a", "-p", String(pid), "-d", "txt", "-Fn"]); + if (result.error || result.status !== 0) return null; + return ( + result.stdout + .split(/\r?\n/u) + .find((line) => line.startsWith("n") && line.length > 1) + ?.slice(1) ?? null + ); +} + +function processArgv(pid: number): readonly string[] | null { + try { + const argv = fs.readFileSync(`/proc/${String(pid)}/cmdline`, "utf8").split("\0"); + if (argv.at(-1) === "") argv.pop(); + return argv.length > 0 ? argv : null; + } catch { + return null; + } +} + +function processCommandLine(pid: number): string | null { + const ps = probeExecutable(["/bin/ps", "/usr/bin/ps"]); + if (!ps) return null; + const result = runProbe(ps, ["-ww", "-p", String(pid), "-o", "command="]); + const commandLine = result.status === 0 ? result.stdout.trim() : ""; + return commandLine || null; +} + +function processEnvironment(pid: number): Readonly> | null { + try { + return Object.fromEntries( + fs + .readFileSync(`/proc/${String(pid)}/environ`, "utf8") + .split("\0") + .filter(Boolean) + .map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]), + ); + } catch { + // Fall through to ps on hosts without procfs. + } + const ps = probeExecutable(["/bin/ps", "/usr/bin/ps"]); + if (!ps) return null; + const result = runProbe(ps, ["eww", "-p", String(pid), "-o", "command="]); + if (result.error || result.status !== 0) return null; + const environment: Record = {}; + for (const token of result.stdout.trim().split(/\s+/u)) { + const separator = token.indexOf("="); + if (separator > 0) environment[token.slice(0, separator)] = token.slice(separator + 1); + } + return environment; +} + +function inspectProcess(pid: number): ForwardServiceProcessSnapshot { + const argv = processArgv(pid); + return { + argv, + commandLine: argv ? null : processCommandLine(pid), + environment: processEnvironment(pid), + executable: processExecutable(pid), + uid: processUid(pid), + }; +} + +function realpath(value: string): string | null { + try { + return fs.realpathSync.native(value); + } catch { + return null; + } +} + +function sameArgv(actual: readonly string[], expected: readonly string[]): boolean { + return ( + actual.length === expected.length && actual.every((value, index) => value === expected[index]) + ); +} + +/** Prove that a bound port belongs to the exact direct ForwardTcp command. */ +export function isForwardServiceListenerOwned( + target: ForwardServiceTarget, + deps: ForwardServiceOwnershipDeps = {}, +): boolean { + validateForwardServiceTarget(target); + const enumerate = deps.listListenerPids ?? listListenerPids; + const before = enumerate(target.localPort); + if (!before || before.length !== 1) return false; + const pid = before[0]; + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + + const currentUid = deps.currentUid + ? deps.currentUid() + : typeof process.getuid === "function" + ? process.getuid() + : null; + const snapshot = (deps.inspectProcess ?? inspectProcess)(pid); + if (!snapshot || currentUid === null || snapshot.uid !== currentUid) return false; + const expectedEnvironment = buildOpenShellSubprocessEnv(deps.sourceEnvironment ?? process.env); + if ( + !expectedEnvironment.HOME || + snapshot.environment?.HOME !== expectedEnvironment.HOME || + snapshot.environment.XDG_CONFIG_HOME !== expectedEnvironment.XDG_CONFIG_HOME || + snapshot.environment.XDG_RUNTIME_DIR !== expectedEnvironment.XDG_RUNTIME_DIR + ) { + return false; + } + const resolvePath = deps.realpath ?? realpath; + const expectedExecutable = resolvePath(target.executable); + const observedExecutable = snapshot.executable ? resolvePath(snapshot.executable) : null; + if (!expectedExecutable || observedExecutable !== expectedExecutable) return false; + + const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; + const invocationMatches = snapshot.argv + ? sameArgv(snapshot.argv, expectedArgv) + : snapshot.commandLine === expectedArgv.join(" "); + if (!invocationMatches) return false; + + const after = enumerate(target.localPort); + return Boolean(after && after.length === 1 && after[0] === pid); +} diff --git a/src/lib/onboard/dashboard-forward-control.ts b/src/lib/onboard/dashboard-forward-control.ts index ea4f66451e1..1349c398901 100644 --- a/src/lib/onboard/dashboard-forward-control.ts +++ b/src/lib/onboard/dashboard-forward-control.ts @@ -6,9 +6,8 @@ export interface DashboardForwardOptions { gatewayName?: string; allowPortReallocation?: boolean; /** - * Preserve a bound port only when the caller has durable evidence that this - * onboarding attempt reused the registered sandbox and will run deployment - * verification before reporting success. + * Permit an ownership probe for a bound registered port only when the caller + * has durable evidence that this attempt reused the registered sandbox. */ preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 35d86bd78ab..7d72fc7f8db 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -8,6 +8,7 @@ import { launchForwardService, type ForwardServiceTarget, } from "../adapters/openshell/forward-service"; +import { isForwardServiceListenerOwned } from "../adapters/openshell/forward-service-ownership"; import type { AgentDefinition } from "../agent/defs"; import { getInteractiveAgentCommand } from "../agent/gateway-restart-scripts"; import { DASHBOARD_PORT } from "../core/ports"; @@ -89,6 +90,7 @@ export interface OnboardDashboardDeps { forwardService?: { executable(): string; launch?(target: ForwardServiceTarget): void; + owns?(target: ForwardServiceTarget): boolean; retireLegacy?(sandboxName: string, gatewayName: string, ports: readonly number[]): number; resolveGatewayName( sandbox: { gatewayName?: string | null; gatewayPort?: number | null } | null | undefined, @@ -231,6 +233,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa if (!executable) throw new Error("OpenShell is unavailable"); return executable; }, + owns: isForwardServiceListenerOwned, resolveGatewayName: productionForwardService.resolveGatewayName, retireLegacy: (sandboxName: string, gatewayName: string, ports: readonly number[]) => productionForwardService.retireLegacy(sandboxName, gatewayName, ports, { @@ -412,7 +415,14 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa revalidateSandboxIdentity?.( `preserve registered dashboard forward ${String(preferredPort)} for sandbox '${sandboxName}'`, ); - return preferredPort; + const preferredTarget = getDashboardForwardTarget(chatUiUrl); + if ( + forwardService?.owns?.( + forwardTarget(sandboxName, forwardGateway, preferredPort, preferredTarget), + ) === true + ) { + return preferredPort; + } } throw new Error( `Registered dashboard port ${String(preferredPort)} is already occupied; it cannot be reallocated or adopted.`, diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index df38fbe1de2..eea8886674e 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -3,12 +3,14 @@ import { describe, expect, it, vi } from "vitest"; +import type { ForwardServiceTarget } from "../../src/lib/adapters/openshell/forward-service"; import { createOnboardDashboardHelpers } from "../../src/lib/onboard/dashboard"; import type { ListSandboxesFn } from "../../src/lib/onboard/dashboard-port"; function harness(options: { listSandboxes: ListSandboxesFn; isPortBound?: (port: number) => boolean; + ownsForward?: (target: ForwardServiceTarget) => boolean; }) { const launch = vi.fn(); const helpers = createOnboardDashboardHelpers({ @@ -28,6 +30,7 @@ function harness(options: { forwardService: { executable: () => "/usr/local/bin/openshell", launch, + owns: options.ownsForward, resolveGatewayName: () => "nemoclaw", retireLegacy: vi.fn(() => 0), }, @@ -73,11 +76,13 @@ describe("finalization dashboard ForwardTcp launch", () => { it("preserves the registered ForwardTcp listener during Ready sandbox reuse (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); + const ownsForward = vi.fn(() => true); const { helpers, launch } = harness({ listSandboxes: () => ({ sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], }), isPortBound: (port) => port === 18_790, + ownsForward, }); expect( @@ -85,10 +90,37 @@ describe("finalization dashboard ForwardTcp launch", () => { preserveRegisteredForward: true, }), ).toBe(18_790); + expect(ownsForward).toHaveBeenCalledWith( + expect.objectContaining({ + gatewayName: "nemoclaw", + sandboxName: "reonboard-test", + localPort: 18_790, + targetPort: 18_790, + }), + ); expect(launch).not.toHaveBeenCalled(); expect(process.env.CHAT_UI_URL).toBe("http://127.0.0.1:18790"); }); + it("rejects an unowned listener during Ready sandbox reuse (#11074)", () => { + vi.stubEnv("CHAT_UI_URL", undefined); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + isPortBound: (port) => port === 18_790, + ownsForward: () => false, + }); + + expect(() => + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toThrow(/cannot be reallocated/u); + expect(launch).not.toHaveBeenCalled(); + expect(process.env.CHAT_UI_URL).toBeUndefined(); + }); + it("does not preserve a reused port registered to another sandbox (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); const { helpers, launch } = harness({ From 80d61797521f4339dd9aa46b1476b04589a44c82 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 11:12:03 +0700 Subject: [PATCH 03/12] fix(onboard): harden reused forward recovery Signed-off-by: San Dang --- .../forward-service-ownership.test.ts | 38 +++++ .../openshell/forward-service-ownership.ts | 147 ++++++++++++++++-- src/lib/onboard.ts | 2 +- src/lib/onboard/dashboard.ts | 26 ++-- .../machine/handlers/agent-setup.test.ts | 41 +++++ .../onboard/machine/handlers/agent-setup.ts | 16 +- ...ard-finalization-dashboard-forward.test.ts | 39 ++++- 7 files changed, 277 insertions(+), 32 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service-ownership.test.ts b/src/lib/adapters/openshell/forward-service-ownership.test.ts index d59484aa5a0..6ae222c89d6 100644 --- a/src/lib/adapters/openshell/forward-service-ownership.test.ts +++ b/src/lib/adapters/openshell/forward-service-ownership.test.ts @@ -5,7 +5,9 @@ import { describe, expect, it, vi } from "vitest"; import { buildForwardServiceArgs, type ForwardServiceTarget } from "./forward-service"; import { + inspectForwardServiceListenerOwnership, isForwardServiceListenerOwned, + listLinuxProcListenerPids, type ForwardServiceOwnershipDeps, } from "./forward-service-ownership"; @@ -124,4 +126,40 @@ describe("direct ForwardTcp listener ownership", () => { ), ).toBe(false); }); + + it("uses Linux procfs when lsof cannot enumerate the listener", () => { + const { listListenerPids: _listListenerPids, ...fallbackDeps } = ownership(); + const listLinuxProcListenerPids = vi.fn(() => [4_242]); + + expect( + isForwardServiceListenerOwned(target, { + ...fallbackDeps, + platform: "linux", + listLsofListenerPids: () => null, + listLinuxProcListenerPids, + }), + ).toBe(true); + expect(listLinuxProcListenerPids).toHaveBeenCalledTimes(2); + }); + + it("resolves a listening IPv4 socket inode to its procfs PID", () => { + expect( + listLinuxProcListenerPids(18_790, { + readFile: (file) => + file === "/proc/net/tcp" + ? "sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + + "0: 0100007F:4966 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 777\n" + : null, + readDirectory: (directory) => + ({ "/proc": ["42", "self"], "/proc/42/fd": ["3", "4"] })[directory] ?? null, + readLink: (file) => (file.endsWith("/3") ? "socket:[777]" : "socket:[999]"), + }), + ).toEqual([42]); + }); + + it("reports unavailable listener enumeration distinctly", () => { + expect( + inspectForwardServiceListenerOwnership(target, ownership({ listListenerPids: () => null })), + ).toEqual({ owned: false, failure: "listener-enumeration-unavailable" }); + }); }); diff --git a/src/lib/adapters/openshell/forward-service-ownership.ts b/src/lib/adapters/openshell/forward-service-ownership.ts index b70a505a7aa..48927424c75 100644 --- a/src/lib/adapters/openshell/forward-service-ownership.ts +++ b/src/lib/adapters/openshell/forward-service-ownership.ts @@ -25,11 +25,30 @@ export interface ForwardServiceProcessSnapshot { export interface ForwardServiceOwnershipDeps { readonly currentUid?: () => number | null; readonly inspectProcess?: (pid: number) => ForwardServiceProcessSnapshot | null; + readonly listLinuxProcListenerPids?: (port: number) => readonly number[] | null; + readonly listLsofListenerPids?: (port: number) => readonly number[] | null; readonly listListenerPids?: (port: number) => readonly number[] | null; + readonly platform?: NodeJS.Platform; readonly realpath?: (value: string) => string | null; readonly sourceEnvironment?: NodeJS.ProcessEnv; } +export type ForwardServiceOwnershipFailure = + | "listener-changed" + | "listener-enumeration-unavailable" + | "listener-not-unique" + | "process-identity-mismatch"; + +export type ForwardServiceOwnershipResult = + | { readonly owned: true } + | { readonly owned: false; readonly failure: ForwardServiceOwnershipFailure }; + +export interface LinuxProcSocketDeps { + readonly readDirectory?: (directory: string) => readonly string[] | null; + readonly readFile?: (file: string) => string | null; + readonly readLink?: (file: string) => string | null; +} + function probeExecutable(candidates: readonly string[]): string | null { return candidates.find((candidate) => fs.existsSync(candidate)) ?? null; } @@ -44,7 +63,7 @@ function runProbe(executable: string, args: readonly string[]) { }); } -function listListenerPids(port: number): readonly number[] | null { +function listLsofListenerPids(port: number): readonly number[] | null { const lsof = probeExecutable(["/usr/sbin/lsof", "/usr/bin/lsof"]); if (!lsof) return null; const result = runProbe(lsof, ["-nP", `-iTCP:${String(port)}`, "-sTCP:LISTEN", "-Fp"]); @@ -57,6 +76,89 @@ function listListenerPids(port: number): readonly number[] | null { return [...pids]; } +function readFile(file: string): string | null { + try { + return fs.readFileSync(file, "utf8"); + } catch { + return null; + } +} + +function readDirectory(directory: string): readonly string[] | null { + try { + return fs.readdirSync(directory); + } catch { + return null; + } +} + +function readLink(file: string): string | null { + try { + return fs.readlinkSync(file); + } catch { + return null; + } +} + +function linuxTcpListenerInodes(table: string, port: number): ReadonlySet { + const portHex = port.toString(16).padStart(4, "0").toUpperCase(); + const inodes = new Set(); + for (const line of table.split(/\r?\n/u).slice(1)) { + const fields = line.trim().split(/\s+/u); + if (fields.length < 10) continue; + const localPort = fields[1]?.split(":").at(-1)?.toUpperCase(); + if (fields[3] === "0A" && localPort === portHex && /^\d+$/u.test(fields[9] ?? "")) { + inodes.add(fields[9] as string); + } + } + return inodes; +} + +/** Resolve an IPv4 listener to its Linux procfs process owners. */ +export function listLinuxProcListenerPids( + port: number, + deps: LinuxProcSocketDeps = {}, +): readonly number[] | null { + const readProcFile = deps.readFile ?? readFile; + const table = readProcFile("/proc/net/tcp"); + if (table === null) return null; + const socketInodes = linuxTcpListenerInodes(table, port); + if (socketInodes.size === 0) return []; + const entries = (deps.readDirectory ?? readDirectory)("/proc"); + if (!entries) return null; + const readProcDirectory = deps.readDirectory ?? readDirectory; + const readProcLink = deps.readLink ?? readLink; + const pids = new Set(); + for (const entry of entries) { + if (!/^[1-9]\d*$/u.test(entry)) continue; + const descriptors = readProcDirectory(`/proc/${entry}/fd`); + if (!descriptors) continue; + for (const descriptor of descriptors) { + const link = readProcLink(`/proc/${entry}/fd/${descriptor}`); + const match = /^socket:\[(\d+)\]$/u.exec(link ?? ""); + if (match && socketInodes.has(match[1] as string)) { + pids.add(Number(entry)); + break; + } + } + } + return [...pids]; +} + +function ownershipListenerPids( + port: number, + deps: ForwardServiceOwnershipDeps, +): readonly number[] | null { + if (deps.listListenerPids) return deps.listListenerPids(port); + const lsof = (deps.listLsofListenerPids ?? listLsofListenerPids)(port); + if (lsof && lsof.length > 0) return lsof; + if ((deps.platform ?? process.platform) === "linux") { + const proc = (deps.listLinuxProcListenerPids ?? listLinuxProcListenerPids)(port); + if (proc !== null) return proc; + } + return lsof; +} + function processUid(pid: number): number | null { try { const uid = fs.statSync(`/proc/${String(pid)}`).uid; @@ -113,7 +215,7 @@ function processEnvironment(pid: number): Readonly> | nul fs .readFileSync(`/proc/${String(pid)}/environ`, "utf8") .split("\0") - .filter(Boolean) + .filter((entry) => entry.includes("=")) .map((entry) => [entry.slice(0, entry.indexOf("=")), entry.slice(entry.indexOf("=") + 1)]), ); } catch { @@ -156,17 +258,20 @@ function sameArgv(actual: readonly string[], expected: readonly string[]): boole ); } -/** Prove that a bound port belongs to the exact direct ForwardTcp command. */ -export function isForwardServiceListenerOwned( +/** Explain whether a bound port belongs to the exact direct ForwardTcp command. */ +export function inspectForwardServiceListenerOwnership( target: ForwardServiceTarget, deps: ForwardServiceOwnershipDeps = {}, -): boolean { +): ForwardServiceOwnershipResult { validateForwardServiceTarget(target); - const enumerate = deps.listListenerPids ?? listListenerPids; + const enumerate = (port: number) => ownershipListenerPids(port, deps); const before = enumerate(target.localPort); - if (!before || before.length !== 1) return false; + if (before === null) return { owned: false, failure: "listener-enumeration-unavailable" }; + if (before.length !== 1) return { owned: false, failure: "listener-not-unique" }; const pid = before[0]; - if (!Number.isSafeInteger(pid) || pid <= 0) return false; + if (!Number.isSafeInteger(pid) || pid <= 0) { + return { owned: false, failure: "listener-not-unique" }; + } const currentUid = deps.currentUid ? deps.currentUid() @@ -174,7 +279,9 @@ export function isForwardServiceListenerOwned( ? process.getuid() : null; const snapshot = (deps.inspectProcess ?? inspectProcess)(pid); - if (!snapshot || currentUid === null || snapshot.uid !== currentUid) return false; + if (!snapshot || currentUid === null || snapshot.uid !== currentUid) { + return { owned: false, failure: "process-identity-mismatch" }; + } const expectedEnvironment = buildOpenShellSubprocessEnv(deps.sourceEnvironment ?? process.env); if ( !expectedEnvironment.HOME || @@ -182,19 +289,33 @@ export function isForwardServiceListenerOwned( snapshot.environment.XDG_CONFIG_HOME !== expectedEnvironment.XDG_CONFIG_HOME || snapshot.environment.XDG_RUNTIME_DIR !== expectedEnvironment.XDG_RUNTIME_DIR ) { - return false; + return { owned: false, failure: "process-identity-mismatch" }; } const resolvePath = deps.realpath ?? realpath; const expectedExecutable = resolvePath(target.executable); const observedExecutable = snapshot.executable ? resolvePath(snapshot.executable) : null; - if (!expectedExecutable || observedExecutable !== expectedExecutable) return false; + if (!expectedExecutable || observedExecutable !== expectedExecutable) { + return { owned: false, failure: "process-identity-mismatch" }; + } const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; const invocationMatches = snapshot.argv ? sameArgv(snapshot.argv, expectedArgv) : snapshot.commandLine === expectedArgv.join(" "); - if (!invocationMatches) return false; + if (!invocationMatches) return { owned: false, failure: "process-identity-mismatch" }; const after = enumerate(target.localPort); - return Boolean(after && after.length === 1 && after[0] === pid); + if (after === null) return { owned: false, failure: "listener-enumeration-unavailable" }; + if (after.length !== 1 || after[0] !== pid) { + return { owned: false, failure: "listener-changed" }; + } + return { owned: true }; +} + +/** Prove that a bound port belongs to the exact direct ForwardTcp command. */ +export function isForwardServiceListenerOwned( + target: ForwardServiceTarget, + deps: ForwardServiceOwnershipDeps = {}, +): boolean { + return inspectForwardServiceListenerOwnership(target, deps).owned; } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 5a445425f31..08315e6ff23 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -3248,7 +3248,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { ensureAgentDashboardForward: (name, selectedAgent, options) => ensureFinalizationAgentDashboardForward(name, selectedAgent, { portReservation: hermesApiPortReservationScope, - preserveRegisteredForward: options?.preserveRegisteredForward === true, + ...(options ?? {}), }), persistDashboardPort: (name, port) => registry.updateSandbox(name, { dashboardPort: port }), diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 7d72fc7f8db..78b11b76cd3 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -8,7 +8,10 @@ import { launchForwardService, type ForwardServiceTarget, } from "../adapters/openshell/forward-service"; -import { isForwardServiceListenerOwned } from "../adapters/openshell/forward-service-ownership"; +import { + inspectForwardServiceListenerOwnership, + type ForwardServiceOwnershipResult, +} from "../adapters/openshell/forward-service-ownership"; import type { AgentDefinition } from "../agent/defs"; import { getInteractiveAgentCommand } from "../agent/gateway-restart-scripts"; import { DASHBOARD_PORT } from "../core/ports"; @@ -89,8 +92,8 @@ export interface OnboardDashboardDeps { /** Direct ForwardTcp launcher. */ forwardService?: { executable(): string; + inspectOwnership?(target: ForwardServiceTarget): ForwardServiceOwnershipResult; launch?(target: ForwardServiceTarget): void; - owns?(target: ForwardServiceTarget): boolean; retireLegacy?(sandboxName: string, gatewayName: string, ports: readonly number[]): number; resolveGatewayName( sandbox: { gatewayName?: string | null; gatewayPort?: number | null } | null | undefined, @@ -233,7 +236,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa if (!executable) throw new Error("OpenShell is unavailable"); return executable; }, - owns: isForwardServiceListenerOwned, + inspectOwnership: inspectForwardServiceListenerOwnership, resolveGatewayName: productionForwardService.resolveGatewayName, retireLegacy: (sandboxName: string, gatewayName: string, ports: readonly number[]) => productionForwardService.retireLegacy(sandboxName, gatewayName, ports, { @@ -416,12 +419,17 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa `preserve registered dashboard forward ${String(preferredPort)} for sandbox '${sandboxName}'`, ); const preferredTarget = getDashboardForwardTarget(chatUiUrl); - if ( - forwardService?.owns?.( - forwardTarget(sandboxName, forwardGateway, preferredPort, preferredTarget), - ) === true - ) { - return preferredPort; + const ownership = forwardService?.inspectOwnership?.( + forwardTarget(sandboxName, forwardGateway, preferredPort, preferredTarget), + ); + if (ownership?.owned === true) return preferredPort; + if (ownership?.failure === "listener-enumeration-unavailable") { + throw new Error( + `Registered dashboard port ${String(preferredPort)} is occupied, but its ForwardTcp ` + + "ownership could not be verified because listener enumeration is unavailable. " + + "Install lsof or restore read access to Linux /proc, then re-run " + + `\`${deps.cliName()} onboard --resume\`; the listener was not adopted.`, + ); } } throw new Error( diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index 3cc935de420..347066ae181 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -183,6 +183,47 @@ describe("handleAgentSetupState", () => { }); }); + it("revalidates sandbox identity before inspecting a reused forward (#11074)", async () => { + const inspectForward = vi.fn(); + const revalidateSandboxIdentity = vi.fn(); + revalidateSandboxIdentity + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("sandbox identity changed"); + }); + const ensureAgentDashboardForward = vi.fn( + ( + _sandboxName: string, + _agent: Agent | null, + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + }, + ) => { + options?.revalidateSandboxIdentity?.("inspect reused dashboard forward"); + inspectForward(); + return 18_789; + }, + ); + const { deps } = createDeps({ ensureAgentDashboardForward }); + const session = createSession(); + session.steps.sandbox.status = "skipped"; + + await expect( + handleAgentSetupState({ + ...baseOptions(deps), + session, + revalidateSandboxIdentity, + }), + ).rejects.toThrow("sandbox identity changed"); + expect(ensureAgentDashboardForward).toHaveBeenCalledWith("my-assistant", null, { + preserveRegisteredForward: true, + revalidateSandboxIdentity, + }); + expect(inspectForward).not.toHaveBeenCalled(); + }); + it("delegates shared OpenClaw configuration before ready-resume completion", async () => { const { deps, calls } = createDeps({ isOpenclawReady: vi.fn(() => true) }); const revalidateSandboxIdentity = vi.fn(); diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index dca779c700a..7403d9dd9aa 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -31,7 +31,10 @@ export interface AgentSetupStateOptions { ensureAgentDashboardForward( sandboxName: string, agent: Agent | null, - options?: { preserveRegisteredForward?: boolean }, + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + }, ): Promise | number; persistDashboardPort(sandboxName: string, dashboardPort: number): void; recordStepSkipped(stepName: string): Promise; @@ -141,8 +144,15 @@ export async function handleAgentSetupState({ deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } - const dashboardPort = await (preserveRegisteredForward - ? deps.ensureAgentDashboardForward(sandboxName, null, { preserveRegisteredForward: true }) + const dashboardOptions = + preserveRegisteredForward || revalidateSandboxIdentity + ? { + ...(preserveRegisteredForward ? { preserveRegisteredForward: true } : {}), + ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), + } + : undefined; + const dashboardPort = await (dashboardOptions + ? deps.ensureAgentDashboardForward(sandboxName, null, dashboardOptions) : deps.ensureAgentDashboardForward(sandboxName, null)); if (dashboardPort > 0) { deps.persistDashboardPort(sandboxName, dashboardPort); diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index eea8886674e..5716c047bbe 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -4,13 +4,14 @@ import { describe, expect, it, vi } from "vitest"; import type { ForwardServiceTarget } from "../../src/lib/adapters/openshell/forward-service"; +import type { ForwardServiceOwnershipResult } from "../../src/lib/adapters/openshell/forward-service-ownership"; import { createOnboardDashboardHelpers } from "../../src/lib/onboard/dashboard"; import type { ListSandboxesFn } from "../../src/lib/onboard/dashboard-port"; function harness(options: { listSandboxes: ListSandboxesFn; + inspectOwnership?: (target: ForwardServiceTarget) => ForwardServiceOwnershipResult; isPortBound?: (port: number) => boolean; - ownsForward?: (target: ForwardServiceTarget) => boolean; }) { const launch = vi.fn(); const helpers = createOnboardDashboardHelpers({ @@ -29,8 +30,8 @@ function harness(options: { isPortBoundOnHost: options.isPortBound ?? (() => false), forwardService: { executable: () => "/usr/local/bin/openshell", + inspectOwnership: options.inspectOwnership, launch, - owns: options.ownsForward, resolveGatewayName: () => "nemoclaw", retireLegacy: vi.fn(() => 0), }, @@ -76,21 +77,28 @@ describe("finalization dashboard ForwardTcp launch", () => { it("preserves the registered ForwardTcp listener during Ready sandbox reuse (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); - const ownsForward = vi.fn(() => true); + const revalidateSandboxIdentity = vi.fn(); + const inspectOwnership = vi.fn(() => { + expect(revalidateSandboxIdentity).toHaveBeenCalledWith( + "preserve registered dashboard forward 18790 for sandbox 'reonboard-test'", + ); + return { owned: true } as const; + }); const { helpers, launch } = harness({ listSandboxes: () => ({ sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], }), + inspectOwnership, isPortBound: (port) => port === 18_790, - ownsForward, }); expect( helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, + revalidateSandboxIdentity, }), ).toBe(18_790); - expect(ownsForward).toHaveBeenCalledWith( + expect(inspectOwnership).toHaveBeenCalledWith( expect.objectContaining({ gatewayName: "nemoclaw", sandboxName: "reonboard-test", @@ -108,8 +116,8 @@ describe("finalization dashboard ForwardTcp launch", () => { listSandboxes: () => ({ sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], }), + inspectOwnership: () => ({ owned: false, failure: "process-identity-mismatch" }), isPortBound: (port) => port === 18_790, - ownsForward: () => false, }); expect(() => @@ -121,6 +129,25 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(process.env.CHAT_UI_URL).toBeUndefined(); }); + it("reports unavailable ownership observation during Ready sandbox reuse (#11074)", () => { + vi.stubEnv("CHAT_UI_URL", undefined); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + inspectOwnership: () => ({ owned: false, failure: "listener-enumeration-unavailable" }), + isPortBound: (port) => port === 18_790, + }); + + expect(() => + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toThrow(/Install lsof or restore read access to Linux \/proc/u); + expect(launch).not.toHaveBeenCalled(); + expect(process.env.CHAT_UI_URL).toBeUndefined(); + }); + it("does not preserve a reused port registered to another sandbox (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); const { helpers, launch } = harness({ From 7104db784ca0635ec71d4d4ba03843150521aa60 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 11:52:14 +0700 Subject: [PATCH 04/12] fix(onboard): complete dashboard reuse handoff Signed-off-by: San Dang --- .../forward-service-ownership.test.ts | 86 ++++++++++++----- .../openshell/forward-service-ownership.ts | 94 +++++++++++++------ src/lib/onboard.ts | 8 +- src/lib/onboard/machine/core-flow-phases.ts | 3 + .../onboard/machine/final-flow-phases.test.ts | 19 ++++ src/lib/onboard/machine/final-flow-phases.ts | 1 + src/lib/onboard/machine/flow-context.ts | 3 + .../onboard/machine/handlers/agent-setup.ts | 3 +- .../machine/handlers/sandbox-test-fixtures.ts | 6 +- .../onboard/machine/handlers/sandbox.test.ts | 7 +- src/lib/onboard/machine/handlers/sandbox.ts | 26 ++++- .../onboard/sandbox-create/orchestration.ts | 31 +++++- .../onboard/sandbox-recreate-transaction.ts | 26 +++++ src/lib/onboard/sandbox-reuse.test.ts | 31 +++++- src/lib/onboard/sandbox-reuse.ts | 16 +++- test/e2e/live/double-onboard.test.ts | 75 ++++++++++++--- test/helpers/onboard-final-flow-phases.ts | 3 +- 17 files changed, 354 insertions(+), 84 deletions(-) diff --git a/src/lib/adapters/openshell/forward-service-ownership.test.ts b/src/lib/adapters/openshell/forward-service-ownership.test.ts index 6ae222c89d6..ea41bb4ce40 100644 --- a/src/lib/adapters/openshell/forward-service-ownership.test.ts +++ b/src/lib/adapters/openshell/forward-service-ownership.test.ts @@ -6,9 +6,9 @@ import { describe, expect, it, vi } from "vitest"; import { buildForwardServiceArgs, type ForwardServiceTarget } from "./forward-service"; import { inspectForwardServiceListenerOwnership, - isForwardServiceListenerOwned, listLinuxProcListenerPids, type ForwardServiceOwnershipDeps, + type ForwardServiceProcessSnapshot, } from "./forward-service-ownership"; const target: ForwardServiceTarget = { @@ -22,16 +22,20 @@ const target: ForwardServiceTarget = { targetPort: 18_790, }; +function ownedProcessSnapshot(): ForwardServiceProcessSnapshot { + return { + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + }; +} + function ownership(overrides: Partial = {}) { return { currentUid: () => 1_000, - inspectProcess: () => ({ - argv: [target.executable, ...buildForwardServiceArgs(target)], - commandLine: null, - environment: { HOME: "/home/operator" }, - executable: target.executable, - uid: 1_000, - }), + inspectProcess: () => ownedProcessSnapshot(), listListenerPids: vi.fn(() => [4_242]), realpath: (value: string) => value, sourceEnvironment: { HOME: "/home/operator" }, @@ -43,13 +47,13 @@ describe("direct ForwardTcp listener ownership", () => { it("accepts one stable listener with the exact user, executable, and target argv", () => { const deps = ownership(); - expect(isForwardServiceListenerOwned(target, deps)).toBe(true); + expect(inspectForwardServiceListenerOwnership(target, deps)).toEqual({ owned: true }); expect(deps.listListenerPids).toHaveBeenCalledTimes(2); }); it("accepts the exact ps command line when procfs argv is unavailable", () => { expect( - isForwardServiceListenerOwned( + inspectForwardServiceListenerOwnership( target, ownership({ inspectProcess: () => ({ @@ -61,7 +65,7 @@ describe("direct ForwardTcp listener ownership", () => { }), }), ), - ).toBe(true); + ).toEqual({ owned: true }); }); it.each([ @@ -78,7 +82,7 @@ describe("direct ForwardTcp listener ownership", () => { ], ])("rejects a %s listener", (_case, replacement) => { expect( - isForwardServiceListenerOwned( + inspectForwardServiceListenerOwnership( target, ownership({ inspectProcess: () => ({ @@ -91,28 +95,30 @@ describe("direct ForwardTcp listener ownership", () => { }), }), ), - ).toBe(false); + ).toMatchObject({ owned: false }); }); it("rejects an incomplete or changing listener scan", () => { const listListenerPids = vi.fn<() => readonly number[] | null>(); listListenerPids.mockReturnValueOnce([4_242]).mockReturnValueOnce([4_243]); - expect(isForwardServiceListenerOwned(target, ownership({ listListenerPids }))).toBe(false); - expect(isForwardServiceListenerOwned(target, ownership({ listListenerPids: () => null }))).toBe( - false, - ); + expect( + inspectForwardServiceListenerOwnership(target, ownership({ listListenerPids })), + ).toMatchObject({ owned: false }); + expect( + inspectForwardServiceListenerOwnership(target, ownership({ listListenerPids: () => null })), + ).toMatchObject({ owned: false }); }); it("rejects a listener when the current user cannot be proven", () => { - expect(isForwardServiceListenerOwned(target, ownership({ currentUid: () => null }))).toBe( - false, - ); + expect( + inspectForwardServiceListenerOwnership(target, ownership({ currentUid: () => null })), + ).toMatchObject({ owned: false }); }); it("rejects a listener from another OpenShell configuration home", () => { expect( - isForwardServiceListenerOwned( + inspectForwardServiceListenerOwnership( target, ownership({ inspectProcess: () => ({ @@ -124,7 +130,7 @@ describe("direct ForwardTcp listener ownership", () => { }), }), ), - ).toBe(false); + ).toMatchObject({ owned: false }); }); it("uses Linux procfs when lsof cannot enumerate the listener", () => { @@ -132,13 +138,13 @@ describe("direct ForwardTcp listener ownership", () => { const listLinuxProcListenerPids = vi.fn(() => [4_242]); expect( - isForwardServiceListenerOwned(target, { + inspectForwardServiceListenerOwnership(target, { ...fallbackDeps, platform: "linux", listLsofListenerPids: () => null, listLinuxProcListenerPids, }), - ).toBe(true); + ).toEqual({ owned: true }); expect(listLinuxProcListenerPids).toHaveBeenCalledTimes(2); }); @@ -157,6 +163,38 @@ describe("direct ForwardTcp listener ownership", () => { ).toEqual([42]); }); + it("stops procfs enumeration when the process scan exceeds its bound", () => { + const readLink = vi.fn(() => "socket:[777]"); + + expect( + listLinuxProcListenerPids(18_790, { + readFile: () => + "sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + + "0: 0100007F:4966 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 777\n", + readDirectory: (directory) => + directory === "/proc" + ? Array.from({ length: 4_097 }, (_value, index) => String(index + 1)) + : ["3"], + readLink, + }), + ).toBeNull(); + expect(readLink).not.toHaveBeenCalled(); + }); + + it("rejects PID reuse after the stable listener scan", () => { + const validProcess = ownedProcessSnapshot(); + const inspectProcess = vi + .fn() + .mockReturnValueOnce(validProcess) + .mockReturnValueOnce({ ...validProcess, executable: "/usr/bin/python3" }); + + expect(inspectForwardServiceListenerOwnership(target, ownership({ inspectProcess }))).toEqual({ + owned: false, + failure: "process-identity-mismatch", + }); + expect(inspectProcess).toHaveBeenCalledTimes(2); + }); + it("reports unavailable listener enumeration distinctly", () => { expect( inspectForwardServiceListenerOwnership(target, ownership({ listListenerPids: () => null })), diff --git a/src/lib/adapters/openshell/forward-service-ownership.ts b/src/lib/adapters/openshell/forward-service-ownership.ts index 48927424c75..942e970f55c 100644 --- a/src/lib/adapters/openshell/forward-service-ownership.ts +++ b/src/lib/adapters/openshell/forward-service-ownership.ts @@ -13,6 +13,9 @@ import { const PROBE_TIMEOUT_MS = 1_000; const PROBE_MAX_BUFFER_BYTES = 16 * 1024; +const LINUX_PROC_MAX_PROCESSES = 4_096; +const LINUX_PROC_MAX_DESCRIPTORS_PER_PROCESS = 4_096; +const LINUX_PROC_MAX_TOTAL_DESCRIPTORS = 32_768; export interface ForwardServiceProcessSnapshot { readonly argv: readonly string[] | null; @@ -126,13 +129,22 @@ export function listLinuxProcListenerPids( if (socketInodes.size === 0) return []; const entries = (deps.readDirectory ?? readDirectory)("/proc"); if (!entries) return null; + const processEntries = entries.filter((entry) => /^[1-9]\d*$/u.test(entry)); + if (processEntries.length > LINUX_PROC_MAX_PROCESSES) return null; const readProcDirectory = deps.readDirectory ?? readDirectory; const readProcLink = deps.readLink ?? readLink; const pids = new Set(); - for (const entry of entries) { - if (!/^[1-9]\d*$/u.test(entry)) continue; + let descriptorCount = 0; + for (const entry of processEntries) { const descriptors = readProcDirectory(`/proc/${entry}/fd`); if (!descriptors) continue; + descriptorCount += descriptors.length; + if ( + descriptors.length > LINUX_PROC_MAX_DESCRIPTORS_PER_PROCESS || + descriptorCount > LINUX_PROC_MAX_TOTAL_DESCRIPTORS + ) { + return null; + } for (const descriptor of descriptors) { const link = readProcLink(`/proc/${entry}/fd/${descriptor}`); const match = /^socket:\[(\d+)\]$/u.exec(link ?? ""); @@ -258,6 +270,33 @@ function sameArgv(actual: readonly string[], expected: readonly string[]): boole ); } +function processMatchesForwardTarget( + pid: number, + deps: ForwardServiceOwnershipDeps, + currentUid: number, + expectedEnvironment: NodeJS.ProcessEnv, + expectedExecutable: string, + expectedArgv: readonly string[], +): boolean { + const snapshot = (deps.inspectProcess ?? inspectProcess)(pid); + if (!snapshot || snapshot.uid !== currentUid) return false; + const environment = snapshot.environment; + if ( + !environment || + environment.HOME !== expectedEnvironment.HOME || + environment.XDG_CONFIG_HOME !== expectedEnvironment.XDG_CONFIG_HOME || + environment.XDG_RUNTIME_DIR !== expectedEnvironment.XDG_RUNTIME_DIR + ) { + return false; + } + const resolvePath = deps.realpath ?? realpath; + const observedExecutable = snapshot.executable ? resolvePath(snapshot.executable) : null; + if (observedExecutable !== expectedExecutable) return false; + return snapshot.argv + ? sameArgv(snapshot.argv, expectedArgv) + : snapshot.commandLine === expectedArgv.join(" "); +} + /** Explain whether a bound port belongs to the exact direct ForwardTcp command. */ export function inspectForwardServiceListenerOwnership( target: ForwardServiceTarget, @@ -278,44 +317,41 @@ export function inspectForwardServiceListenerOwnership( : typeof process.getuid === "function" ? process.getuid() : null; - const snapshot = (deps.inspectProcess ?? inspectProcess)(pid); - if (!snapshot || currentUid === null || snapshot.uid !== currentUid) { + const expectedEnvironment = buildOpenShellSubprocessEnv(deps.sourceEnvironment ?? process.env); + const expectedExecutable = (deps.realpath ?? realpath)(target.executable); + const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; + if (currentUid === null || !expectedEnvironment.HOME || !expectedExecutable) { return { owned: false, failure: "process-identity-mismatch" }; } - const expectedEnvironment = buildOpenShellSubprocessEnv(deps.sourceEnvironment ?? process.env); if ( - !expectedEnvironment.HOME || - snapshot.environment?.HOME !== expectedEnvironment.HOME || - snapshot.environment.XDG_CONFIG_HOME !== expectedEnvironment.XDG_CONFIG_HOME || - snapshot.environment.XDG_RUNTIME_DIR !== expectedEnvironment.XDG_RUNTIME_DIR + !processMatchesForwardTarget( + pid, + deps, + currentUid, + expectedEnvironment, + expectedExecutable, + expectedArgv, + ) ) { return { owned: false, failure: "process-identity-mismatch" }; } - const resolvePath = deps.realpath ?? realpath; - const expectedExecutable = resolvePath(target.executable); - const observedExecutable = snapshot.executable ? resolvePath(snapshot.executable) : null; - if (!expectedExecutable || observedExecutable !== expectedExecutable) { - return { owned: false, failure: "process-identity-mismatch" }; - } - - const expectedArgv = [target.executable, ...buildForwardServiceArgs(target)]; - const invocationMatches = snapshot.argv - ? sameArgv(snapshot.argv, expectedArgv) - : snapshot.commandLine === expectedArgv.join(" "); - if (!invocationMatches) return { owned: false, failure: "process-identity-mismatch" }; const after = enumerate(target.localPort); if (after === null) return { owned: false, failure: "listener-enumeration-unavailable" }; if (after.length !== 1 || after[0] !== pid) { return { owned: false, failure: "listener-changed" }; } + if ( + !processMatchesForwardTarget( + pid, + deps, + currentUid, + expectedEnvironment, + expectedExecutable, + expectedArgv, + ) + ) { + return { owned: false, failure: "process-identity-mismatch" }; + } return { owned: true }; } - -/** Prove that a bound port belongs to the exact direct ForwardTcp command. */ -export function isForwardServiceListenerOwned( - target: ForwardServiceTarget, - deps: ForwardServiceOwnershipDeps = {}, -): boolean { - return inspectForwardServiceListenerOwnership(target, deps).owned; -} diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 08315e6ff23..19421fdf9a9 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2701,6 +2701,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { initialHint: opts.baseImageResolutionHint, initialPreResolvedMetadata: opts.preResolvedBaseImageMetadata, }); + let reusedSandboxIdentityRevalidation: ((operation: string) => void) | undefined; const lockedRuntime = await resumeRuntime.prepare( opts, resume, @@ -2790,9 +2791,8 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { } const effectiveHostMounts = hostMountScope.activate(session?.metadata.hostMounts); await onboardRuntimeBoundary.recordOnboardStarted(resume); - // Resume backstop: a session may exist without a sandboxName if sandbox - // creation failed before that step. Non-interactive --from cannot infer a - // safe name in that state. + // A resumed session may lack a sandbox name when creation failed before that step; + // non-interactive --from cannot infer a safe name in that state. if ( resume && cannotPrompt && @@ -3191,9 +3191,11 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { hermesApiPortReservationScope, ...createArgs, opts.allowRemovedImmutabilityStateRecord === true, + (revalidate) => (reusedSandboxIdentityRevalidation = revalidate), ), ), ), + takeReusedSandboxIdentityRevalidation: () => reusedSandboxIdentityRevalidation, updateSandboxRegistry: (name, updates) => registry.updateSandbox(name, updates), finalizeSandboxRouteReservation: registry.finalizeSandboxRouteReservation, getSandboxAgentRegistryFields, diff --git a/src/lib/onboard/machine/core-flow-phases.ts b/src/lib/onboard/machine/core-flow-phases.ts index 17e4f84e96e..7d6a71112c0 100644 --- a/src/lib/onboard/machine/core-flow-phases.ts +++ b/src/lib/onboard/machine/core-flow-phases.ts @@ -378,6 +378,9 @@ export function createSandboxOnboardFlowPhase< hermesToolGateways: sandboxStateResult.hermesToolGateways, selectedMessagingChannels: sandboxStateResult.selectedMessagingChannels, webSearchSupported: sandboxStateResult.webSearchSupported, + ...(sandboxStateResult.revalidateSandboxIdentity + ? { revalidateSandboxIdentity: sandboxStateResult.revalidateSandboxIdentity } + : {}), }), result: sandboxStateResult.stateResult, }; diff --git a/src/lib/onboard/machine/final-flow-phases.test.ts b/src/lib/onboard/machine/final-flow-phases.test.ts index f08d5aceedc..8cc0f683258 100644 --- a/src/lib/onboard/machine/final-flow-phases.test.ts +++ b/src/lib/onboard/machine/final-flow-phases.test.ts @@ -38,6 +38,25 @@ describe("final onboard flow phases", () => { expect(result.context.selectedMessagingChannels).toEqual(["slack", "discord"]); }); + it("retains reused sandbox identity authority through final flow (#11074)", async () => { + const revalidateSandboxIdentity = vi + .fn<(operation: string) => void>() + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => undefined) + .mockImplementationOnce(() => { + throw new Error("sandbox identity changed"); + }); + const order: string[] = []; + const [branchPhase] = createPhases("openclaw", order); + const session = createSession(); + session.steps.sandbox.status = "skipped"; + + await expect(branchPhase.run(context({ session, revalidateSandboxIdentity }))).rejects.toThrow( + "sandbox identity changed", + ); + expect(order).toEqual(["openclaw"]); + }); + it("rejects final phases when required context is missing", async () => { const [branchPhase, policiesPhase, finalizationPhase, postVerifyPhase] = createPhases("openclaw"); diff --git a/src/lib/onboard/machine/final-flow-phases.ts b/src/lib/onboard/machine/final-flow-phases.ts index 9fdf25b6bbd..ee028b9abc2 100644 --- a/src/lib/onboard/machine/final-flow-phases.ts +++ b/src/lib/onboard/machine/final-flow-phases.ts @@ -74,6 +74,7 @@ export function createFinalOnboardFlowPhases< session: context.session, hermesAuthMethod: context.hermesAuthMethod, hermesToolGateways: context.hermesToolGateways, + revalidateSandboxIdentity: context.revalidateSandboxIdentity, deps: options.agentSetupDeps, }); return { diff --git a/src/lib/onboard/machine/flow-context.ts b/src/lib/onboard/machine/flow-context.ts index 73df46ed8ae..69f46d2fff3 100644 --- a/src/lib/onboard/machine/flow-context.ts +++ b/src/lib/onboard/machine/flow-context.ts @@ -42,6 +42,8 @@ export interface OnboardFlowContext void; } export type ProviderModelSelectedOnboardFlowContext = @@ -98,6 +100,7 @@ export interface SandboxCreatedContextUpdate { hermesToolGateways: string[]; selectedMessagingChannels: string[]; webSearchSupported: boolean; + revalidateSandboxIdentity?: (operation: string) => void; } export function assertProviderModelSelectedContext( diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index 7403d9dd9aa..7c73370d23d 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -110,7 +110,8 @@ export async function handleAgentSetupState({ // A skipped sandbox step is the durable machine receipt for Ready-sandbox // reuse. Every other state keeps the strict occupied-port path. - const preserveRegisteredForward = session?.steps.sandbox.status === "skipped"; + const preserveRegisteredForward = + session?.steps.sandbox.status === "skipped" || revalidateSandboxIdentity !== undefined; const resumeOpenclaw = resume && sandboxName && deps.isOpenclawReady(sandboxName); if (resumeOpenclaw) { deps.skippedStepMessage("openclaw", sandboxName); diff --git a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts index 8b1bba05661..08f2e2508f2 100644 --- a/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts +++ b/src/lib/onboard/machine/handlers/sandbox-test-fixtures.ts @@ -281,8 +281,10 @@ export function createDeps( hydrateMessagingChannelConfig: (config: MessagingChannelConfig | null) => config, messagingChannelConfigsEqual: () => true, getSandboxReuseState: () => "missing", - getSandboxRecreateObservation: () => - ({ state: "missing", liveIdentityFingerprint: null }) as const, + getSandboxRecreateObservation: (name: string | null) => + overrides.getSandboxReuseState?.(name) === "ready" + ? ({ state: "ready", liveIdentityFingerprint: "a".repeat(64) } as const) + : ({ state: "missing", liveIdentityFingerprint: null } as const), getDcodeSelectionDrift: () => ({ changed: false, unknown: false }), hasSandboxGpuDrift: () => false, getSandboxHermesToolGateways: () => [], diff --git a/src/lib/onboard/machine/handlers/sandbox.test.ts b/src/lib/onboard/machine/handlers/sandbox.test.ts index 59fff4d16c8..7434652e184 100644 --- a/src/lib/onboard/machine/handlers/sandbox.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox.test.ts @@ -579,11 +579,13 @@ describe("handleSandboxState", () => { session.steps.sandbox.status = "complete"; const skippedSession = createSession({ sandboxName: "saved-after-skip" }); const recordStateSkipped = vi.fn(async () => skippedSession); + let liveIdentityFingerprint = "a".repeat(64); const readMessagingPlanFromEnv = vi.fn(() => { throw new Error("invalid environment plan"); }); const { deps, calls } = createDeps({ getSandboxReuseState: () => "ready", + getSandboxRecreateObservation: () => ({ state: "ready", liveIdentityFingerprint }), getSandboxRegistryEntry: () => ({ name: "saved", pendingRouteReservation: true, @@ -595,18 +597,17 @@ describe("handleSandboxState", () => { toolDisclosure: "progressive", fromDockerfile: null, hermesAuthMethod: null, + lifecycleLiveIdentityFingerprint: "a".repeat(64), }), getRegistrySandboxMessagingAuthority: () => ({ authoritative: true, plan: registryPlan }), readMessagingPlanFromEnv, recordStateSkipped, }); - const result = await handleSandboxState({ ...baseOptions(deps, session), resume: true, sandboxName: "saved", }); - expect(readMessagingPlanFromEnv).not.toHaveBeenCalled(); expect(calls.createSandbox).not.toHaveBeenCalled(); expect(calls.finalizeRouteReservation).toHaveBeenCalledExactlyOnceWith( @@ -621,6 +622,8 @@ describe("handleSandboxState", () => { expect(result.selectedMessagingChannels).toEqual(["telegram"]); expect(result.webSearchConfigChanged).toBe(false); expect(result.session).toBe(skippedSession); + liveIdentityFingerprint = "b".repeat(64); + expect(() => result.revalidateSandboxIdentity?.("dashboard")).toThrow(/changed identity/u); }); it("treats checkpoint machine-state progress past sandbox as step-complete even when the legacy step status is stale (#6228)", async () => { diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index a3ba41026bd..8c12fa83051 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -83,6 +83,7 @@ import type { SandboxCreateIntent as ResolvedSandboxCreateIntent } from "../../s import { advanceSandboxRecreateTransaction, clearCompletedSandboxRecreateTransaction, + createReusedSandboxIdentityRevalidation, fingerprintSandboxRecreateValue, ownSandboxRecreateTransaction, type ReplacedSandboxSourceEntry, @@ -365,6 +366,7 @@ export interface SandboxStateOptions< createIntent: CompleteSandboxCreateIntent, runVerifiedSandboxCreateEffects?: import("../../types").VerifiedSandboxCreateEffects, ): Promise; + takeReusedSandboxIdentityRevalidation?(): ((operation: string) => void) | undefined; finalizeSandboxRouteReservation(sandboxName: string, sessionId: string): boolean; updateSandboxRegistry(sandboxName: string, updates: Record): void; getSandboxAgentRegistryFields( @@ -399,6 +401,7 @@ export interface SandboxStateResult { webSearchSupported: boolean; session: Session | null; stateResult: OnboardStateResult; + revalidateSandboxIdentity?: (operation: string) => void; } interface SandboxStepState { @@ -410,6 +413,7 @@ interface SandboxStepState { readonly webSearchSupported: boolean; readonly webSearchSupportDropped: boolean; readonly webSearchSupportProbePath: string | null; + readonly revalidateSandboxIdentity?: (operation: string) => void; } function resolveRequestedWebSearchConfig( @@ -1191,6 +1195,16 @@ class SandboxStateFlow< return this.deps.withGatewayRouteMutationLock(this.options.gatewayName, async () => { this.assertCheckpointBindingsStillLive(state); this.assertGatewayRouteCompatible(state.sandboxName); + const sandboxName = state.sandboxName as string; + const openingObservation = this.deps.getSandboxRecreateObservation(sandboxName); + const revalidateSandboxIdentity = createReusedSandboxIdentityRevalidation({ + sandboxName, + openingObservation, + registeredIdentity: + this.deps.getSandboxRegistryEntry(sandboxName)?.lifecycleLiveIdentityFingerprint ?? null, + observe: () => this.deps.getSandboxRecreateObservation(sandboxName), + }); + revalidateSandboxIdentity(`reusing sandbox '${sandboxName}'`); if (state.webSearchConfig) { const provider = webSearchProviderForConfig( state.webSearchConfig as unknown as SharedWebSearchConfig, @@ -1231,6 +1245,7 @@ class SandboxStateFlow< ...state, session: recordedSession, selectedMessagingChannels: messaging.selectedChannels, + revalidateSandboxIdentity, }; }); } @@ -2200,6 +2215,7 @@ class SandboxStateFlow< throw error; } let recordedTransaction: CheckpointSandboxRecreateTransaction | null; + const revalidateSandboxIdentity = this.deps.takeReusedSandboxIdentityRevalidation?.(); try { recordedTransaction = this.reloadSandboxRecreateTransaction(transaction); this.retireSandboxRecreateSourceWorkload(recordedTransaction, sourceEntry, sandboxName); @@ -2251,7 +2267,12 @@ class SandboxStateFlow< sandboxName, createIntent, ); - return { ...state, sandboxName, session: recordedSession }; + return { + ...state, + sandboxName, + session: recordedSession, + ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), + }; }; const withGatewayLock = () => this.deps.withGatewayRouteMutationLock(this.options.gatewayName, createAndRecord); @@ -2489,6 +2510,9 @@ class SandboxStateFlow< selectedMessagingChannels: state.selectedMessagingChannels, webSearchSupported: state.webSearchSupported, session: state.session, + ...(state.revalidateSandboxIdentity + ? { revalidateSandboxIdentity: state.revalidateSandboxIdentity } + : {}), stateResult: this.options.apfInterceptorRequested === true ? completeOnboardMachine({}, metadata) diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 4fb8ba50361..6f5b1d7563b 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -60,6 +60,7 @@ import { cliName } from "../branding"; import type { CreatedSandboxLifecycle, CreatedSandboxLifecycleRegistration, + SandboxRecreateObservation, } from "../sandbox-recreate-transaction"; import type { PortableOnboardRuntimeContext } from "../session-bootstrap"; import type { @@ -90,6 +91,16 @@ function cancelRecoveryIdentity( }; } +function observeOpeningReuseIdentity(input: { + readonly liveExists: boolean; + readonly sandboxName: string; + readonly gatewayName: string; + readonly observe: (sandboxName: string, gatewayName: string) => SandboxRecreateObservation; +}): SandboxRecreateObservation | null { + if (!input.liveExists) return null; + return input.observe(input.sandboxName, input.gatewayName); +} + /** Finalize provider arguments from the exact policy that creation consumes. */ export function bindRebuildPolicyProvidersToCreateArgs( createArgs: readonly string[], @@ -1302,6 +1313,9 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche runVerifiedSandboxCreateEffects: import("../types").VerifiedSandboxCreateEffects | null = null, preparedBuildContext: PreparedSandboxBuildContext | null = null, allowRemovedImmutabilityStateRecord = false, + retainReusedSandboxIdentityRevalidation?: ( + revalidateSandboxIdentity: (operation: string) => void, + ) => void, ) { const portableRuntimeAuthority = portableRuntimeContext?.authority ?? null; const { @@ -1647,6 +1661,13 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche prepareWorkload: ensurePreparedSandboxWorkload, }); const apfInterceptorRequested = createIntent?.apfInterceptorRequested === true; + const openingReuseIdentity = observeOpeningReuseIdentity({ + liveExists, + sandboxName, + gatewayName: GATEWAY_NAME, + observe: getSandboxRecreateObservation, + }); + const registeredReuseIdentity = existingEntry?.lifecycleLiveIdentityFingerprint ?? null; let verifiedCreateBoundary: VerifiedSandboxCreateBoundary | null = null; let pendingCreateIdentity: PendingSandboxCreateIdentity | null = null; let admittedCreateReservation: QualifiedPendingSandboxCreateReservation | null = null; @@ -1700,6 +1721,14 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche }); const resumingVerifiedCreate = acceptedTargetPendingIdentity !== null; const restoreReusedSandboxDashboard = async (selectionVerified: boolean): Promise => { + const revalidateReusedSandboxIdentity = sandboxReuse.createReusedSandboxIdentityRevalidation({ + sandboxName, + openingObservation: openingReuseIdentity, + registeredIdentity: registeredReuseIdentity, + observe: () => getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), + }); + revalidateReusedSandboxIdentity(`restoring dashboard state for sandbox '${sandboxName}'`); + retainReusedSandboxIdentityRevalidation?.(revalidateReusedSandboxIdentity); ({ chatUiUrl } = await sandboxReuse.restoreReusedSandboxDashboardState({ sandboxName, chatUiUrl, @@ -1716,7 +1745,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche hermesDashboardForwarding, updateReusedSandboxMetadata, releaseDashboardPort: dashboardPortReservationScope.release, - revalidateSandboxIdentity: (operation) => revalidateSandboxIdentity(true, operation), + revalidateSandboxIdentity: revalidateReusedSandboxIdentity, })); }; if (recreateRuntime.acceptedTarget && !resumingVerifiedCreate) { diff --git a/src/lib/onboard/sandbox-recreate-transaction.ts b/src/lib/onboard/sandbox-recreate-transaction.ts index 9da98f3f335..ca4c4b72de1 100644 --- a/src/lib/onboard/sandbox-recreate-transaction.ts +++ b/src/lib/onboard/sandbox-recreate-transaction.ts @@ -46,6 +46,32 @@ export type ReplacedSandboxSourceEntry = Omit & { }; }; +export function createReusedSandboxIdentityRevalidation(input: { + readonly sandboxName: string; + readonly openingObservation: SandboxRecreateObservation | null; + readonly registeredIdentity: string | null; + readonly observe: () => SandboxRecreateObservation; +}): (operation: string) => void { + const expectedIdentity = input.openingObservation?.liveIdentityFingerprint; + if ( + input.openingObservation?.state !== "ready" || + !expectedIdentity || + (input.registeredIdentity !== null && input.registeredIdentity !== expectedIdentity) + ) { + throw new Error( + `Sandbox '${input.sandboxName}' has no stable identity for reuse. Retry onboarding against the current sandbox.`, + ); + } + return (operation: string): void => { + const current = input.observe(); + if (current.state !== "ready" || current.liveIdentityFingerprint !== expectedIdentity) { + throw new Error( + `Sandbox '${input.sandboxName}' changed identity before ${operation}. Retry onboarding against the current sandbox.`, + ); + } + }; +} + interface ReplacedSandboxWorkloadCleanupDeps { readonly runtimeProviders?: RuntimeProviderBundleRegistry; } diff --git a/src/lib/onboard/sandbox-reuse.test.ts b/src/lib/onboard/sandbox-reuse.test.ts index c59aab6bc39..e7d9e24b6b5 100644 --- a/src/lib/onboard/sandbox-reuse.test.ts +++ b/src/lib/onboard/sandbox-reuse.test.ts @@ -8,6 +8,7 @@ import { SANDBOX_RECREATE_PROBE_TIMEOUT_MS } from "./sandbox-recreate-probe"; import { fingerprintSandboxRecreateValue } from "./sandbox-recreate-transaction"; import { applyReusedSandboxDashboardState, + createReusedSandboxIdentityRevalidation, createSandboxReuseHelpers, restoreReusedSandboxDashboardState, type SandboxReuseDeps, @@ -33,6 +34,7 @@ describe("applyReusedSandboxDashboardState", () => { it("clears Hermes dashboard registry fields when the reused sandbox has it disabled", () => { const updateSandbox = vi.fn(); + const ensureDashboardForward = vi.fn(() => 18789); const sandboxGpuConfig: SandboxGpuConfig = { hostGpuDetected: false, hostGpuPlatform: null, @@ -53,7 +55,7 @@ describe("applyReusedSandboxDashboardState", () => { sandboxGpuConfig, gatewayName: "nemoclaw", gatewayPort: 8080, - ensureDashboardForward: vi.fn(() => 18789), + ensureDashboardForward, hermesDashboardForwarding: { resolveStateForPort: vi.fn(() => hermesDashboardState), ensureForState: vi.fn(), @@ -71,6 +73,23 @@ describe("applyReusedSandboxDashboardState", () => { gatewayPort: 8080, }); expect(result.hermesDashboardState).toBe(hermesDashboardState); + expect(ensureDashboardForward).toHaveBeenCalledWith("reuse-me", "http://127.0.0.1:18789", { + preserveRegisteredForward: true, + }); + }); + + it("retains the exact live identity selected for reuse (#11074)", () => { + let liveIdentityFingerprint = "a".repeat(64); + const revalidate = createReusedSandboxIdentityRevalidation({ + sandboxName: "reuse-me", + openingObservation: { state: "ready", liveIdentityFingerprint }, + registeredIdentity: liveIdentityFingerprint, + observe: () => ({ state: "ready", liveIdentityFingerprint }), + }); + + expect(() => revalidate("restoring its dashboard")).not.toThrow(); + liveIdentityFingerprint = "b".repeat(64); + expect(() => revalidate("inspecting its dashboard forward")).toThrow(/changed identity/u); }); it("skips dashboard forwarding while preserving reuse metadata for terminal agents", () => { @@ -151,7 +170,10 @@ describe("applyReusedSandboxDashboardState", () => { ( _sandboxName: string, _chatUiUrl: string, - options?: { revalidateSandboxIdentity?: (operation: string) => void }, + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + }, ) => { options?.revalidateSandboxIdentity?.("start the dashboard forward"); return 18790; @@ -194,6 +216,11 @@ describe("applyReusedSandboxDashboardState", () => { ).rejects.toThrow(/Sandbox identity changed before/u); expect(ensureDashboardForward).toHaveBeenCalledOnce(); + expect(ensureDashboardForward).toHaveBeenCalledWith( + "reuse-me", + "http://127.0.0.1:18789", + expect.objectContaining({ preserveRegisteredForward: true }), + ); expect(env.CHAT_UI_URL).toBeUndefined(); expect(ensureForState).not.toHaveBeenCalled(); expect(updateReusedSandboxMetadata).not.toHaveBeenCalled(); diff --git a/src/lib/onboard/sandbox-reuse.ts b/src/lib/onboard/sandbox-reuse.ts index 4cfebedd42a..d83f97852c2 100644 --- a/src/lib/onboard/sandbox-reuse.ts +++ b/src/lib/onboard/sandbox-reuse.ts @@ -18,6 +18,8 @@ import { type SandboxRecreateObservation, } from "./sandbox-recreate-transaction"; +export { createReusedSandboxIdentityRevalidation } from "./sandbox-recreate-transaction"; + interface SandboxCaptureResult { status: number | null; output: string; @@ -104,7 +106,10 @@ export interface ReusedSandboxDashboardStateInput { ensureDashboardForward( sandboxName: string, chatUiUrl: string, - options?: { revalidateSandboxIdentity?: (operation: string) => void }, + options?: { + preserveRegisteredForward?: boolean; + revalidateSandboxIdentity?: (operation: string) => void; + }, ): number; hermesDashboardForwarding: ReusedSandboxDashboardForwarding; updateSandbox?(sandboxName: string, updates: Partial): unknown; @@ -141,15 +146,16 @@ export function applyReusedSandboxDashboardState( `Sandbox '${input.sandboxName}' was created without remote dashboard exposure. Re-run onboarding with NEMOCLAW_DASHBOARD_BIND=0.0.0.0 and --recreate-sandbox before opening a remote bind.`, ); } - input.revalidateSandboxIdentity?.( - `restore dashboard state for sandbox '${input.sandboxName}'`, - ); + input.revalidateSandboxIdentity?.(`restore dashboard state for sandbox '${input.sandboxName}'`); const dashboardPort = manageDashboard ? input.revalidateSandboxIdentity ? input.ensureDashboardForward(input.sandboxName, input.chatUiUrl, { + preserveRegisteredForward: true, revalidateSandboxIdentity: input.revalidateSandboxIdentity, }) - : input.ensureDashboardForward(input.sandboxName, input.chatUiUrl) + : input.ensureDashboardForward(input.sandboxName, input.chatUiUrl, { + preserveRegisteredForward: true, + }) : 0; const chatUiUrl = manageDashboard ? `http://127.0.0.1:${dashboardPort}` : input.chatUiUrl; if (manageDashboard) { diff --git a/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index e90538c514d..303ce526af7 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -114,6 +114,33 @@ async function runOnboard( }); } +async function dashboardForwardProcessIdentity( + host: HostCliClient, + port: number, + artifactName: string, +): Promise { + const result = await host.command( + "bash", + [ + "-lc", + [ + "set -euo pipefail", + 'pids="$(lsof -nP -iTCP:"$1" -sTCP:LISTEN -Fp | sed -n \'s/^p//p\' | sort -u)"', + 'test -n "$pids"', + 'test "$(printf \'%s\\n\' "$pids" | wc -l | tr -d \' \')" = 1', + 'ps -ww -p "$pids" -o pid= -o uid= -o lstart= -o command=', + ].join("\n"), + "nemoclaw-dashboard-forward-identity", + String(port), + ], + { artifactName, env: commandEnv(), timeoutMs: 30_000 }, + ); + const identity = stripAnsi(result.stdout).trim(); + expect(result.exitCode, resultText(result)).toBe(0); + expect(identity, "dashboard ForwardTcp process identity").not.toBe(""); + return identity; +} + async function runProbeOnlyConnect( host: HostCliClient, sandboxName: string, @@ -439,6 +466,7 @@ test( ["-lc", "command -v openshell"], "prereq-openshell", ); + await prerequisiteOrSkip(host, skip, "bash", ["-lc", "command -v lsof"], "prereq-lsof"); await prerequisiteOrSkip( host, skip, @@ -501,6 +529,7 @@ test( "first onboard creates a sandbox and NemoClaw gateway", "OpenShell status reports the managed gateway through its Server endpoint line", "same-name re-onboard reuses the healthy gateway and sandbox without port conflicts", + "same-name re-onboard retains the exact dashboard ForwardTcp process and reachable UI", "explicit same-name recreation preserves the healthy gateway", "different-name onboard preserves the first sandbox and allocates distinct dashboard forwards", "stopping one sandbox releases only its dashboard forward and reports the container stopped", @@ -516,14 +545,6 @@ test( const first = await runOnboard(host, SANDBOX_A, fake.baseUrl, "phase-2-first-onboard"); const firstText = resultText(first); expect(first.exitCode, firstText).toBe(0); - expect(firstText).toContain(`Sandbox '${SANDBOX_A}' created`); - - const gatewayInfo = await sandbox.openshell(["gateway", "info", "-g", "nemoclaw"], { - artifactName: "phase-2-openshell-gateway-info", - env: commandEnv(), - timeoutMs: 30_000, - }); - expect(resultText(gatewayInfo)).toContain("nemoclaw"); const gatewayStatus = await sandbox.openshell(["status"], { artifactName: "phase-2-openshell-status", @@ -554,6 +575,17 @@ test( expect(sandboxAIdAfterFirst, resultText(sandboxAAfterFirst)).not.toBeNull(); expect(registryHas(SANDBOX_A), `${REGISTRY_FILE} missing ${SANDBOX_A}`).toBe(true); assertRegistryInferenceMetadata(SANDBOX_A, fake.baseUrl); + const dashboardPort = Number(registryEntry(SANDBOX_A)?.dashboardPort); + expect(Number.isSafeInteger(dashboardPort) && dashboardPort > 0).toBe(true); + const forwardIdentityBeforeSecond = await dashboardForwardProcessIdentity( + host, + dashboardPort, + "phase-2-dashboard-forward-identity", + ); + expect(forwardIdentityBeforeSecond).toContain(`forward service ${SANDBOX_A}`); + expect(forwardIdentityBeforeSecond).toContain( + `--local 127.0.0.1:${String(dashboardPort)}`, + ); progress.phase("re-onboard same sandbox on existing gateway"); // Phase 3: second onboard with the same name must reuse the healthy gateway. @@ -566,10 +598,6 @@ test( const gatewayAfterSecond = await gatewayRuntimeId(gateway); expect(gatewayBeforeSecond, "gateway runtime id before second onboard").not.toBe(""); expect(gatewayAfterSecond).toBe(gatewayBeforeSecond); - expect(secondText).toContain("Reusing healthy NemoClaw gateway."); - expect(secondText).toContain(`[reuse] Skipping sandbox (${SANDBOX_A})`); - expect(secondText).not.toContain("Port 8080 is not available"); - expect(secondText).not.toContain("Port 18789 is not available"); const sandboxAAfterSecond = await sandbox.openshell(["sandbox", "get", SANDBOX_A], { artifactName: "phase-3-openshell-sandbox-a-get", env: commandEnv(), @@ -577,6 +605,25 @@ test( }); expect(sandboxAAfterSecond.exitCode, resultText(sandboxAAfterSecond)).toBe(0); expect(parseOpenShellSandboxId(resultText(sandboxAAfterSecond))).toBe(sandboxAIdAfterFirst); + const forwardIdentityAfterSecond = await dashboardForwardProcessIdentity( + host, + dashboardPort, + "phase-3-dashboard-forward-identity", + ); + expect(forwardIdentityAfterSecond).toBe(forwardIdentityBeforeSecond); + const dashboardResponse = await host.command( + "curl", + [ + "--fail", + "--silent", + "--show-error", + "--max-time", + "15", + `http://127.0.0.1:${String(dashboardPort)}/`, + ], + { artifactName: "phase-3-dashboard-request", env: commandEnv(), timeoutMs: 30_000 }, + ); + expect(dashboardResponse.exitCode, resultText(dashboardResponse)).toBe(0); const sandboxARegistryAfterSecond = registryEntry(SANDBOX_A); expect(sandboxARegistryAfterSecond, `${REGISTRY_FILE} missing ${SANDBOX_A}`).toBeTruthy(); expect(hasOwn(sandboxARegistryAfterSecond!, "pendingRouteReservation")).toBe(false); @@ -587,7 +634,6 @@ test( timeoutMs: 60_000, }); expect(listAfterSecond.exitCode, resultText(listAfterSecond)).toBe(0); - expect(stripAnsi(listAfterSecond.stdout)).toContain(SANDBOX_A); progress.phase("recreate same sandbox on existing gateway"); const gatewayBeforeRecreate = await gatewayRuntimeId(gateway); @@ -889,6 +935,9 @@ test( secondOnboardReusedGateway: gatewayAfterSecond === gatewayBeforeSecond && secondText.includes("Reusing healthy NemoClaw gateway."), + secondOnboardRetainedDashboardForward: + forwardIdentityAfterSecond === forwardIdentityBeforeSecond && + dashboardResponse.exitCode === 0, thirdOnboardPreservedSibling: sandboxAAfterThird.exitCode === 0 && sandboxBAfterThird.exitCode === 0, distinctDashboardPorts: Boolean(portA && portB && portA !== portB), diff --git a/test/helpers/onboard-final-flow-phases.ts b/test/helpers/onboard-final-flow-phases.ts index eb96b9aaf1c..8c9334dac01 100644 --- a/test/helpers/onboard-final-flow-phases.ts +++ b/test/helpers/onboard-final-flow-phases.ts @@ -196,7 +196,8 @@ export function createPhases( order.push("agent-setup"); }), agentSetupContext: () => ({}), - ensureAgentDashboardForward: vi.fn(() => { + ensureAgentDashboardForward: vi.fn((_sandboxName, _agent, options) => { + options?.revalidateSandboxIdentity?.("inspect reused dashboard forward"); order.push("agent-forward"); return 45123; }), From f7150577418f249f4a495ea62d775e03c514c1e5 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 12:20:52 +0700 Subject: [PATCH 05/12] fix(onboard): defer dashboard reuse ownership checks Signed-off-by: San Dang --- src/lib/onboard/dashboard.ts | 50 +++++++++++++++-- .../onboard/sandbox-create/orchestration.ts | 54 +++++++++---------- src/lib/onboard/sandbox-reuse.test.ts | 26 +++++++++ test/e2e/mock-parity.json | 2 + test/helpers/onboard-script-mocks.cjs | 9 +++- ...ard-finalization-dashboard-forward.test.ts | 41 +++++++++++++- test/onboarding/onboard-messaging.test.ts | 2 +- test/onboarding/onboard.test.ts | 2 +- 8 files changed, 146 insertions(+), 40 deletions(-) diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 78b11b76cd3..5efb3710fc9 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -10,6 +10,7 @@ import { } from "../adapters/openshell/forward-service"; import { inspectForwardServiceListenerOwnership, + type ForwardServiceOwnershipFailure, type ForwardServiceOwnershipResult, } from "../adapters/openshell/forward-service-ownership"; import type { AgentDefinition } from "../agent/defs"; @@ -49,6 +50,43 @@ function looksLikeForwardPortConflict(diagnostic: string): boolean { return /eaddrinuse|address already in use|port .* in use|bind: .*in use/iu.test(diagnostic); } +function dashboardForwardOwnershipFailureMessage( + failure: ForwardServiceOwnershipFailure, + port: number, + sandboxName: string, + cliName: string, +): string { + const subject = + `Registered dashboard port ${String(port)} for sandbox '${sandboxName}' is occupied, ` + + `but its ForwardTcp ownership check failed (${failure}). `; + switch (failure) { + case "listener-changed": + return ( + subject + + `The listener changed during inspection. Re-run \`${cliName} onboard --resume\`; ` + + "the listener was not adopted." + ); + case "listener-not-unique": + return ( + subject + + `Identify and stop the extra listener on port ${String(port)}, then re-run ` + + `\`${cliName} onboard --resume\`; no listener was adopted.` + ); + case "process-identity-mismatch": + return ( + subject + + `Free port ${String(port)} and re-run \`${cliName} onboard --resume\`, or select another ` + + `port with \`${cliName} onboard --resume --control-ui-port \`; the listener was not adopted.` + ); + case "listener-enumeration-unavailable": + return ( + subject + + "Install lsof or restore read access to Linux /proc, then re-run " + + `\`${cliName} onboard --resume\`; the listener was not adopted.` + ); + } +} + type CommandResult = { status: number | null }; export interface OnboardDashboardDeps { @@ -423,12 +461,14 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa forwardTarget(sandboxName, forwardGateway, preferredPort, preferredTarget), ); if (ownership?.owned === true) return preferredPort; - if (ownership?.failure === "listener-enumeration-unavailable") { + if (ownership?.owned === false) { throw new Error( - `Registered dashboard port ${String(preferredPort)} is occupied, but its ForwardTcp ` + - "ownership could not be verified because listener enumeration is unavailable. " + - "Install lsof or restore read access to Linux /proc, then re-run " + - `\`${deps.cliName()} onboard --resume\`; the listener was not adopted.`, + dashboardForwardOwnershipFailureMessage( + ownership.failure, + preferredPort, + sandboxName, + deps.cliName(), + ), ); } } diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 6f5b1d7563b..02465871712 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -60,7 +60,6 @@ import { cliName } from "../branding"; import type { CreatedSandboxLifecycle, CreatedSandboxLifecycleRegistration, - SandboxRecreateObservation, } from "../sandbox-recreate-transaction"; import type { PortableOnboardRuntimeContext } from "../session-bootstrap"; import type { @@ -91,16 +90,6 @@ function cancelRecoveryIdentity( }; } -function observeOpeningReuseIdentity(input: { - readonly liveExists: boolean; - readonly sandboxName: string; - readonly gatewayName: string; - readonly observe: (sandboxName: string, gatewayName: string) => SandboxRecreateObservation; -}): SandboxRecreateObservation | null { - if (!input.liveExists) return null; - return input.observe(input.sandboxName, input.gatewayName); -} - /** Finalize provider arguments from the exact policy that creation consumes. */ export function bindRebuildPolicyProvidersToCreateArgs( createArgs: readonly string[], @@ -1661,13 +1650,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche prepareWorkload: ensurePreparedSandboxWorkload, }); const apfInterceptorRequested = createIntent?.apfInterceptorRequested === true; - const openingReuseIdentity = observeOpeningReuseIdentity({ - liveExists, - sandboxName, - gatewayName: GATEWAY_NAME, - observe: getSandboxRecreateObservation, - }); - const registeredReuseIdentity = existingEntry?.lifecycleLiveIdentityFingerprint ?? null; let verifiedCreateBoundary: VerifiedSandboxCreateBoundary | null = null; let pendingCreateIdentity: PendingSandboxCreateIdentity | null = null; let admittedCreateReservation: QualifiedPendingSandboxCreateReservation | null = null; @@ -1720,15 +1702,29 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche readEntry: () => registry.getSandbox(sandboxName), }); const resumingVerifiedCreate = acceptedTargetPendingIdentity !== null; - const restoreReusedSandboxDashboard = async (selectionVerified: boolean): Promise => { - const revalidateReusedSandboxIdentity = sandboxReuse.createReusedSandboxIdentityRevalidation({ + let reusedSandboxIdentityRevalidation: ((operation: string) => void) | undefined; + const selectReusedSandboxIdentity = (): ((operation: string) => void) | undefined => { + if (!manageDashboard) return undefined; + reusedSandboxIdentityRevalidation ??= sandboxReuse.createReusedSandboxIdentityRevalidation({ sandboxName, - openingObservation: openingReuseIdentity, - registeredIdentity: registeredReuseIdentity, + openingObservation: getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), + registeredIdentity: + registry.getSandbox(sandboxName)?.lifecycleLiveIdentityFingerprint ?? null, observe: () => getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), }); - revalidateReusedSandboxIdentity(`restoring dashboard state for sandbox '${sandboxName}'`); - retainReusedSandboxIdentityRevalidation?.(revalidateReusedSandboxIdentity); + return reusedSandboxIdentityRevalidation; + }; + const revalidateSelectedReuse = (operation: string): void => { + const revalidate = selectReusedSandboxIdentity(); + if (revalidate) revalidate(operation); + else revalidateSandboxIdentity(true, operation); + }; + const restoreReusedSandboxDashboard = async (selectionVerified: boolean): Promise => { + const revalidateReusedSandboxIdentity = selectReusedSandboxIdentity(); + revalidateReusedSandboxIdentity?.(`restoring dashboard state for sandbox '${sandboxName}'`); + if (revalidateReusedSandboxIdentity) { + retainReusedSandboxIdentityRevalidation?.(revalidateReusedSandboxIdentity); + } ({ chatUiUrl } = await sandboxReuse.restoreReusedSandboxDashboardState({ sandboxName, chatUiUrl, @@ -1925,12 +1921,11 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche if (actionableSelectionDrift) { note(" [non-interactive] Recreating sandbox due to provider/model drift."); } else { - revalidateSandboxIdentity(true, `reusing sandbox '${sandboxName}'`); + revalidateSelectedReuse(`reusing sandbox '${sandboxName}'`); // Upsert messaging providers even on reuse so credential changes take // effect without requiring a full sandbox recreation. upsertMessagingProviders(messagingTokenDefs, { - revalidateSandboxIdentity: (operation) => - revalidateSandboxIdentity(true, operation), + revalidateSandboxIdentity: revalidateSelectedReuse, }); if (selectionDrift.unknown) { note( @@ -1975,10 +1970,9 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche console.log(` Sandbox '${sandboxName}' already exists.`); console.log(" Choosing 'n' will delete the existing sandbox and create a new one."); if (await promptYesNoOrDefault(" Reuse existing sandbox?", null, true)) { - revalidateSandboxIdentity(true, `reusing sandbox '${sandboxName}'`); + revalidateSelectedReuse(`reusing sandbox '${sandboxName}'`); upsertMessagingProviders(messagingTokenDefs, { - revalidateSandboxIdentity: (operation) => - revalidateSandboxIdentity(true, operation), + revalidateSandboxIdentity: revalidateSelectedReuse, }); await restoreReusedSandboxDashboard(!selectionDrift.unknown); return sandboxName; diff --git a/src/lib/onboard/sandbox-reuse.test.ts b/src/lib/onboard/sandbox-reuse.test.ts index e7d9e24b6b5..a92cea2a183 100644 --- a/src/lib/onboard/sandbox-reuse.test.ts +++ b/src/lib/onboard/sandbox-reuse.test.ts @@ -92,6 +92,32 @@ describe("applyReusedSandboxDashboardState", () => { expect(() => revalidate("inspecting its dashboard forward")).toThrow(/changed identity/u); }); + it.each([ + ["a missing observation", null], + ["a non-Ready observation", { state: "not_ready", liveIdentityFingerprint: "a".repeat(64) }], + ["a missing fingerprint", { state: "ready", liveIdentityFingerprint: null }], + ] as const)("rejects reuse with %s (#11074)", (_case, openingObservation) => { + expect(() => + createReusedSandboxIdentityRevalidation({ + sandboxName: "reuse-me", + openingObservation, + registeredIdentity: "a".repeat(64), + observe: () => ({ state: "ready", liveIdentityFingerprint: "a".repeat(64) }), + }), + ).toThrow(/no stable identity for reuse/u); + }); + + it("rejects reuse when the Ready identity differs from the registry (#11074)", () => { + expect(() => + createReusedSandboxIdentityRevalidation({ + sandboxName: "reuse-me", + openingObservation: { state: "ready", liveIdentityFingerprint: "a".repeat(64) }, + registeredIdentity: "b".repeat(64), + observe: () => ({ state: "ready", liveIdentityFingerprint: "a".repeat(64) }), + }), + ).toThrow(/no stable identity for reuse/u); + }); + it("skips dashboard forwarding while preserving reuse metadata for terminal agents", () => { const updateSandbox = vi.fn(); const env: NodeJS.ProcessEnv = { CHAT_UI_URL: "https://chat.example.test:19000" }; diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index b68d8fd1d0b..74209ad97bd 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -473,6 +473,8 @@ "src/lib/onboard/machine/core-flow-phases.test.ts", "src/lib/onboard/machine/handlers/sandbox-route-publication.test.ts", "src/lib/onboard/sandbox-registration.test.ts", + "test/onboarding/onboard-finalization-dashboard-forward.test.ts", + "test/onboarding/onboard.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts" ] diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index 03a90b63ae3..63674cd70ef 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -713,7 +713,13 @@ function createCreatedSandboxFixture(options = {}) { assertState(); }; - const installRuntimeObservation = () => { + const installRuntimeObservation = (observationOptions = {}) => { + const restoreStructuredCapture = observationOptions.includeStructuredOpenShellCapture + ? mockStructuredOpenShellCaptureFromRunner({ + gatewayName: state.gatewayName, + sandboxName: state.sandboxName, + }) + : () => {}; const openshellRuntime = require( path.resolve(__dirname, "../../src/lib/adapters/openshell/runtime.ts"), ); @@ -732,6 +738,7 @@ function createCreatedSandboxFixture(options = {}) { }; openshellRuntime.captureResolvedOpenshell = fixtureCapture; return () => { + restoreStructuredCapture(); if (openshellRuntime.captureResolvedOpenshell === fixtureCapture) { openshellRuntime.captureResolvedOpenshell = previousCapture; } diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index 5716c047bbe..6ae25cd8e6f 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -124,11 +124,46 @@ describe("finalization dashboard ForwardTcp launch", () => { helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, }), - ).toThrow(/cannot be reallocated/u); + ).toThrow( + /port 18790 for sandbox 'reonboard-test'.*process-identity-mismatch.*onboard --resume.*--control-ui-port .*not adopted/su, + ); expect(launch).not.toHaveBeenCalled(); expect(process.env.CHAT_UI_URL).toBeUndefined(); }); + it.each([ + [ + "listener-changed", + /port 18790 for sandbox 'reonboard-test'.*listener-changed.*changed during inspection.*onboard --resume/su, + ], + [ + "listener-not-unique", + /port 18790 for sandbox 'reonboard-test'.*listener-not-unique.*stop the extra listener.*onboard --resume/su, + ], + ] as const)( + "reports %s ownership recovery during Ready sandbox reuse (#11074)", + (failure, message) => { + vi.stubEnv("CHAT_UI_URL", undefined); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + inspectOwnership: () => ({ + owned: false, + failure, + }), + isPortBound: (port) => port === 18_790, + }); + + expect(() => + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toThrow(message); + expect(launch).not.toHaveBeenCalled(); + }, + ); + it("reports unavailable ownership observation during Ready sandbox reuse (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); const { helpers, launch } = harness({ @@ -143,7 +178,9 @@ describe("finalization dashboard ForwardTcp launch", () => { helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, }), - ).toThrow(/Install lsof or restore read access to Linux \/proc/u); + ).toThrow( + /port 18790 for sandbox 'reonboard-test'.*listener-enumeration-unavailable.*Install lsof or restore read access to Linux \/proc/su, + ); expect(launch).not.toHaveBeenCalled(); expect(process.env.CHAT_UI_URL).toBeUndefined(); }); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index dcb83a1839f..26a649af524 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -1263,7 +1263,7 @@ const registry = require(${registryPath}); const fixtureMocks = require(${onboardScriptMocksPath}); const commands = []; -const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation(); +const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation({ includeStructuredOpenShellCapture: true }); const messagingProviderRunner = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ commands, createdSandbox: existingSandbox, diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 4c25917b398..11aacf4cd3b 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -689,7 +689,7 @@ const { EventEmitter } = require("node:events"); const commands = []; const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); const forwardService = fixtureMocks.installForwardServiceReachabilityFixture(); -existingSandbox.installRuntimeObservation(); +existingSandbox.installRuntimeObservation({ includeStructuredOpenShellCapture: true }); const sandboxCommand = (command) => Array.isArray(command) ? command : _n(command).split(/\s+/u); runner.run = (command, opts = {}) => { commands.push({ command: _n(command), env: opts.env || null }); From ac94a6021423a0eea8db287ff181ae51dd1dcdb3 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 13:03:16 +0700 Subject: [PATCH 06/12] fix(onboard): complete dashboard reuse handling --- .../onboard/agent-dashboard-forward.test.ts | 42 ++++++ src/lib/onboard/agent-dashboard-forward.ts | 4 + src/lib/onboard/dashboard.ts | 4 + .../fixtures/dashboard-listener-process.ts | 126 ++++++++++++++++++ test/e2e/live/double-onboard.test.ts | 120 ++++++++++------- ...ard-finalization-dashboard-forward.test.ts | 40 ++++++ 6 files changed, 287 insertions(+), 49 deletions(-) create mode 100644 test/e2e/fixtures/dashboard-listener-process.ts diff --git a/src/lib/onboard/agent-dashboard-forward.test.ts b/src/lib/onboard/agent-dashboard-forward.test.ts index b2e660b4f9d..703621417ce 100644 --- a/src/lib/onboard/agent-dashboard-forward.test.ts +++ b/src/lib/onboard/agent-dashboard-forward.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; +import { loadAgent } from "../agent/defs"; import { ensureAgentDashboardForward } from "./agent-dashboard-forward"; describe("ensureAgentDashboardForward", () => { @@ -223,4 +224,45 @@ describe("ensureAgentDashboardForward", () => { ); expect(process.env.CHAT_UI_URL).toBe("https://hermes.example.test:9120/ui"); }); + + it("preserves only the registered Hermes dashboard forward during Ready reuse (#11074)", async () => { + const revalidateSandboxIdentity = vi.fn(); + const ensureDashboardForward = vi.fn((_sandboxName, chatUiUrl = "") => { + return Number(new URL(chatUiUrl).port); + }); + + await ensureAgentDashboardForward({ + sandboxName: "hermes-reuse", + agent: loadAgent("hermes"), + ensureDashboardForward, + hermesApiPort: 8647, + chatUiUrl: "http://127.0.0.1:9120", + controlUiPort: 9120, + preserveRegisteredForward: true, + revalidateSandboxIdentity, + }); + + expect(ensureDashboardForward).toHaveBeenNthCalledWith( + 1, + "hermes-reuse", + "http://127.0.0.1:9120", + { + allowPortReallocation: false, + preserveRegisteredForward: true, + revalidateSandboxIdentity: expect.any(Function), + }, + ); + expect(ensureDashboardForward).toHaveBeenNthCalledWith( + 2, + "hermes-reuse", + "http://127.0.0.1:8647", + { + allowPortReallocation: false, + revalidateSandboxIdentity: expect.any(Function), + }, + ); + expect(revalidateSandboxIdentity).toHaveBeenCalledWith( + "report successful dashboard forwarding for sandbox 'hermes-reuse'", + ); + }); }); diff --git a/src/lib/onboard/agent-dashboard-forward.ts b/src/lib/onboard/agent-dashboard-forward.ts index e43b787318e..1ec6f6cba18 100644 --- a/src/lib/onboard/agent-dashboard-forward.ts +++ b/src/lib/onboard/agent-dashboard-forward.ts @@ -21,6 +21,7 @@ export type EnsureDashboardForward = ( chatUiUrl?: string, options?: { allowPortReallocation?: boolean; + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; }, ) => number; @@ -39,6 +40,7 @@ export async function ensureAgentDashboardForward(options: { /** Host port allocated to this sandbox's OpenAI-compatible API, when it has one. */ hermesApiPort?: number | null; beforeForwardPort?: (port: number) => Promise | void; + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; warn?: (message: string) => void; }): Promise { @@ -50,6 +52,7 @@ export async function ensureAgentDashboardForward(options: { controlUiPort, hermesApiPort, beforeForwardPort, + preserveRegisteredForward = false, revalidateSandboxIdentity, warn = (message: string) => console.warn(message), } = options; @@ -108,6 +111,7 @@ export async function ensureAgentDashboardForward(options: { await beforeForwardPort?.(agentDashboardPort); const actualAgentDashboardPort = ensureDashboardForward(sandboxName, requestedDashboardUrl, { allowPortReallocation: false, + ...(preserveRegisteredForward ? { preserveRegisteredForward: true } : {}), ...(revalidateIdentity ? { revalidateSandboxIdentity: revalidateIdentity } : {}), }); if (!usesFixedApiPort) { diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 5efb3710fc9..01b29cf0c5d 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -179,6 +179,7 @@ export interface OnboardDashboardHelpers { agent: { forwardPort?: number | null; forward_ports?: number[] | null }, options?: { beforeForwardPort?: (port: number) => Promise | void; + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; }, ): Promise; @@ -619,6 +620,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa agent: { forwardPort?: number | null; forward_ports?: number[] | null }, options: { beforeForwardPort?: (port: number) => Promise | void; + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; } = {}, ): Promise { @@ -631,6 +633,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa controlUiPort: chatUiUrl ? Number(getDashboardForwardPort(chatUiUrl)) : undefined, hermesApiPort: getSandbox?.(sandboxName)?.hermesApiPort, beforeForwardPort: options.beforeForwardPort, + preserveRegisteredForward: options.preserveRegisteredForward, revalidateSandboxIdentity: options.revalidateSandboxIdentity, }); } @@ -653,6 +656,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa } = options; return agent ? ensureAgentDashboardForward(sandboxName, agent, { + preserveRegisteredForward, revalidateSandboxIdentity, beforeForwardPort: portReservation ? (port) => portReservation.releaseBeforeForward(agent.name, port) diff --git a/test/e2e/fixtures/dashboard-listener-process.ts b/test/e2e/fixtures/dashboard-listener-process.ts new file mode 100644 index 00000000000..b486fc74369 --- /dev/null +++ b/test/e2e/fixtures/dashboard-listener-process.ts @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { createServer, type Server } from "node:net"; +import path from "node:path"; + +export interface DashboardListenerProcessIdentity { + pid: number; + uid: number; + startTimeTicks: string; + argv: string[]; +} + +function tcpListenerInodes(port: number): Set { + const inodes = new Set(); + for (const tablePath of ["/proc/net/tcp", "/proc/net/tcp6"]) { + let table: string; + try { + table = fs.readFileSync(tablePath, "utf8"); + } catch { + continue; + } + for (const line of table.split(/\r?\n/u).slice(1)) { + const fields = line.trim().split(/\s+/u); + const localAddress = fields[1]; + const state = fields[3]; + const inode = fields[9]; + const localPortHex = localAddress?.split(":").at(-1); + if (state === "0A" && inode && localPortHex && Number.parseInt(localPortHex, 16) === port) { + inodes.add(inode); + } + } + } + return inodes; +} + +function dashboardListenerProcessIds(port: number): number[] { + const socketLinks = new Set([...tcpListenerInodes(port)].map((inode) => `socket:[${inode}]`)); + if (socketLinks.size === 0) return []; + + const processIds: number[] = []; + for (const entry of fs.readdirSync("/proc", { withFileTypes: true })) { + if (!entry.isDirectory() || !/^\d+$/u.test(entry.name)) continue; + let descriptors: string[]; + try { + descriptors = fs.readdirSync(path.join("/proc", entry.name, "fd")); + } catch { + continue; + } + const ownsListener = descriptors.some((descriptor) => { + try { + return socketLinks.has(fs.readlinkSync(path.join("/proc", entry.name, "fd", descriptor))); + } catch { + return false; + } + }); + if (ownsListener) processIds.push(Number(entry.name)); + } + return processIds.sort((left, right) => left - right); +} + +export function dashboardForwardProcessIdentity(port: number): DashboardListenerProcessIdentity { + const processIds = dashboardListenerProcessIds(port); + if (processIds.length !== 1) { + throw new Error( + `Expected one listener process on dashboard port ${String(port)}, found ${String(processIds.length)}.`, + ); + } + const pid = processIds[0]!; + const processDirectory = path.join("/proc", String(pid)); + const statText = fs.readFileSync(path.join(processDirectory, "stat"), "utf8"); + const commandEnd = statText.lastIndexOf(")"); + const statFields = + commandEnd >= 0 + ? statText + .slice(commandEnd + 2) + .trim() + .split(/\s+/u) + : []; + const startTimeTicks = statFields[19]; + if (!startTimeTicks) { + throw new Error(`Could not read the start time for dashboard listener process ${String(pid)}.`); + } + return { + pid, + uid: fs.statSync(processDirectory).uid, + startTimeTicks, + argv: fs + .readFileSync(path.join(processDirectory, "cmdline")) + .toString("utf8") + .split("\0") + .filter(Boolean), + }; +} + +export async function waitForDashboardListenerToStop(port: number): Promise { + const deadline = Date.now() + 30_000; + while (Date.now() < deadline) { + if (dashboardListenerProcessIds(port).length === 0) return; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error(`Dashboard listener on port ${String(port)} did not stop within 30 seconds.`); +} + +export async function closeServer(server: Server): Promise { + if (!server.listening) return; + await new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} + +export async function startForeignDashboardListener(port: number): Promise { + const server = createServer((socket) => { + socket.end("HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\nforeign"); + }); + await new Promise((resolve, reject) => { + const onError = (error: Error): void => reject(error); + server.once("error", onError); + server.listen(port, "127.0.0.1", () => { + server.off("error", onError); + resolve(); + }); + }); + return server; +} diff --git a/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index 303ce526af7..874d35e3773 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -17,6 +17,12 @@ import { startFakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compati import type { LifecyclePhaseFixture } from "../fixtures/phases/lifecycle.ts"; import { CLI_DIST_ENTRYPOINT, CLI_ENTRYPOINT } from "../fixtures/paths.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; +import { + closeServer, + dashboardForwardProcessIdentity, + startForeignDashboardListener, + waitForDashboardListenerToStop, +} from "../fixtures/dashboard-listener-process.ts"; // // This intentionally stays as one free-standing live test with local @@ -114,33 +120,6 @@ async function runOnboard( }); } -async function dashboardForwardProcessIdentity( - host: HostCliClient, - port: number, - artifactName: string, -): Promise { - const result = await host.command( - "bash", - [ - "-lc", - [ - "set -euo pipefail", - 'pids="$(lsof -nP -iTCP:"$1" -sTCP:LISTEN -Fp | sed -n \'s/^p//p\' | sort -u)"', - 'test -n "$pids"', - 'test "$(printf \'%s\\n\' "$pids" | wc -l | tr -d \' \')" = 1', - 'ps -ww -p "$pids" -o pid= -o uid= -o lstart= -o command=', - ].join("\n"), - "nemoclaw-dashboard-forward-identity", - String(port), - ], - { artifactName, env: commandEnv(), timeoutMs: 30_000 }, - ); - const identity = stripAnsi(result.stdout).trim(); - expect(result.exitCode, resultText(result)).toBe(0); - expect(identity, "dashboard ForwardTcp process identity").not.toBe(""); - return identity; -} - async function runProbeOnlyConnect( host: HostCliClient, sandboxName: string, @@ -444,6 +423,7 @@ test( "onboard sibling sandbox with isolated dashboard", "stop sibling sandbox without disturbing the first forward", "replace sandbox after stale registry refusal", + "reject foreign dashboard listener during reuse", "validate gateway-stop lifecycle guidance", "remove double-onboard resources", ], @@ -466,7 +446,6 @@ test( ["-lc", "command -v openshell"], "prereq-openshell", ); - await prerequisiteOrSkip(host, skip, "bash", ["-lc", "command -v lsof"], "prereq-lsof"); await prerequisiteOrSkip( host, skip, @@ -534,6 +513,7 @@ test( "different-name onboard preserves the first sandbox and allocates distinct dashboard forwards", "stopping one sandbox releases only its dashboard forward and reports the container stopped", "stale OpenShell deletion preserves registry metadata through status/connect and rebuild directs a clean replacement", + "same-name re-onboard rejects a real foreign listener without replacing the sandbox", "status after gateway stop gives explicit lifecycle guidance without deleting registry state", ], }); @@ -577,13 +557,10 @@ test( assertRegistryInferenceMetadata(SANDBOX_A, fake.baseUrl); const dashboardPort = Number(registryEntry(SANDBOX_A)?.dashboardPort); expect(Number.isSafeInteger(dashboardPort) && dashboardPort > 0).toBe(true); - const forwardIdentityBeforeSecond = await dashboardForwardProcessIdentity( - host, - dashboardPort, - "phase-2-dashboard-forward-identity", - ); - expect(forwardIdentityBeforeSecond).toContain(`forward service ${SANDBOX_A}`); - expect(forwardIdentityBeforeSecond).toContain( + const forwardIdentityBeforeSecond = dashboardForwardProcessIdentity(dashboardPort); + await artifacts.writeJson("phase-2-dashboard-forward-identity.json", forwardIdentityBeforeSecond); + expect(forwardIdentityBeforeSecond.argv.join(" ")).toContain(`forward service ${SANDBOX_A}`); + expect(forwardIdentityBeforeSecond.argv.join(" ")).toContain( `--local 127.0.0.1:${String(dashboardPort)}`, ); @@ -605,12 +582,9 @@ test( }); expect(sandboxAAfterSecond.exitCode, resultText(sandboxAAfterSecond)).toBe(0); expect(parseOpenShellSandboxId(resultText(sandboxAAfterSecond))).toBe(sandboxAIdAfterFirst); - const forwardIdentityAfterSecond = await dashboardForwardProcessIdentity( - host, - dashboardPort, - "phase-3-dashboard-forward-identity", - ); - expect(forwardIdentityAfterSecond).toBe(forwardIdentityBeforeSecond); + const forwardIdentityAfterSecond = dashboardForwardProcessIdentity(dashboardPort); + await artifacts.writeJson("phase-3-dashboard-forward-identity.json", forwardIdentityAfterSecond); + expect(forwardIdentityAfterSecond).toEqual(forwardIdentityBeforeSecond); const dashboardResponse = await host.command( "curl", [ @@ -647,8 +621,6 @@ test( const recreatedText = resultText(recreated); expect(recreated.exitCode, recreatedText).toBe(0); expect(await gatewayRuntimeId(gateway)).toBe(gatewayBeforeRecreate); - expect(recreatedText).not.toContain("Port 8080 is not available"); - expect(recreatedText).not.toContain("Port 18789 is not available"); progress.phase("onboard sibling sandbox with isolated dashboard"); // Phase 4: a different-name onboard must not destroy A. @@ -674,8 +646,6 @@ test( const gatewayAfterThird = await gatewayRuntimeId(gateway); expect(gatewayBeforeThird, "gateway runtime id before third onboard").not.toBe(""); expect(gatewayAfterThird).toBe(gatewayBeforeThird); - expect(thirdText).not.toContain("Port 8080 is not available"); - expect(thirdText).not.toContain("Port 18789 is not available"); const selectedNemoclaw = await host.command( "bash", @@ -730,7 +700,6 @@ test( if (attempt < PROBE_ATTEMPTS) await sleep(PROBE_DELAY_MS); } expect(probe?.exitCode, probe ? resultText(probe) : "probe did not run").toBe(0); - expect(probe?.timedOut, probe ? resultText(probe) : "probe did not run").toBe(false); const restoredForwardB = await waitForForwardOwner( sandbox, @@ -818,7 +787,6 @@ test( const staleStatusText = resultText(staleStatus); expect(staleStatus.exitCode, staleStatusText).toBe(1); expect(staleStatusText).toContain("No local registry entry was removed"); - expect(staleStatusText).not.toContain("Removed stale local registry entry"); expect(registryHas(SANDBOX_A), "status removed stale registry entry").toBe(true); const staleConnect = await command(host, [SANDBOX_A, "connect"], { @@ -844,7 +812,6 @@ test( expect(rebuildText).toContain("Rebuild cannot recover its missing OpenShell policy"); expect(rebuildText).toContain(`nemoclaw ${SANDBOX_A} destroy --yes`); expect(rebuildText).toContain("nemoclaw onboard"); - expect(rebuildText).not.toContain("Creating new sandbox with current image"); expect(rebuild.exitCode, rebuildText).not.toBe(0); const removeStale = await command(host, [SANDBOX_A, "destroy", "--yes"], { @@ -871,6 +838,57 @@ test( expect(sandboxAAfterRebuild.exitCode, resultText(sandboxAAfterRebuild)).toBe(0); expect(registryHas(SANDBOX_A), "rebuild lost sandbox A registry entry").toBe(true); + progress.phase("reject foreign dashboard listener during reuse"); + const sandboxAIdBeforeForeignListener = parseOpenShellSandboxId(resultText(sandboxAAfterRebuild)); + expect(sandboxAIdBeforeForeignListener, resultText(sandboxAAfterRebuild)).not.toBeNull(); + const foreignListenerPort = Number(registryEntry(SANDBOX_A)?.dashboardPort); + expect(Number.isSafeInteger(foreignListenerPort) && foreignListenerPort > 0).toBe(true); + const ownedForwardBeforeForeignListener = dashboardForwardProcessIdentity(foreignListenerPort); + await artifacts.writeJson( + "phase-5-owned-dashboard-forward-before-foreign-listener.json", + ownedForwardBeforeForeignListener, + ); + expect(ownedForwardBeforeForeignListener.argv.join(" ")).toContain( + `forward service ${SANDBOX_A}`, + ); + process.kill(ownedForwardBeforeForeignListener.pid, "SIGTERM"); + await waitForDashboardListenerToStop(foreignListenerPort); + + const foreignListener = await startForeignDashboardListener(foreignListenerPort); + cleanup.trackDisposable("close foreign dashboard listener", () => closeServer(foreignListener)); + const foreignIdentityBeforeAttempt = dashboardForwardProcessIdentity(foreignListenerPort); + await artifacts.writeJson( + "phase-5-foreign-dashboard-listener-before-reuse.json", + foreignIdentityBeforeAttempt, + ); + expect(foreignIdentityBeforeAttempt.pid).toBe(process.pid); + + const rejectedForeignReuse = await runOnboard( + host, + SANDBOX_A, + fake.baseUrl, + "phase-5-reject-foreign-dashboard-listener", + ); + const rejectedForeignReuseText = resultText(rejectedForeignReuse); + expect(rejectedForeignReuse.exitCode, rejectedForeignReuseText).not.toBe(0); + expect(rejectedForeignReuseText).toContain("process-identity-mismatch"); + expect(rejectedForeignReuseText).toContain("listener was not adopted"); + const foreignIdentityAfterAttempt = dashboardForwardProcessIdentity(foreignListenerPort); + await artifacts.writeJson( + "phase-5-foreign-dashboard-listener-after-reuse.json", + foreignIdentityAfterAttempt, + ); + expect(foreignIdentityAfterAttempt).toEqual(foreignIdentityBeforeAttempt); + const sandboxAAfterForeignReuse = await sandbox.openshell(["sandbox", "get", SANDBOX_A], { + artifactName: "phase-5-openshell-sandbox-a-after-foreign-reuse", + env: commandEnv(), + timeoutMs: 30_000, + }); + expect(parseOpenShellSandboxId(resultText(sandboxAAfterForeignReuse))).toBe( + sandboxAIdBeforeForeignListener, + ); + await closeServer(foreignListener); + await command(host, [SANDBOX_A, "destroy", "--yes"], { artifactName: "phase-5-destroy-recovered-sandbox-a", env: commandEnv(), @@ -936,8 +954,12 @@ test( gatewayAfterSecond === gatewayBeforeSecond && secondText.includes("Reusing healthy NemoClaw gateway."), secondOnboardRetainedDashboardForward: - forwardIdentityAfterSecond === forwardIdentityBeforeSecond && + JSON.stringify(forwardIdentityAfterSecond) === JSON.stringify(forwardIdentityBeforeSecond) && dashboardResponse.exitCode === 0, + foreignDashboardListenerRejected: + rejectedForeignReuse.exitCode !== 0 && + rejectedForeignReuseText.includes("process-identity-mismatch") && + foreignIdentityAfterAttempt.pid === foreignIdentityBeforeAttempt.pid, thirdOnboardPreservedSibling: sandboxAAfterThird.exitCode === 0 && sandboxBAfterThird.exitCode === 0, distinctDashboardPorts: Boolean(portA && portB && portA !== portB), diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index 6ae25cd8e6f..d153fd0a013 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -5,11 +5,14 @@ import { describe, expect, it, vi } from "vitest"; import type { ForwardServiceTarget } from "../../src/lib/adapters/openshell/forward-service"; import type { ForwardServiceOwnershipResult } from "../../src/lib/adapters/openshell/forward-service-ownership"; +import { loadAgent } from "../../src/lib/agent/defs"; import { createOnboardDashboardHelpers } from "../../src/lib/onboard/dashboard"; +import type { OnboardDashboardDeps } from "../../src/lib/onboard/dashboard"; import type { ListSandboxesFn } from "../../src/lib/onboard/dashboard-port"; function harness(options: { listSandboxes: ListSandboxesFn; + getSandbox?: OnboardDashboardDeps["getSandbox"]; inspectOwnership?: (target: ForwardServiceTarget) => ForwardServiceOwnershipResult; isPortBound?: (port: number) => boolean; }) { @@ -27,6 +30,7 @@ function harness(options: { sleep: vi.fn(), printAgentDashboardUi: vi.fn(), listSandboxes: options.listSandboxes, + ...(options.getSandbox ? { getSandbox: options.getSandbox } : {}), isPortBoundOnHost: options.isPortBound ?? (() => false), forwardService: { executable: () => "/usr/local/bin/openshell", @@ -110,6 +114,42 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(process.env.CHAT_UI_URL).toBe("http://127.0.0.1:18790"); }); + it("preserves the registered Hermes dashboard through agent finalization (#11074)", async () => { + vi.stubEnv("CHAT_UI_URL", "http://127.0.0.1:18789"); + const revalidateSandboxIdentity = vi.fn(); + const inspectOwnership = vi.fn(() => ({ owned: true }) as const); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "hermes-reuse", dashboardPort: 18_789 }], + }), + getSandbox: () => ({ hermesApiPort: 8647 }) as never, + inspectOwnership, + isPortBound: (port) => port === 18_789, + }); + + expect( + await helpers.ensureFinalizationAgentDashboardForward("hermes-reuse", loadAgent("hermes"), { + preserveRegisteredForward: true, + revalidateSandboxIdentity, + }), + ).toBe(18_789); + expect(inspectOwnership).toHaveBeenCalledOnce(); + expect(inspectOwnership).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "hermes-reuse", + localPort: 18_789, + targetPort: 18_789, + }), + ); + expect(launch).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "hermes-reuse", + localPort: 8647, + targetPort: 8647, + }), + ); + }); + it("rejects an unowned listener during Ready sandbox reuse (#11074)", () => { vi.stubEnv("CHAT_UI_URL", undefined); const { helpers, launch } = harness({ From 75e567093896c1dec315562a091f9d6a3335c779 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 13:17:20 +0700 Subject: [PATCH 07/12] fix(onboard): carry agent reuse authority --- .../machine/handlers/agent-setup.test.ts | 21 ++++++++++++++- .../onboard/machine/handlers/agent-setup.ts | 26 ++++++++++--------- 2 files changed, 34 insertions(+), 13 deletions(-) diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index 347066ae181..208985997e9 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -75,7 +75,6 @@ describe("handleAgentSetupState", () => { const { deps, calls } = createDeps(); const agent = { name: "hermes", displayName: "Hermes" }; const session = createSession(); - session.steps.sandbox.status = "skipped"; const result = await handleAgentSetupState({ ...baseOptions(deps, agent), @@ -105,6 +104,26 @@ describe("handleAgentSetupState", () => { }); }); + it("passes Ready-sandbox reuse authority to a non-OpenClaw agent (#11074)", async () => { + const { deps, calls } = createDeps(); + const agent = { name: "hermes", displayName: "Hermes" }; + const session = createSession(); + session.steps.sandbox.status = "skipped"; + const revalidateSandboxIdentity = vi.fn(); + + await handleAgentSetupState({ + ...baseOptions(deps, agent), + session, + resume: true, + revalidateSandboxIdentity, + }); + + expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", agent, { + preserveRegisteredForward: true, + revalidateSandboxIdentity, + }); + }); + it("persists the bumped dashboard port returned by the forward (#8214)", async () => { const { deps, calls } = createDeps({}); calls.ensureDashboard.mockReturnValue(18791); diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index 7c73370d23d..28869ed20c1 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -85,6 +85,17 @@ export async function handleAgentSetupState({ revalidateSandboxIdentity, deps, }: AgentSetupStateOptions): Promise { + // A skipped sandbox step is the durable machine receipt for Ready-sandbox + // reuse. Every other state keeps the strict occupied-port path. + const preserveRegisteredForward = + session?.steps.sandbox.status === "skipped" || revalidateSandboxIdentity !== undefined; + const dashboardOptions = + preserveRegisteredForward || revalidateSandboxIdentity + ? { + ...(preserveRegisteredForward ? { preserveRegisteredForward: true } : {}), + ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), + } + : undefined; if (agent) { await deps.handleAgentSetup( sandboxName, @@ -100,7 +111,9 @@ export async function handleAgentSetupState({ // taken by another sandbox. Persist it to the registry so `dashboard-url` // reports the live port instead of the default. Discarding the return here // regressed multi-sandbox onboarding in the machine handler path (#8214). - const dashboardPort = await deps.ensureAgentDashboardForward(sandboxName, agent); + const dashboardPort = await (dashboardOptions + ? deps.ensureAgentDashboardForward(sandboxName, agent, dashboardOptions) + : deps.ensureAgentDashboardForward(sandboxName, agent)); if (dashboardPort > 0) { deps.persistDashboardPort(sandboxName, dashboardPort); } @@ -108,10 +121,6 @@ export async function handleAgentSetupState({ return { session, stateResult: advanceTo("policies", { metadata: { state: "agent_setup" } }) }; } - // A skipped sandbox step is the durable machine receipt for Ready-sandbox - // reuse. Every other state keeps the strict occupied-port path. - const preserveRegisteredForward = - session?.steps.sandbox.status === "skipped" || revalidateSandboxIdentity !== undefined; const resumeOpenclaw = resume && sandboxName && deps.isOpenclawReady(sandboxName); if (resumeOpenclaw) { deps.skippedStepMessage("openclaw", sandboxName); @@ -145,13 +154,6 @@ export async function handleAgentSetupState({ deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } - const dashboardOptions = - preserveRegisteredForward || revalidateSandboxIdentity - ? { - ...(preserveRegisteredForward ? { preserveRegisteredForward: true } : {}), - ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), - } - : undefined; const dashboardPort = await (dashboardOptions ? deps.ensureAgentDashboardForward(sandboxName, null, dashboardOptions) : deps.ensureAgentDashboardForward(sandboxName, null)); From 7f4622c68d8edc934c07eb0af72ecf61b6f9cd29 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 13:29:59 +0700 Subject: [PATCH 08/12] fix(onboard): require live reuse identity --- .../machine/handlers/agent-setup.test.ts | 6 ++---- src/lib/onboard/machine/handlers/agent-setup.ts | 17 ++++++----------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/lib/onboard/machine/handlers/agent-setup.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index 208985997e9..63bb28fab53 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -190,16 +190,14 @@ describe("handleAgentSetupState", () => { }); }); - it("preserves the registered dashboard forward after Ready sandbox reuse (#11074)", async () => { + it("does not preserve from a skipped sandbox receipt without a live identity lease (#11074)", async () => { const { deps, calls } = createDeps(); const session = createSession(); session.steps.sandbox.status = "skipped"; await handleAgentSetupState({ ...baseOptions(deps), session }); - expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", null, { - preserveRegisteredForward: true, - }); + expect(calls.ensureDashboard).toHaveBeenCalledWith("my-assistant", null); }); it("revalidates sandbox identity before inspecting a reused forward (#11074)", async () => { diff --git a/src/lib/onboard/machine/handlers/agent-setup.ts b/src/lib/onboard/machine/handlers/agent-setup.ts index 28869ed20c1..9a938ac8996 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -85,17 +85,12 @@ export async function handleAgentSetupState({ revalidateSandboxIdentity, deps, }: AgentSetupStateOptions): Promise { - // A skipped sandbox step is the durable machine receipt for Ready-sandbox - // reuse. Every other state keeps the strict occupied-port path. - const preserveRegisteredForward = - session?.steps.sandbox.status === "skipped" || revalidateSandboxIdentity !== undefined; - const dashboardOptions = - preserveRegisteredForward || revalidateSandboxIdentity - ? { - ...(preserveRegisteredForward ? { preserveRegisteredForward: true } : {}), - ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), - } - : undefined; + // Only the process-local Ready-sandbox identity lease authorizes retaining a + // bound forward. A persisted skipped-step receipt can outlive the sandbox it + // originally described and therefore cannot establish reuse by itself. + const dashboardOptions = revalidateSandboxIdentity + ? { preserveRegisteredForward: true, revalidateSandboxIdentity } + : undefined; if (agent) { await deps.handleAgentSetup( sandboxName, From 9e062afc3e955c88236e0e37b24790d26d4cc159 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 16:17:16 +0700 Subject: [PATCH 09/12] fix(onboard): correct dashboard reuse recovery --- src/lib/onboard/dashboard.ts | 4 ++-- .../onboarding/onboard-finalization-dashboard-forward.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 01b29cf0c5d..c5ce155f127 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -75,8 +75,8 @@ function dashboardForwardOwnershipFailureMessage( case "process-identity-mismatch": return ( subject + - `Free port ${String(port)} and re-run \`${cliName} onboard --resume\`, or select another ` + - `port with \`${cliName} onboard --resume --control-ui-port \`; the listener was not adopted.` + `Free port ${String(port)} and re-run \`${cliName} onboard --resume\`; ` + + "the listener was not adopted." ); case "listener-enumeration-unavailable": return ( diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index d153fd0a013..e1218c397a9 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -165,7 +165,7 @@ describe("finalization dashboard ForwardTcp launch", () => { preserveRegisteredForward: true, }), ).toThrow( - /port 18790 for sandbox 'reonboard-test'.*process-identity-mismatch.*onboard --resume.*--control-ui-port .*not adopted/su, + /^Registered dashboard port 18790 for sandbox 'reonboard-test' is occupied, but its ForwardTcp ownership check failed \(process-identity-mismatch\)\. Free port 18790 and re-run `nemoclaw onboard --resume`; the listener was not adopted\.$/u, ); expect(launch).not.toHaveBeenCalled(); expect(process.env.CHAT_UI_URL).toBeUndefined(); From f18a1159dd350fe25e812bdee005d3d84602b90e Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 16:38:59 +0700 Subject: [PATCH 10/12] test(e2e): complete dashboard reuse evidence --- test/e2e/live/onboard-resume.test.ts | 25 +++++++++++++++++++++++-- test/e2e/mock-parity.json | 1 + test/e2e/support/workflow-plan.test.ts | 8 ++++++++ tools/e2e/target-catalogue.mts | 6 +++++- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/test/e2e/live/onboard-resume.test.ts b/test/e2e/live/onboard-resume.test.ts index fe94c8b644e..f036b491ac2 100644 --- a/test/e2e/live/onboard-resume.test.ts +++ b/test/e2e/live/onboard-resume.test.ts @@ -23,6 +23,7 @@ import { createCorporateCaFixture, registeredCorporateCaWorkloadKind, } from "../fixtures/corporate-ca.ts"; +import { dashboardForwardProcessIdentity } from "../fixtures/dashboard-listener-process.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { REGISTRY_FILE, @@ -37,6 +38,7 @@ import { expectSandboxProviderAttachment, upsertGenericGatewayProvider, } from "../fixtures/gateway-providers.ts"; +import { readRegistrySandboxEntry } from "../fixtures/phases/state-validation.ts"; import { CLI_ENTRYPOINT } from "../fixtures/paths.ts"; // Disruption-recovery contract — regression for #446. @@ -192,6 +194,7 @@ test( "resume proves recreated sandbox provider attachments are selectively reconciled", "host trust-store anchor corporate CA source is baked and merged after resume", "an unreachable committed route pauses at final verification and completes after repair", + "route-repair resume retains the exact dashboard forward and reachable UI", "implicit resume is detected and --fresh suppresses that auto-resume", ], }); @@ -619,7 +622,14 @@ test( requireAuth: true, requireAuthModels: true, }); - expect(fake.baseUrl).toBe(`http://${fakePublicHost}:${String(fakePort)}/v1`); + const registeredDashboardPort = Number( + readRegistrySandboxEntry(SANDBOX_NAME).dashboardPort, + ); + const dashboardForwardBeforeRepair = dashboardForwardProcessIdentity(registeredDashboardPort); + await artifacts.writeJson( + "phase-3-5-dashboard-forward-before-route-repair.json", + dashboardForwardBeforeRepair, + ); const repairedResumeRun = await host.command( "node", @@ -633,9 +643,20 @@ test( ); const repairedResumeText = `${repairedResumeRun.stdout}\n${repairedResumeRun.stderr}`; expect(repairedResumeRun.exitCode, repairedResumeText).toBe(0); - expect(repairedResumeText).toContain("is ready"); expect(repairedResumeText).not.toContain(`Deleting and recreating sandbox '${SANDBOX_NAME}'`); expect(repairedResumeText).not.toContain(`Sandbox '${SANDBOX_NAME}' created`); + const dashboardForwardAfterRepair = dashboardForwardProcessIdentity(registeredDashboardPort); + await artifacts.writeJson( + "phase-3-5-dashboard-forward-after-route-repair.json", + dashboardForwardAfterRepair, + ); + expect(dashboardForwardAfterRepair).toEqual(dashboardForwardBeforeRepair); + const dashboardResponse = await fetch( + `http://127.0.0.1:${String(registeredDashboardPort)}/`, + { signal: AbortSignal.timeout(15_000) }, + ); + expect(dashboardResponse.ok).toBe(true); + await dashboardResponse.body?.cancel(); const repaired = readSession(SESSION_FILE); expect(repaired.status).toBe("complete"); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 74209ad97bd..ba0fdd3d663 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -321,6 +321,7 @@ "src/lib/onboard/extra-provider-reconciliation-probes.test.ts", "src/lib/onboard/extra-provider-reconciliation.test.ts", "src/lib/onboard/initial-policy-real-policy.test.ts", + "src/lib/onboard/machine/handlers/agent-setup.test.ts", "src/lib/onboard/machine/handlers/sandbox-recreate-resume.test.ts", "src/lib/onboard/machine/handlers/sandbox-resume.test.ts", "src/lib/onboard/managed-startup-image-runtime-handoff.test.ts", diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index d25b31a80d5..569c21379a3 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -662,6 +662,14 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard", "jetson-nvmap-gpu"]); }); + it("selects every dashboard-listener helper consumer", () => { + const targets = catalogueTargetsForChangedFiles([ + "test/e2e/fixtures/dashboard-listener-process.ts", + ]); + + expect(targets.map((target) => target.id)).toEqual(["double-onboard", "onboard-resume"]); + }); + it.each([ "nemoclaw-blueprint/router/pool-config.yaml", "test/e2e/live/model-router-provider-routed-inference-helpers.ts", diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index e094a3980a6..cd849e0c434 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -766,6 +766,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "authenticated", restoreCli: true, exposeCliBin: true, + owningPaths: ["test/e2e/fixtures/dashboard-listener-process.ts"], environment: nonInteractive, }), managedRuntimeTarget("gpu-double-onboard", { @@ -1094,7 +1095,10 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "credential-free", restoreCli: true, exposeCliBin: true, - owningPaths: ["tools/e2e/onboard-timeout-contract.mts"], + owningPaths: [ + "test/e2e/fixtures/dashboard-listener-process.ts", + "tools/e2e/onboard-timeout-contract.mts", + ], environment: { ...nonInteractive, NEMOCLAW_SANDBOX_NAME: "e2e-resume" }, }), managedRuntimeTarget("openclaw-discord-pairing", { From 44e93a37a36365287fbce6ffbfaddd928f3c37b8 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 19:19:21 +0700 Subject: [PATCH 11/12] test(e2e): narrow dashboard reuse evidence selection --- .../{fixtures => lib}/dashboard-listener-process.ts | 0 test/e2e/live/double-onboard.test.ts | 8 ++++---- test/e2e/live/onboard-resume.test.ts | 2 +- test/e2e/support/workflow-plan.test.ts | 11 ++++++++--- .../onboard-finalization-dashboard-forward.test.ts | 2 +- tools/e2e/target-catalogue.mts | 4 ++-- 6 files changed, 16 insertions(+), 11 deletions(-) rename test/e2e/{fixtures => lib}/dashboard-listener-process.ts (100%) diff --git a/test/e2e/fixtures/dashboard-listener-process.ts b/test/e2e/lib/dashboard-listener-process.ts similarity index 100% rename from test/e2e/fixtures/dashboard-listener-process.ts rename to test/e2e/lib/dashboard-listener-process.ts diff --git a/test/e2e/live/double-onboard.test.ts b/test/e2e/live/double-onboard.test.ts index 874d35e3773..597466b4f1b 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -22,12 +22,12 @@ import { dashboardForwardProcessIdentity, startForeignDashboardListener, waitForDashboardListenerToStop, -} from "../fixtures/dashboard-listener-process.ts"; +} from "../lib/dashboard-listener-process.ts"; // -// This intentionally stays as one free-standing live test with local -// helpers: the contract is a real OpenShell/Docker/nemoclaw lifecycle -// boundary, but it does not need a new registry target or shared fixture. +// This intentionally stays as one free-standing live test: the contract is a +// real OpenShell/Docker/nemoclaw lifecycle boundary, but it does not need a +// second registry target. const REGISTRY_FILE = path.join(os.homedir(), ".nemoclaw", "sandboxes.json"); const SANDBOX_A = process.env.NEMOCLAW_DOUBLE_ONBOARD_SANDBOX_A ?? "e2e-double-a"; diff --git a/test/e2e/live/onboard-resume.test.ts b/test/e2e/live/onboard-resume.test.ts index f036b491ac2..8672253ac2a 100644 --- a/test/e2e/live/onboard-resume.test.ts +++ b/test/e2e/live/onboard-resume.test.ts @@ -23,7 +23,7 @@ import { createCorporateCaFixture, registeredCorporateCaWorkloadKind, } from "../fixtures/corporate-ca.ts"; -import { dashboardForwardProcessIdentity } from "../fixtures/dashboard-listener-process.ts"; +import { dashboardForwardProcessIdentity } from "../lib/dashboard-listener-process.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { REGISTRY_FILE, diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 569c21379a3..8bec765a17d 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -663,11 +663,16 @@ describe("E2E workflow plan", () => { }); it("selects every dashboard-listener helper consumer", () => { - const targets = catalogueTargetsForChangedFiles([ - "test/e2e/fixtures/dashboard-listener-process.ts", - ]); + const changedFile = "test/e2e/lib/dashboard-listener-process.ts"; + const plan = buildE2eWorkflowPlan({}, { changedFiles: [changedFile] }); + const targets = catalogueTargetsForChangedFiles([changedFile]); expect(targets.map((target) => target.id)).toEqual(["double-onboard", "onboard-resume"]); + expect(Object.values(plan.catalogueMatrices).flat().map((row) => row.id)).toEqual([ + "double-onboard", + "onboard-resume", + ]); + expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard", "jetson-nvmap-gpu"]); }); it.each([ diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index e1218c397a9..411c096d028 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -181,7 +181,7 @@ describe("finalization dashboard ForwardTcp launch", () => { /port 18790 for sandbox 'reonboard-test'.*listener-not-unique.*stop the extra listener.*onboard --resume/su, ], ] as const)( - "reports %s ownership recovery during Ready sandbox reuse (#11074)", + "reports listener ownership failure (%s) during Ready sandbox reuse (#11074)", (failure, message) => { vi.stubEnv("CHAT_UI_URL", undefined); const { helpers, launch } = harness({ diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index cd849e0c434..a31e550478a 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -766,7 +766,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ installMode: "authenticated", restoreCli: true, exposeCliBin: true, - owningPaths: ["test/e2e/fixtures/dashboard-listener-process.ts"], + owningPaths: ["test/e2e/lib/dashboard-listener-process.ts"], environment: nonInteractive, }), managedRuntimeTarget("gpu-double-onboard", { @@ -1096,7 +1096,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, exposeCliBin: true, owningPaths: [ - "test/e2e/fixtures/dashboard-listener-process.ts", + "test/e2e/lib/dashboard-listener-process.ts", "tools/e2e/onboard-timeout-contract.mts", ], environment: { ...nonInteractive, NEMOCLAW_SANDBOX_NAME: "e2e-resume" }, From 7fbe756a25d76a060515faf62b8e21429c5a1bf1 Mon Sep 17 00:00:00 2001 From: San Dang Date: Sat, 5 Sep 2026 20:36:29 +0700 Subject: [PATCH 12/12] fix(onboard): bind forward reuse to sandbox identity --- src/lib/onboard/dashboard-forward-control.ts | 4 +- src/lib/onboard/dashboard.ts | 3 +- src/lib/onboard/sandbox-reuse.test.ts | 7 +-- src/lib/onboard/sandbox-reuse.ts | 4 +- test/e2e/lib/dashboard-listener-process.ts | 50 +++---------------- ...ard-finalization-dashboard-forward.test.ts | 25 ++++++++++ 6 files changed, 41 insertions(+), 52 deletions(-) diff --git a/src/lib/onboard/dashboard-forward-control.ts b/src/lib/onboard/dashboard-forward-control.ts index 1349c398901..a12d1111de0 100644 --- a/src/lib/onboard/dashboard-forward-control.ts +++ b/src/lib/onboard/dashboard-forward-control.ts @@ -21,6 +21,8 @@ export function normalizeDashboardForwardOptions(options: DashboardForwardOption return { rollbackSandboxOnFailure: options.rollbackSandboxOnFailure === true, allowPortReallocation: options.allowPortReallocation !== false, - preserveRegisteredForward: options.preserveRegisteredForward === true, + preserveRegisteredForward: + options.preserveRegisteredForward === true && + typeof options.revalidateSandboxIdentity === "function", }; } diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index c5ce155f127..60b097f5258 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -451,10 +451,11 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa const listedOwner = findDashboardForwardOwner(existingForwards, String(preferredPort)); if ( preserveRegisteredForward && + revalidateSandboxIdentity !== undefined && listedOwner === null && !registryOccupiedPorts.has(String(preferredPort)) ) { - revalidateSandboxIdentity?.( + revalidateSandboxIdentity( `preserve registered dashboard forward ${String(preferredPort)} for sandbox '${sandboxName}'`, ); const preferredTarget = getDashboardForwardTarget(chatUiUrl); diff --git a/src/lib/onboard/sandbox-reuse.test.ts b/src/lib/onboard/sandbox-reuse.test.ts index a92cea2a183..27c514524bc 100644 --- a/src/lib/onboard/sandbox-reuse.test.ts +++ b/src/lib/onboard/sandbox-reuse.test.ts @@ -73,9 +73,10 @@ describe("applyReusedSandboxDashboardState", () => { gatewayPort: 8080, }); expect(result.hermesDashboardState).toBe(hermesDashboardState); - expect(ensureDashboardForward).toHaveBeenCalledWith("reuse-me", "http://127.0.0.1:18789", { - preserveRegisteredForward: true, - }); + expect(ensureDashboardForward).toHaveBeenCalledWith( + "reuse-me", + "http://127.0.0.1:18789", + ); }); it("retains the exact live identity selected for reuse (#11074)", () => { diff --git a/src/lib/onboard/sandbox-reuse.ts b/src/lib/onboard/sandbox-reuse.ts index d83f97852c2..acd1e6a9dab 100644 --- a/src/lib/onboard/sandbox-reuse.ts +++ b/src/lib/onboard/sandbox-reuse.ts @@ -153,9 +153,7 @@ export function applyReusedSandboxDashboardState( preserveRegisteredForward: true, revalidateSandboxIdentity: input.revalidateSandboxIdentity, }) - : input.ensureDashboardForward(input.sandboxName, input.chatUiUrl, { - preserveRegisteredForward: true, - }) + : input.ensureDashboardForward(input.sandboxName, input.chatUiUrl) : 0; const chatUiUrl = manageDashboard ? `http://127.0.0.1:${dashboardPort}` : input.chatUiUrl; if (manageDashboard) { diff --git a/test/e2e/lib/dashboard-listener-process.ts b/test/e2e/lib/dashboard-listener-process.ts index b486fc74369..9001ca7edf4 100644 --- a/test/e2e/lib/dashboard-listener-process.ts +++ b/test/e2e/lib/dashboard-listener-process.ts @@ -5,6 +5,8 @@ import fs from "node:fs"; import { createServer, type Server } from "node:net"; import path from "node:path"; +import { listLinuxProcListenerPids } from "../../../src/lib/adapters/openshell/forward-service-ownership.ts"; + export interface DashboardListenerProcessIdentity { pid: number; uid: number; @@ -12,52 +14,12 @@ export interface DashboardListenerProcessIdentity { argv: string[]; } -function tcpListenerInodes(port: number): Set { - const inodes = new Set(); - for (const tablePath of ["/proc/net/tcp", "/proc/net/tcp6"]) { - let table: string; - try { - table = fs.readFileSync(tablePath, "utf8"); - } catch { - continue; - } - for (const line of table.split(/\r?\n/u).slice(1)) { - const fields = line.trim().split(/\s+/u); - const localAddress = fields[1]; - const state = fields[3]; - const inode = fields[9]; - const localPortHex = localAddress?.split(":").at(-1); - if (state === "0A" && inode && localPortHex && Number.parseInt(localPortHex, 16) === port) { - inodes.add(inode); - } - } - } - return inodes; -} - function dashboardListenerProcessIds(port: number): number[] { - const socketLinks = new Set([...tcpListenerInodes(port)].map((inode) => `socket:[${inode}]`)); - if (socketLinks.size === 0) return []; - - const processIds: number[] = []; - for (const entry of fs.readdirSync("/proc", { withFileTypes: true })) { - if (!entry.isDirectory() || !/^\d+$/u.test(entry.name)) continue; - let descriptors: string[]; - try { - descriptors = fs.readdirSync(path.join("/proc", entry.name, "fd")); - } catch { - continue; - } - const ownsListener = descriptors.some((descriptor) => { - try { - return socketLinks.has(fs.readlinkSync(path.join("/proc", entry.name, "fd", descriptor))); - } catch { - return false; - } - }); - if (ownsListener) processIds.push(Number(entry.name)); + const processIds = listLinuxProcListenerPids(port); + if (processIds === null) { + throw new Error(`Could not inspect the listener process on dashboard port ${String(port)}.`); } - return processIds.sort((left, right) => left - right); + return [...processIds].sort((left, right) => left - right); } export function dashboardForwardProcessIdentity(port: number): DashboardListenerProcessIdentity { diff --git a/test/onboarding/onboard-finalization-dashboard-forward.test.ts b/test/onboarding/onboard-finalization-dashboard-forward.test.ts index 411c096d028..e5dad9c2f9c 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -114,6 +114,27 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(process.env.CHAT_UI_URL).toBe("http://127.0.0.1:18790"); }); + it("rejects an owned listener without Ready sandbox identity authority (#11074)", () => { + vi.stubEnv("CHAT_UI_URL", undefined); + const inspectOwnership = vi.fn(() => ({ owned: true }) as const); + const { helpers, launch } = harness({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + inspectOwnership, + isPortBound: (port) => port === 18_790, + }); + + expect(() => + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + }), + ).toThrow(/cannot be reallocated or adopted/u); + expect(inspectOwnership).not.toHaveBeenCalled(); + expect(launch).not.toHaveBeenCalled(); + expect(process.env.CHAT_UI_URL).toBeUndefined(); + }); + it("preserves the registered Hermes dashboard through agent finalization (#11074)", async () => { vi.stubEnv("CHAT_UI_URL", "http://127.0.0.1:18789"); const revalidateSandboxIdentity = vi.fn(); @@ -163,6 +184,7 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(() => helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, + revalidateSandboxIdentity: vi.fn(), }), ).toThrow( /^Registered dashboard port 18790 for sandbox 'reonboard-test' is occupied, but its ForwardTcp ownership check failed \(process-identity-mismatch\)\. Free port 18790 and re-run `nemoclaw onboard --resume`; the listener was not adopted\.$/u, @@ -198,6 +220,7 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(() => helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, + revalidateSandboxIdentity: vi.fn(), }), ).toThrow(message); expect(launch).not.toHaveBeenCalled(); @@ -217,6 +240,7 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(() => helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, + revalidateSandboxIdentity: vi.fn(), }), ).toThrow( /port 18790 for sandbox 'reonboard-test'.*listener-enumeration-unavailable.*Install lsof or restore read access to Linux \/proc/su, @@ -240,6 +264,7 @@ describe("finalization dashboard ForwardTcp launch", () => { expect(() => helpers.ensureFinalizationDashboardForward("reonboard-test", { preserveRegisteredForward: true, + revalidateSandboxIdentity: vi.fn(), }), ).toThrow(/cannot be reallocated/u); expect(launch).not.toHaveBeenCalled();