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..ea41bb4ce40 --- /dev/null +++ b/src/lib/adapters/openshell/forward-service-ownership.test.ts @@ -0,0 +1,203 @@ +// 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 { + inspectForwardServiceListenerOwnership, + listLinuxProcListenerPids, + type ForwardServiceOwnershipDeps, + type ForwardServiceProcessSnapshot, +} 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 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: () => ownedProcessSnapshot(), + 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(inspectForwardServiceListenerOwnership(target, deps)).toEqual({ owned: true }); + expect(deps.listListenerPids).toHaveBeenCalledTimes(2); + }); + + it("accepts the exact ps command line when procfs argv is unavailable", () => { + expect( + inspectForwardServiceListenerOwnership( + target, + ownership({ + inspectProcess: () => ({ + argv: null, + commandLine: [target.executable, ...buildForwardServiceArgs(target)].join(" "), + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + }), + }), + ), + ).toEqual({ owned: 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( + inspectForwardServiceListenerOwnership( + target, + ownership({ + inspectProcess: () => ({ + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/operator" }, + executable: target.executable, + uid: 1_000, + ...replacement, + }), + }), + ), + ).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( + 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( + inspectForwardServiceListenerOwnership(target, ownership({ currentUid: () => null })), + ).toMatchObject({ owned: false }); + }); + + it("rejects a listener from another OpenShell configuration home", () => { + expect( + inspectForwardServiceListenerOwnership( + target, + ownership({ + inspectProcess: () => ({ + argv: [target.executable, ...buildForwardServiceArgs(target)], + commandLine: null, + environment: { HOME: "/home/other" }, + executable: target.executable, + uid: 1_000, + }), + }), + ), + ).toMatchObject({ owned: false }); + }); + + it("uses Linux procfs when lsof cannot enumerate the listener", () => { + const { listListenerPids: _listListenerPids, ...fallbackDeps } = ownership(); + const listLinuxProcListenerPids = vi.fn(() => [4_242]); + + expect( + inspectForwardServiceListenerOwnership(target, { + ...fallbackDeps, + platform: "linux", + listLsofListenerPids: () => null, + listLinuxProcListenerPids, + }), + ).toEqual({ owned: 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("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 })), + ).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 new file mode 100644 index 00000000000..942e970f55c --- /dev/null +++ b/src/lib/adapters/openshell/forward-service-ownership.ts @@ -0,0 +1,357 @@ +// 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; +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; + 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 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; +} + +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 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"]); + 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 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 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(); + 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 ?? ""); + 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; + 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((entry) => entry.includes("=")) + .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]) + ); +} + +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, + deps: ForwardServiceOwnershipDeps = {}, +): ForwardServiceOwnershipResult { + validateForwardServiceTarget(target); + const enumerate = (port: number) => ownershipListenerPids(port, deps); + const before = enumerate(target.localPort); + 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 { owned: false, failure: "listener-not-unique" }; + } + + const currentUid = deps.currentUid + ? deps.currentUid() + : typeof process.getuid === "function" + ? process.getuid() + : null; + 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" }; + } + if ( + !processMatchesForwardTarget( + pid, + deps, + currentUid, + expectedEnvironment, + expectedExecutable, + expectedArgv, + ) + ) { + 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 }; +} diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 4ecee3a2c4d..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, @@ -3245,13 +3247,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, + ...(options ?? {}), + }), persistDashboardPort: (name, port) => registry.updateSandbox(name, { dashboardPort: port }), recordStepSkipped, 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-forward-control.ts b/src/lib/onboard/dashboard-forward-control.ts index 7b58fd24393..a12d1111de0 100644 --- a/src/lib/onboard/dashboard-forward-control.ts +++ b/src/lib/onboard/dashboard-forward-control.ts @@ -5,15 +5,24 @@ export interface DashboardForwardOptions { rollbackSandboxOnFailure?: boolean; gatewayName?: string; allowPortReallocation?: boolean; + /** + * 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; } export function normalizeDashboardForwardOptions(options: DashboardForwardOptions = {}): { rollbackSandboxOnFailure: boolean; allowPortReallocation: boolean; + preserveRegisteredForward: boolean; } { return { rollbackSandboxOnFailure: options.rollbackSandboxOnFailure === true, allowPortReallocation: options.allowPortReallocation !== false, + preserveRegisteredForward: + options.preserveRegisteredForward === true && + typeof options.revalidateSandboxIdentity === "function", }; } diff --git a/src/lib/onboard/dashboard.ts b/src/lib/onboard/dashboard.ts index 615e45e0ad7..60b097f5258 100644 --- a/src/lib/onboard/dashboard.ts +++ b/src/lib/onboard/dashboard.ts @@ -8,6 +8,11 @@ import { launchForwardService, type ForwardServiceTarget, } from "../adapters/openshell/forward-service"; +import { + inspectForwardServiceListenerOwnership, + type ForwardServiceOwnershipFailure, + 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"; @@ -27,6 +32,7 @@ import { } from "./dashboard-forward-control"; import { findAvailableDashboardPort, + findDashboardForwardOwner, getPersistedDashboardPort, getRegistryOccupiedDashboardPorts, isPortBoundOnHost, @@ -44,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\`; ` + + "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 { @@ -87,6 +130,7 @@ export interface OnboardDashboardDeps { /** Direct ForwardTcp launcher. */ forwardService?: { executable(): string; + inspectOwnership?(target: ForwardServiceTarget): ForwardServiceOwnershipResult; launch?(target: ForwardServiceTarget): void; retireLegacy?(sandboxName: string, gatewayName: string, ports: readonly number[]): number; resolveGatewayName( @@ -135,19 +179,26 @@ export interface OnboardDashboardHelpers { agent: { forwardPort?: number | null; forward_ports?: number[] | null }, options?: { beforeForwardPort?: (port: number) => Promise | void; + preserveRegisteredForward?: boolean; revalidateSandboxIdentity?: (operation: string) => void; }, ): 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( @@ -224,6 +275,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa if (!executable) throw new Error("OpenShell is unavailable"); return executable; }, + inspectOwnership: inspectForwardServiceListenerOwnership, resolveGatewayName: productionForwardService.resolveGatewayName, retireLegacy: (sandboxName: string, gatewayName: string, ports: readonly number[]) => productionForwardService.retireLegacy(sandboxName, gatewayName, ports, { @@ -379,7 +431,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 +446,34 @@ 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 && + revalidateSandboxIdentity !== undefined && + listedOwner === null && + !registryOccupiedPorts.has(String(preferredPort)) + ) { + revalidateSandboxIdentity( + `preserve registered dashboard forward ${String(preferredPort)} for sandbox '${sandboxName}'`, + ); + const preferredTarget = getDashboardForwardTarget(chatUiUrl); + const ownership = forwardService?.inspectOwnership?.( + forwardTarget(sandboxName, forwardGateway, preferredPort, preferredTarget), + ); + if (ownership?.owned === true) return preferredPort; + if (ownership?.owned === false) { + throw new Error( + dashboardForwardOwnershipFailureMessage( + ownership.failure, + preferredPort, + sandboxName, + deps.cliName(), + ), + ); + } + } throw new Error( `Registered dashboard port ${String(preferredPort)} is already occupied; it cannot be reallocated or adopted.`, ); @@ -406,7 +485,7 @@ export function createOnboardDashboardHelpers(deps: OnboardDashboardDeps): Onboa preferredPort, existingForwards, isPortBound, - getRegistryOccupiedDashboardPorts(sandboxName, listSandboxes), + registryOccupiedPorts, ); } catch (err) { if (!rollbackSandboxOnFailure) throw err; @@ -505,20 +584,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}'`); @@ -534,6 +621,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 { @@ -546,6 +634,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, }); } @@ -553,19 +642,31 @@ 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, { + preserveRegisteredForward, revalidateSandboxIdentity, beforeForwardPort: portReservation ? (port) => portReservation.releaseBeforeForward(agent.name, port) : undefined, }) - : ensureFinalizationDashboardForward(sandboxName, revalidateSandboxIdentity); + : ensureFinalizationDashboardForward(sandboxName, { + revalidateSandboxIdentity, + preserveRegisteredForward, + }); } function ensureAgentFixedForward( 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.test.ts b/src/lib/onboard/machine/handlers/agent-setup.test.ts index c3ad023ec1a..63bb28fab53 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.test.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.test.ts @@ -104,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); @@ -170,6 +190,57 @@ describe("handleAgentSetupState", () => { }); }); + 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); + }); + + 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 0bebdedbc60..9a938ac8996 100644 --- a/src/lib/onboard/machine/handlers/agent-setup.ts +++ b/src/lib/onboard/machine/handlers/agent-setup.ts @@ -28,7 +28,14 @@ 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; + revalidateSandboxIdentity?: (operation: string) => void; + }, + ): Promise | number; persistDashboardPort(sandboxName: string, dashboardPort: number): void; recordStepSkipped(stepName: string): Promise; isOpenclawReady(sandboxName: string): boolean; @@ -78,6 +85,12 @@ export async function handleAgentSetupState({ revalidateSandboxIdentity, deps, }: AgentSetupStateOptions): Promise { + // 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, @@ -93,7 +106,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); } @@ -134,7 +149,9 @@ export async function handleAgentSetupState({ deps.toSessionUpdates({ sandboxName, provider, model, hermesAuthMethod, hermesToolGateways }), ); } - const dashboardPort = await deps.ensureAgentDashboardForward(sandboxName, null); + const dashboardPort = await (dashboardOptions + ? deps.ensureAgentDashboardForward(sandboxName, null, dashboardOptions) + : deps.ensureAgentDashboardForward(sandboxName, null)); if (dashboardPort > 0) { deps.persistDashboardPort(sandboxName, dashboardPort); } 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..02465871712 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1302,6 +1302,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 { @@ -1699,7 +1702,29 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche readEntry: () => registry.getSandbox(sandboxName), }); const resumingVerifiedCreate = acceptedTargetPendingIdentity !== null; + let reusedSandboxIdentityRevalidation: ((operation: string) => void) | undefined; + const selectReusedSandboxIdentity = (): ((operation: string) => void) | undefined => { + if (!manageDashboard) return undefined; + reusedSandboxIdentityRevalidation ??= sandboxReuse.createReusedSandboxIdentityRevalidation({ + sandboxName, + openingObservation: getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), + registeredIdentity: + registry.getSandbox(sandboxName)?.lifecycleLiveIdentityFingerprint ?? null, + observe: () => getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), + }); + 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, @@ -1716,7 +1741,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche hermesDashboardForwarding, updateReusedSandboxMetadata, releaseDashboardPort: dashboardPortReservationScope.release, - revalidateSandboxIdentity: (operation) => revalidateSandboxIdentity(true, operation), + revalidateSandboxIdentity: revalidateReusedSandboxIdentity, })); }; if (recreateRuntime.acceptedTarget && !resumingVerifiedCreate) { @@ -1896,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( @@ -1946,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-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..27c514524bc 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,50 @@ describe("applyReusedSandboxDashboardState", () => { gatewayPort: 8080, }); expect(result.hermesDashboardState).toBe(hermesDashboardState); + expect(ensureDashboardForward).toHaveBeenCalledWith( + "reuse-me", + "http://127.0.0.1:18789", + ); + }); + + 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.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", () => { @@ -151,7 +197,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 +243,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..acd1e6a9dab 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,12 +146,11 @@ 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) diff --git a/test/e2e/lib/dashboard-listener-process.ts b/test/e2e/lib/dashboard-listener-process.ts new file mode 100644 index 00000000000..9001ca7edf4 --- /dev/null +++ b/test/e2e/lib/dashboard-listener-process.ts @@ -0,0 +1,88 @@ +// 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"; + +import { listLinuxProcListenerPids } from "../../../src/lib/adapters/openshell/forward-service-ownership.ts"; + +export interface DashboardListenerProcessIdentity { + pid: number; + uid: number; + startTimeTicks: string; + argv: string[]; +} + +function dashboardListenerProcessIds(port: number): number[] { + 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); +} + +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 e90538c514d..597466b4f1b 100644 --- a/test/e2e/live/double-onboard.test.ts +++ b/test/e2e/live/double-onboard.test.ts @@ -17,11 +17,17 @@ 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 "../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"; @@ -417,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", ], @@ -501,10 +508,12 @@ 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", "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", ], }); @@ -516,14 +525,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 +555,14 @@ 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 = 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)}`, + ); progress.phase("re-onboard same sandbox on existing gateway"); // Phase 3: second onboard with the same name must reuse the healthy gateway. @@ -566,10 +575,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 +582,22 @@ test( }); expect(sandboxAAfterSecond.exitCode, resultText(sandboxAAfterSecond)).toBe(0); expect(parseOpenShellSandboxId(resultText(sandboxAAfterSecond))).toBe(sandboxAIdAfterFirst); + const forwardIdentityAfterSecond = dashboardForwardProcessIdentity(dashboardPort); + await artifacts.writeJson("phase-3-dashboard-forward-identity.json", forwardIdentityAfterSecond); + expect(forwardIdentityAfterSecond).toEqual(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 +608,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); @@ -601,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. @@ -628,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", @@ -684,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, @@ -772,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"], { @@ -798,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"], { @@ -825,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(), @@ -889,6 +953,13 @@ test( secondOnboardReusedGateway: gatewayAfterSecond === gatewayBeforeSecond && secondText.includes("Reusing healthy NemoClaw gateway."), + secondOnboardRetainedDashboardForward: + 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/e2e/live/onboard-resume.test.ts b/test/e2e/live/onboard-resume.test.ts index fe94c8b644e..8672253ac2a 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 "../lib/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 b68d8fd1d0b..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", @@ -473,6 +474,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/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index d25b31a80d5..8bec765a17d 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -662,6 +662,19 @@ describe("E2E workflow plan", () => { expect(selectedWorkflowJobs(plan)).toEqual(["catalogue-standard", "jetson-nvmap-gpu"]); }); + it("selects every dashboard-listener helper consumer", () => { + 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([ "nemoclaw-blueprint/router/pool-config.yaml", "test/e2e/live/model-router-provider-routed-inference-helpers.ts", 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; }), 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 6a8eefd0f5d..e5dad9c2f9c 100644 --- a/test/onboarding/onboard-finalization-dashboard-forward.test.ts +++ b/test/onboarding/onboard-finalization-dashboard-forward.test.ts @@ -3,11 +3,17 @@ 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; }) { const launch = vi.fn(); @@ -24,9 +30,11 @@ 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", + inspectOwnership: options.inspectOwnership, launch, resolveGatewayName: () => "nemoclaw", retireLegacy: vi.fn(() => 0), @@ -71,6 +79,197 @@ 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 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, + }); + + expect( + helpers.ensureFinalizationDashboardForward("reonboard-test", { + preserveRegisteredForward: true, + revalidateSandboxIdentity, + }), + ).toBe(18_790); + expect(inspectOwnership).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 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(); + 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({ + listSandboxes: () => ({ + sandboxes: [{ name: "reonboard-test", dashboardPort: 18_790 }], + }), + inspectOwnership: () => ({ owned: false, failure: "process-identity-mismatch" }), + isPortBound: (port) => port === 18_790, + }); + + 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, + ); + 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 listener ownership failure (%s) 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, + revalidateSandboxIdentity: vi.fn(), + }), + ).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({ + 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, + revalidateSandboxIdentity: vi.fn(), + }), + ).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(); + }); + + 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, + revalidateSandboxIdentity: vi.fn(), + }), + ).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({ 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 }); diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index e094a3980a6..a31e550478a 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/lib/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/lib/dashboard-listener-process.ts", + "tools/e2e/onboard-timeout-contract.mts", + ], environment: { ...nonInteractive, NEMOCLAW_SANDBOX_NAME: "e2e-resume" }, }), managedRuntimeTarget("openclaw-discord-pairing", {