diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx
index 55ed8cdf82b..318f662d851 100644
--- a/docs/reference/commands.mdx
+++ b/docs/reference/commands.mdx
@@ -1057,6 +1057,10 @@ The sandbox name is required, and the command takes no flags. The sandbox must a
+For an older OpenClaw registration without recorded lifecycle identity, `launch` requires a ready live sandbox with an observable identity before it starts the agent.
+If this identity check fails, `launch` stops before starting the agent.
+Run `$$nemoclaw doctor`, resolve the reported issue, and retry `$$nemoclaw launch `.
+
`launch` returns the agent's exit code when the post-command OpenClaw permission cleanup succeeds. If that cleanup cannot inspect, restore, or verify the mutable config permission contract, `launch` fails closed with exit `1` and prints `OpenClaw permission cleanup failed (...)` to `stderr`.
diff --git a/src/lib/actions/sandbox/exec.test.ts b/src/lib/actions/sandbox/exec.test.ts
index 7b9e1446aad..e0f7c63e5d1 100644
--- a/src/lib/actions/sandbox/exec.test.ts
+++ b/src/lib/actions/sandbox/exec.test.ts
@@ -1,9 +1,30 @@
// 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 os from "node:os";
+import path from "node:path";
+
import { afterEach, describe, expect, it, vi } from "vitest";
-import { execSandbox, type SandboxExecCleanupDeps, workdirMissingMessage } from "./exec";
+import { execTimeout, testTimeoutOptions } from "../../../../test/helpers/timeouts";
+
+import {
+ withMcpLifecycleLock,
+ withMcpLifecycleLockSync,
+ isMcpLifecycleLockHeld,
+} from "../../state/mcp-lifecycle-lock-acquisition";
+import {
+ withPortableHostFence,
+ portableHostFencePath,
+} from "../../state/portable-uninstall-retirement";
+import {
+ execSandbox,
+ startSandboxExec,
+ type SandboxExecCleanupDeps,
+ workdirMissingMessage,
+} from "./exec";
describe("workdirMissingMessage", () => {
it("renders a user-facing CLI error with the offending path", () => {
@@ -303,3 +324,184 @@ describe("execSandbox scope-upgrade hint wiring (#9744)", () => {
expect(stderr).toBe("");
});
});
+
+it.each([
+ { mode: "sync", error: new Error("lock timed out"), commandCode: 0, invocationFailed: false },
+ {
+ mode: "async",
+ error: new Error("migration blocked"),
+ commandCode: 23,
+ invocationFailed: false,
+ },
+ { mode: "async", error: "registry unavailable", commandCode: 1, invocationFailed: true },
+])(
+ "reports $mode cleanup authority failure after command status $commandCode (#11647)",
+ async ({ mode, error, commandCode, invocationFailed }) => {
+ const stderr = vi.spyOn(console, "error").mockImplementation(() => {});
+ const release = vi.fn();
+ const inspect = vi.fn(() => ({ applies: true as const, ok: true, issues: [] }));
+ const exit = vi.fn((code: number): never => {
+ throw new Error(`exit:${code}`);
+ });
+ try {
+ const finish = await startSandboxExec(
+ "alpha",
+ ["true"],
+ {},
+ {
+ selectGateway: () => ({ outcome: "unregistered", gatewayName: null }),
+ commandExecutor: {
+ probeDirectory: async () => ({ state: "present" }),
+ runStreaming: async () => ({
+ outcome: invocationFailed
+ ? { kind: "failed", error: { kind: "invocation", message: "transport failed" } }
+ : { kind: "completed", exitCode: commandCode },
+ release,
+ }),
+ },
+ withCleanupAuthority:
+ mode === "sync"
+ ? () => {
+ throw error;
+ }
+ : () => Promise.reject(error),
+ cleanupDeps: {
+ getSandbox: () => ({ agent: "openclaw" }),
+ inspectMutableConfigPerms: inspect,
+ repairMutableConfigPerms: () => ({ applied: true, verified: true, errors: [] }),
+ },
+ policyHint: {
+ env: {},
+ probeLogs: () => "",
+ enableAudit: () => {},
+ sleep: async () => {},
+ attempts: 1,
+ },
+ exit,
+ },
+ );
+ await expect(finish()).rejects.toThrow("exit:1");
+ expect(exit).toHaveBeenCalledExactlyOnceWith(1);
+ expect(stderr).toHaveBeenCalledWith(
+ ` OpenClaw permission cleanup failed (command exit ${commandCode}; cleanup exit 1): cleanup authority unavailable: ${error instanceof Error ? error.message : error}`,
+ );
+ expect(
+ stderr.mock.calls.filter(([line]) => String(line).includes("Failed to invoke openshell")),
+ ).toHaveLength(invocationFailed ? 1 : 0);
+ expect(inspect).not.toHaveBeenCalled();
+ expect(release).toHaveBeenCalledOnce();
+ } finally {
+ stderr.mockRestore();
+ }
+ },
+);
+
+it(
+ "releases authority to another process before interactive completion (#11647)",
+ testTimeoutOptions(15_000),
+ async () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-exec-"));
+ const stateDir = path.join(home, "state");
+ const lockOptions = { stateDir };
+ const sandboxName = "launch-exec";
+ let endSession: () => void = () => {};
+ const ended = new Promise((resolve) => {
+ endSession = resolve;
+ });
+ const release = vi.fn();
+ const cleanup = vi.fn(() =>
+ withMcpLifecycleLockSync(
+ sandboxName,
+ () => {
+ expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true);
+ return { applies: true as const, ok: true, issues: [] };
+ },
+ lockOptions,
+ ),
+ );
+ let dispatched = false;
+ let lockHeldDuringCleanup: boolean | null = null;
+ let fenceHeldDuringCleanup: boolean | null = null;
+ try {
+ const finish = await withPortableHostFence(home, () =>
+ withMcpLifecycleLock(
+ sandboxName,
+ () =>
+ startSandboxExec(
+ sandboxName,
+ ["bash", "-lc", "openclaw tui"],
+ { tty: true, stdin: true, timeoutSeconds: 0 },
+ {
+ selectGateway: () => ({ outcome: "unregistered", gatewayName: null }),
+ commandExecutor: {
+ probeDirectory: async () => ({ state: "present" }),
+ runStreaming: async () => {
+ expect(isMcpLifecycleLockHeld(sandboxName, stateDir)).toBe(true);
+ expect(fs.existsSync(portableHostFencePath(home))).toBe(true);
+ dispatched = true;
+ await ended;
+ return { outcome: { kind: "completed", exitCode: 0 }, release };
+ },
+ },
+ cleanupDeps: {
+ getSandbox: () => {
+ lockHeldDuringCleanup = isMcpLifecycleLockHeld(sandboxName, stateDir);
+ fenceHeldDuringCleanup = fs.existsSync(portableHostFencePath(home));
+ return { agent: "openclaw" };
+ },
+ inspectMutableConfigPerms: cleanup,
+ repairMutableConfigPerms: () => {
+ throw new Error("healthy config needs no repair");
+ },
+ },
+ exit: (code) => {
+ throw new Error(`exit:${code}`);
+ },
+ },
+ ),
+ lockOptions,
+ ),
+ );
+ expect(dispatched).toBe(true);
+ expect(cleanup).not.toHaveBeenCalled();
+ const contender = spawnSync(
+ process.execPath,
+ [
+ "--no-warnings",
+ "--import",
+ "tsx",
+ "--input-type=module",
+ "-e",
+ `
+ const retirement = (await import(process.argv[1])).default;
+ const lifecycle = (await import(process.argv[2])).default;
+ await retirement.withPortableHostFence(process.argv[3], () =>
+ lifecycle.withMcpLifecycleLock(process.argv[4], () => {
+ console.log("contender-entered");
+ }, { stateDir: process.argv[5] }),
+ );
+ `,
+ new URL("../../state/portable-uninstall-retirement.ts", import.meta.url).href,
+ new URL("../../state/mcp-lifecycle-lock-acquisition.ts", import.meta.url).href,
+ home,
+ sandboxName,
+ stateDir,
+ ],
+ { encoding: "utf8", timeout: execTimeout() },
+ );
+ expect(contender.status, contender.stderr || String(contender.error ?? "")).toBe(0);
+ expect(contender.stdout.trim()).toBe("contender-entered");
+ expect(cleanup).not.toHaveBeenCalled();
+ expect(release).not.toHaveBeenCalled();
+ endSession();
+ await expect(finish()).rejects.toThrow("exit:0");
+ expect(lockHeldDuringCleanup).toBe(false);
+ expect(fenceHeldDuringCleanup).toBe(false);
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(release).toHaveBeenCalledOnce();
+ } finally {
+ endSession();
+ fs.rmSync(home, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/src/lib/actions/sandbox/exec.ts b/src/lib/actions/sandbox/exec.ts
index 1e1a930df2e..5876562f7b5 100644
--- a/src/lib/actions/sandbox/exec.ts
+++ b/src/lib/actions/sandbox/exec.ts
@@ -148,6 +148,8 @@ export type ExecSandboxDeps = {
/** Post-command observability and cleanup seams. */
policyHint?: ExecPolicyHintDeps;
cleanupDeps?: SandboxExecCleanupDeps;
+ /** Reacquire and verify dispatch authority before delayed launch cleanup. */
+ withCleanupAuthority?: (cleanup: () => string | null) => Promise;
/** Activate config written by a successful direct Google Chat pairing approval. */
restartGateway?: SandboxExecGatewayRestart;
/** Resolve the sandbox's recorded agent before applying agent-specific post-exec effects. */
@@ -161,8 +163,7 @@ export type ExecSandboxDeps = {
async function runSandboxExecRequest(
executor: OpenShellSandboxCommandExecutor,
request: OpenShellSandboxCommandRequest,
- cleanupDeps: SandboxExecCleanupDeps,
-): Promise {
+): Promise>> {
let completed: Awaited>;
try {
completed = await executor.runStreaming(request);
@@ -178,11 +179,28 @@ async function runSandboxExecRequest(
release: () => {},
};
}
+ return completed;
+}
+
+async function finishSandboxExecRequest(
+ completed: Awaited>,
+ request: OpenShellSandboxCommandRequest,
+ cleanupDeps: SandboxExecCleanupDeps,
+ withCleanupAuthority?: ExecSandboxDeps["withCleanupAuthority"],
+): Promise {
try {
const commandCode = completed.outcome.kind === "completed" ? completed.outcome.exitCode : 1;
const invocationError =
completed.outcome.kind === "failed" ? completed.outcome.error.message : undefined;
- const cleanupError = cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps) ?? undefined;
+ const cleanup = () => cleanupOpenClawAfterExec(request.sandboxName, cleanupDeps);
+ let cleanupError: string | undefined;
+ try {
+ cleanupError =
+ (await (withCleanupAuthority ? withCleanupAuthority(cleanup) : cleanup())) ?? undefined;
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : String(error);
+ cleanupError = `cleanup authority unavailable: ${detail}`;
+ }
return {
code: cleanupError ? 1 : commandCode,
commandCode,
@@ -240,6 +258,17 @@ export async function execSandbox(
options: SandboxExecOptions = {},
deps: ExecSandboxDeps = {},
): Promise {
+ const finish = await startSandboxExec(sandboxName, command, options, deps);
+ await finish();
+}
+
+/** Dispatch under the caller's lifecycle fence; invoke completion after releasing it. */
+export async function startSandboxExec(
+ sandboxName: string,
+ command: readonly string[],
+ options: SandboxExecOptions = {},
+ deps: ExecSandboxDeps = {},
+): Promise<() => Promise> {
const { CLI_NAME } = require("../../cli/branding");
const exit = deps.exit ?? process.exit;
if (command.length === 0) {
@@ -296,71 +325,78 @@ export async function execSandbox(
deps.policyHint,
gatewayName,
);
- const completion = await runSandboxExecRequest(
- commandExecutor,
- {
- sandboxName,
- target,
- command: wrapExecCommandWithRuntimeEnv(command),
- workdir: options.workdir,
- tty: options.tty,
- timeoutSeconds: options.timeoutSeconds,
- stdin: options.stdin,
- },
- deps.cleanupDeps ?? {
- getSandbox: (name) =>
- (require("../../state/registry") as typeof import("../../state/registry")).getSandbox(name),
- inspectMutableConfigPerms: (name) =>
- (
- require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms")
- ).inspectMutableConfigPerms(name),
- repairMutableConfigPerms: (name) =>
- (
- require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms")
- ).repairMutableConfigPerms(name),
- },
- );
- if (completion.invocationError) {
- console.error(` Failed to invoke openshell: ${completion.invocationError}`);
- console.error(" Ensure 'openshell' is installed and on PATH.");
- }
- if (completion.cleanupError) {
- console.error(cleanupFailureMessage(completion.commandCode, completion.cleanupError));
- }
- await emitPolicyDenialHint(completion);
- let exitCode = completion.code;
- const googleChatApprovalCommitted =
- completion.commandCode === 0 && isGoogleChatPairingApproval(command);
- const managedGoogleChatApproval =
- googleChatApprovalCommitted && gatewaySelection.outcome === "selected";
- if (googleChatApprovalCommitted && completion.cleanupError) {
- console.error(
- managedGoogleChatApproval
- ? googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName)
- : googleChatPairingUnmanagedCleanupFailureMessage(sandboxName),
+ const request: OpenShellSandboxCommandRequest = {
+ sandboxName,
+ target,
+ command: wrapExecCommandWithRuntimeEnv(command),
+ workdir: options.workdir,
+ tty: options.tty,
+ timeoutSeconds: options.timeoutSeconds,
+ stdin: options.stdin,
+ };
+ const pending = runSandboxExecRequest(commandExecutor, request);
+ return async () => {
+ const completion = await finishSandboxExecRequest(
+ await pending,
+ request,
+ deps.cleanupDeps ?? {
+ getSandbox: (name) =>
+ (require("../../state/registry") as typeof import("../../state/registry")).getSandbox(
+ name,
+ ),
+ inspectMutableConfigPerms: (name) =>
+ (
+ require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms")
+ ).inspectMutableConfigPerms(name),
+ repairMutableConfigPerms: (name) =>
+ (
+ require("../../sandbox/mutable-config-perms") as typeof import("../../sandbox/mutable-config-perms")
+ ).repairMutableConfigPerms(name),
+ },
+ deps.withCleanupAuthority,
);
- }
- if (exitCode === 0 && managedGoogleChatApproval) {
- let recordedAgent: string | null = null;
- try {
- recordedAgent = (deps.resolveSandboxAgent ?? defaultResolveSandboxAgent)(sandboxName);
- } catch {
- console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName));
- exit(1);
+ if (completion.invocationError) {
+ console.error(` Failed to invoke openshell: ${completion.invocationError}`);
+ console.error(" Ensure 'openshell' is installed and on PATH.");
+ }
+ if (completion.cleanupError) {
+ console.error(cleanupFailureMessage(completion.commandCode, completion.cleanupError));
}
- if (recordedAgent === "openclaw") {
- let restartSucceeded = false;
+ await emitPolicyDenialHint(completion);
+ let exitCode = completion.code;
+ const googleChatApprovalCommitted =
+ completion.commandCode === 0 && isGoogleChatPairingApproval(command);
+ const managedGoogleChatApproval =
+ googleChatApprovalCommitted && gatewaySelection.outcome === "selected";
+ if (googleChatApprovalCommitted && completion.cleanupError) {
+ console.error(
+ managedGoogleChatApproval
+ ? googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName)
+ : googleChatPairingUnmanagedCleanupFailureMessage(sandboxName),
+ );
+ }
+ if (exitCode === 0 && managedGoogleChatApproval) {
+ let recordedAgent: string | null = null;
try {
- restartSucceeded = (await (deps.restartGateway ?? defaultRestartGateway)(sandboxName)).ok;
+ recordedAgent = (deps.resolveSandboxAgent ?? defaultResolveSandboxAgent)(sandboxName);
} catch {
- // The approval already committed inside OpenClaw. Convert restart
- // exceptions into the same explicit partial-commit recovery contract.
- }
- if (!restartSucceeded) {
console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName));
- exitCode = 1;
+ exit(1);
+ }
+ if (recordedAgent === "openclaw") {
+ let restartSucceeded = false;
+ try {
+ restartSucceeded = (await (deps.restartGateway ?? defaultRestartGateway)(sandboxName)).ok;
+ } catch {
+ // The approval already committed inside OpenClaw. Convert restart
+ // exceptions into the same explicit partial-commit recovery contract.
+ }
+ if (!restartSucceeded) {
+ console.error(googleChatPairingActivationFailureMessage(CLI_NAME, sandboxName));
+ exitCode = 1;
+ }
}
}
- }
- exit(exitCode);
+ exit(exitCode);
+ };
}
diff --git a/src/lib/actions/sandbox/launch-cleanup.test.ts b/src/lib/actions/sandbox/launch-cleanup.test.ts
new file mode 100644
index 00000000000..765e9409318
--- /dev/null
+++ b/src/lib/actions/sandbox/launch-cleanup.test.ts
@@ -0,0 +1,250 @@
+// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
+import { loadAgent } from "../../agent/defs";
+import type { SandboxEntry } from "../../state/registry";
+import { launchSandbox } from "./launch";
+
+const mocks = vi.hoisted(() => ({ startSandboxExec: vi.fn() }));
+vi.mock("./exec", () => ({ startSandboxExec: mocks.startSandboxExec }));
+vi.mock("./connect", () => ({
+ printInteractiveSessionHints: vi.fn(),
+ completeReadinessQualifiedInteractiveSessionSetup: vi.fn(),
+}));
+vi.mock("./connect-hermes-light-skin", () => ({ prepareHermesLightTerminalSkin: vi.fn() }));
+vi.mock("./gateway-state", async (original) => ({
+ ...(await original()),
+ inspectPortableAgentReceiptDisposition: () => ({ kind: "absent" }),
+}));
+
+function deferred(): { promise: Promise; resolve: () => void } {
+ let resolve!: () => void;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+function createSerialTestLock(
+ events: string[],
+ label: string,
+): (name: string, operation: () => Promise | T) => Promise {
+ let tail = Promise.resolve();
+ return async (_name: string, operation: () => Promise | T): Promise => {
+ const previous = tail;
+ const release = deferred();
+ tail = previous.then(() => release.promise);
+ await previous;
+ events.push(`${label}:acquired`);
+ try {
+ return await operation();
+ } finally {
+ events.push(`${label}:released`);
+ release.resolve();
+ }
+ };
+}
+
+describe("interactive launch cleanup", () => {
+ afterEach(() => vi.unstubAllEnvs());
+ it.each([
+ { replacement: "unchanged", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" },
+ { replacement: "legacy", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" },
+ {
+ replacement: "legacy-replaced",
+ cleanupCount: 0,
+ stateFile: "unrelated.json",
+ error: "exit:0",
+ },
+ {
+ replacement: "legacy-missing",
+ cleanupCount: 0,
+ stateFile: "unrelated.json",
+ error: "exit:0",
+ },
+ {
+ replacement: "legacy-unavailable",
+ cleanupCount: 0,
+ stateFile: "unrelated.json",
+ error: "probe unavailable",
+ },
+ { replacement: "gateway-moved", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" },
+ { replacement: "metadata", cleanupCount: 1, stateFile: "unrelated.json", error: "exit:0" },
+ { replacement: "recreated", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" },
+ { replacement: "removed", cleanupCount: 0, stateFile: "unrelated.json", error: "exit:0" },
+ {
+ replacement: "legacy-recovery",
+ cleanupCount: 0,
+ stateFile: "shields-timer-alpha.json",
+ error: /recovery artifacts from the removed Shields/u,
+ },
+ ])(
+ "binds completion cleanup to the launched sandbox ($replacement)",
+ async ({ replacement, cleanupCount, stateFile, error }) => {
+ const stderr = vi.spyOn(console, "error").mockImplementation(() => {});
+ onTestFinished(() => stderr.mockRestore());
+ const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-launch-cleanup-"));
+ onTestFinished(() => fs.rmSync(stateDir, { recursive: true, force: true }));
+ vi.stubEnv("HOME", stateDir);
+ vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir);
+ vi.stubEnv("NEMOCLAW_TEST_STATE_DIR", stateDir);
+ const statePath = path.join(stateDir, stateFile);
+ const { startSandboxExec } = await vi.importActual("./exec");
+ const agent = loadAgent("openclaw");
+ const legacy = ["legacy", "legacy-replaced", "legacy-missing", "legacy-unavailable"].includes(
+ replacement,
+ );
+ let current: SandboxEntry | null = {
+ ...({ name: "alpha", agent: agent.name } as SandboxEntry),
+ gatewayName: "nemoclaw-8081",
+ lifecycleGeneration: legacy ? undefined : "generation-alpha",
+ lifecycleLiveIdentityFingerprint: legacy ? undefined : "f".repeat(64),
+ };
+ let liveIdentityFingerprint: string | null = "f".repeat(64);
+ const sessionEnded = deferred();
+ const childStarted = deferred();
+ const events: string[] = [];
+ const lock = createSerialTestLock(events, "sandbox");
+ const cleanup = vi.fn(() => {
+ events.push("cleanup");
+ return { applies: true as const, ok: false, issues: ["config mode drift"] };
+ });
+ const repair = vi.fn(() => ({ applied: true as const, verified: true, errors: [] }));
+ const observeSandbox = vi.fn(() => {
+ events.push("identity");
+ return { state: "ready" as const, liveIdentityFingerprint };
+ });
+ const release = vi.fn();
+ mocks.startSandboxExec.mockImplementation((name, command, options, deps) =>
+ startSandboxExec(name, command, options, {
+ ...deps,
+ selectGateway: () => ({ outcome: "unregistered", gatewayName: null }),
+ commandExecutor: {
+ probeDirectory: async () => ({ state: "present" }),
+ runStreaming: async () => {
+ childStarted.resolve();
+ await sessionEnded.promise;
+ return { outcome: { kind: "completed", exitCode: 0 }, release };
+ },
+ },
+ cleanupDeps: {
+ getSandbox: () => current,
+ inspectMutableConfigPerms: cleanup,
+ repairMutableConfigPerms: repair,
+ },
+ policyHint: {
+ env: {},
+ probeLogs: () => "",
+ enableAudit: () => {},
+ sleep: async () => {},
+ attempts: 1,
+ },
+ exit: (code) => {
+ throw new Error(`exit:${code}`);
+ },
+ }),
+ );
+ const launch = launchSandbox("alpha", {
+ inspectLaunchReadiness: async () => ({
+ kind: "accepted",
+ category: "accepted",
+ agent,
+ sb: current!,
+ }),
+ getSandbox: () => current,
+ observeSandbox,
+ withSandboxMutationLock: lock,
+ });
+ const completion = expect(launch).rejects.toThrow(error === "exit:0" ? error : "exit:1");
+ await childStarted.promise;
+ await lock("alpha", () => {
+ fs.writeFileSync(statePath, "recorded state\n");
+ current =
+ replacement === "removed"
+ ? null
+ : {
+ ...current!,
+ gatewayPort: replacement === "gateway-moved" ? 8082 : current!.gatewayPort,
+ model: replacement === "metadata" ? "updated-model" : current!.model,
+ lifecycleGeneration:
+ replacement === "recreated" ? "generation-new" : current!.lifecycleGeneration,
+ };
+ liveIdentityFingerprint =
+ replacement === "legacy-missing"
+ ? null
+ : replacement === "legacy-replaced"
+ ? "e".repeat(64)
+ : liveIdentityFingerprint;
+ observeSandbox.mockImplementation(() => {
+ events.push("identity");
+ replacement !== "legacy-unavailable" ||
+ (() => {
+ throw new Error("probe unavailable");
+ })();
+ return { state: "ready" as const, liveIdentityFingerprint };
+ });
+ events.push("replacement-observed");
+ });
+ expect(cleanup).not.toHaveBeenCalled();
+ events.length = 0;
+ sessionEnded.resolve();
+ await completion;
+ expect(stderr.mock.calls.map(([line]) => line)).toEqual(
+ error === "exit:0" ? [] : [expect.stringMatching(error)],
+ );
+ expect(cleanup).toHaveBeenCalledTimes(cleanupCount);
+ expect(repair).toHaveBeenCalledTimes(cleanupCount);
+ expect(observeSandbox).toHaveBeenCalledTimes(legacy ? 2 : 0);
+ expect(release).toHaveBeenCalledOnce();
+ expect(fs.readFileSync(statePath, "utf8")).toBe("recorded state\n");
+ expect(events).toEqual([
+ "sandbox:acquired",
+ ...(legacy ? ["identity"] : []),
+ ...(cleanupCount === 1 ? ["cleanup"] : []),
+ "sandbox:released",
+ ]);
+ },
+ );
+ it.each([
+ { state: "missing", liveIdentityFingerprint: null },
+ { state: "not_ready", liveIdentityFingerprint: "f".repeat(64) },
+ { state: "ready", liveIdentityFingerprint: null },
+ ] as const)(
+ "stops before dispatch when legacy identity is unverified ($state)",
+ async (observation) => {
+ const entry = {
+ name: "alpha",
+ agent: "openclaw",
+ gatewayName: "nemoclaw-8081",
+ } as SandboxEntry;
+ const events: string[] = [];
+ const observeSandbox = vi.fn(() => observation);
+ await expect(
+ launchSandbox("alpha", {
+ getSandbox: () => entry,
+ inspectLaunchReadiness: async () => ({
+ kind: "accepted",
+ category: "accepted",
+ agent: loadAgent("openclaw"),
+ sb: entry,
+ }),
+ withSandboxMutationLock: createSerialTestLock(events, "sandbox"),
+ observeSandbox,
+ }),
+ ).rejects.toThrow(/Cannot verify the live identity.*sandbox doctor/u);
+ expect(observeSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sandboxName: "alpha",
+ gatewayName: "nemoclaw-8081",
+ gatewayPort: 8081,
+ }),
+ );
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
+ expect(events).toEqual(["sandbox:acquired", "sandbox:released"]);
+ },
+ );
+});
diff --git a/src/lib/actions/sandbox/launch.test.ts b/src/lib/actions/sandbox/launch.test.ts
index 3163e7aa3fe..30aca458062 100644
--- a/src/lib/actions/sandbox/launch.test.ts
+++ b/src/lib/actions/sandbox/launch.test.ts
@@ -14,7 +14,7 @@ const mocks = vi.hoisted(() => ({
printInteractiveSessionHints: vi.fn(),
completeInteractiveSessionSetup: vi.fn(),
completeReadinessQualifiedInteractiveSessionSetup: vi.fn(),
- execSandbox: vi.fn(),
+ startSandboxExec: vi.fn(),
startSandboxSession: vi.fn(),
createSessionExecutor: vi.fn(),
releaseSession: vi.fn(),
@@ -40,7 +40,7 @@ vi.mock("./connect", () => ({
mocks.completeReadinessQualifiedInteractiveSessionSetup,
}));
vi.mock("./exec", () => ({
- execSandbox: mocks.execSandbox,
+ startSandboxExec: mocks.startSandboxExec,
wrapExecCommandWithRuntimeEnv: (command: readonly string[]) => command,
}));
vi.mock("../../adapters/openshell/sandbox-command-cli", async (importOriginal) => ({
@@ -177,7 +177,7 @@ function prepareSession(
}
function launchedCommand(): readonly string[] {
- return mocks.execSandbox.mock.calls[0]?.[1] as readonly string[];
+ return mocks.startSandboxExec.mock.calls[0]?.[1] as readonly string[];
}
type AsyncTestLock = (name: string, operation: () => Promise | T) => Promise;
@@ -215,8 +215,9 @@ describe("launchSandbox", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.calls.length = 0;
- mocks.execSandbox.mockImplementation(async () => {
- mocks.calls.push("execSandbox");
+ mocks.startSandboxExec.mockImplementation(async () => {
+ mocks.calls.push("startSandboxExec");
+ return async () => undefined;
});
mocks.createSessionExecutor.mockReturnValue({ start: mocks.startSandboxSession });
mocks.startSandboxSession.mockImplementation(() => {
@@ -333,6 +334,7 @@ describe("launchSandbox", () => {
cancel: vi.fn(),
});
const exit = vi.spyOn(process, "exit").mockImplementation((code) => {
+ expect(mocks.releaseSession).toHaveBeenCalledOnce();
throw new Error(`exit:${code}`);
});
await expect(
@@ -346,7 +348,7 @@ describe("launchSandbox", () => {
expect(mocks.releaseSession).toHaveBeenCalledOnce();
});
- it("holds schema-5 authority through the exact interactive child execution (#9203)", async () => {
+ it("holds schema-5 authority through dispatch and releases it while the child runs (#11647)", async () => {
vi.stubEnv("NVIDIA_INFERENCE_API_KEY", "do-not-forward");
vi.stubEnv("GITHUB_TOKEN", "do-not-forward");
vi.stubEnv("AWS_SECRET_ACCESS_KEY", "do-not-forward");
@@ -379,13 +381,20 @@ describe("launchSandbox", () => {
});
await childStarted.promise;
const contender = withSandboxMutationLock("alpha", () => events.push("contender"));
- await Promise.resolve();
+ await new Promise((resolve) => setImmediate(resolve));
expect(mocks.recoverPortableLifecycle).toHaveBeenCalledOnce();
expect(mocks.recoverPortableLifecycle).toHaveBeenCalledWith("alpha", entry, "gateway-alpha");
expect(mocks.assertCommandCurrent).toHaveBeenCalledTimes(3);
- expect(events).toEqual(["sandbox:acquired", "sandbox:released", "sandbox:acquired", "child"]);
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(events).toEqual([
+ "sandbox:acquired",
+ "child",
+ "sandbox:released",
+ "sandbox:acquired",
+ "contender",
+ "sandbox:released",
+ ]);
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled();
expect(mocks.startSandboxSession).toHaveBeenCalledWith({
kind: "command",
@@ -411,8 +420,6 @@ describe("launchSandbox", () => {
await launch;
await contender;
expect(events).toEqual([
- "sandbox:acquired",
- "sandbox:released",
"sandbox:acquired",
"child",
"sandbox:released",
@@ -439,11 +446,11 @@ describe("launchSandbox", () => {
).rejects.toThrow("lifecycle authority changed");
expect(mocks.recoverPortableLifecycle).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
expect(mocks.startSandboxSession).not.toHaveBeenCalled();
});
- it("does not run accepted ordinary setup when schema-5 publishes before the launch fence (#9203)", async () => {
+ it("qualifies schema-5 published before the launch fence without ordinary setup (#9203)", async () => {
const hermes = loadAgent("hermes");
const entry = sandboxEntry("hermes");
mocks.inspectLaunchReadiness.mockResolvedValue({
@@ -463,12 +470,13 @@ describe("launchSandbox", () => {
return await operation();
},
}),
- ).rejects.toThrow("lifecycle authority changed");
+ ).resolves.toBeUndefined();
expect(mocks.printInteractiveSessionHints).not.toHaveBeenCalled();
expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
- expect(mocks.startSandboxSession).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
+ expect(mocks.startSandboxSession).toHaveBeenCalledOnce();
+ expect(mocks.requireActiveLifecycleAuthority).toHaveBeenCalled();
});
it("rejects schema-5 retirement inside the launch lifecycle fence (#9203)", async () => {
@@ -487,7 +495,7 @@ describe("launchSandbox", () => {
).rejects.toThrow("lifecycle authority changed");
expect(mocks.recoverPortableLifecycle).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("launches NemoCUA through the ordinary terminal-agent path (#9649)", async () => {
@@ -522,10 +530,10 @@ describe("launchSandbox", () => {
);
expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
- // Regression guard for #6291: execSandbox wraps every command in
+ // Regression guard for #6291: startSandboxExec wraps every command in
// wrapExecCommandWithRuntimeEnv, which unsets OPENCLAW_GATEWAY_TOKEN after
// sourcing the runtime env file. Only a login shell re-sources the file
// through the profile, so a bare argv would start the agent with different
@@ -550,14 +558,14 @@ describe("launchSandbox", () => {
expect(mocks.calls).toEqual([
"prepareInteractiveSession",
"prepareHermesLightTerminalSkin",
- "execSandbox",
+ "startSandboxExec",
]);
});
it("requests an interactive session with no timeout (#6006)", async () => {
await launchSandbox("alpha");
- expect(mocks.execSandbox.mock.calls[0]?.[2]).toEqual({
+ expect(mocks.startSandboxExec.mock.calls[0]?.[2]).toEqual({
tty: true,
stdin: true,
timeoutSeconds: 0,
@@ -568,7 +576,7 @@ describe("launchSandbox", () => {
await launchSandbox("beta-01");
expect(mocks.prepareInteractiveSession).toHaveBeenCalledWith("beta-01");
- expect(mocks.execSandbox.mock.calls[0]?.[0]).toBe("beta-01");
+ expect(mocks.startSandboxExec.mock.calls[0]?.[0]).toBe("beta-01");
});
// Without the preflight, the agent starts over exec while gateway process
@@ -579,7 +587,7 @@ describe("launchSandbox", () => {
expect(mocks.calls).toEqual([
"prepareInteractiveSession",
"prepareHermesLightTerminalSkin",
- "execSandbox",
+ "startSandboxExec",
]);
expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith(
expect.objectContaining({ epochId: null }),
@@ -604,7 +612,7 @@ describe("launchSandbox", () => {
expect(mocks.withLaunchReadinessMutationGate).not.toHaveBeenCalled();
expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("skips the complete OpenClaw pairing pass after current lease qualification (#9023)", async () => {
@@ -626,7 +634,7 @@ describe("launchSandbox", () => {
const launch = launchSandbox("alpha");
await vi.waitFor(() => expect(mocks.printInteractiveSessionHints).toHaveBeenCalledOnce());
expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
finishProbe();
await launch;
@@ -645,7 +653,7 @@ describe("launchSandbox", () => {
expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).toHaveBeenCalledBefore(
mocks.prepareHermesLightTerminalSkin,
);
- expect(mocks.prepareHermesLightTerminalSkin).toHaveBeenCalledBefore(mocks.execSandbox);
+ expect(mocks.prepareHermesLightTerminalSkin).toHaveBeenCalledBefore(mocks.startSandboxExec);
expect(launchedCommand()).toEqual(["bash", "-lc", "openclaw tui"]);
expect(mocks.emitPortableOpenClawAlreadyRunningTiming).toHaveBeenCalledOnce();
});
@@ -918,7 +926,7 @@ describe("launchSandbox", () => {
openclaw,
sb,
);
- expect(mocks.execSandbox).toHaveBeenCalledOnce();
+ expect(mocks.startSandboxExec).toHaveBeenCalledOnce();
});
it("keeps repeated launch and exit cycles on the accepted non-sliding lease (#8942)", async () => {
@@ -935,7 +943,7 @@ describe("launchSandbox", () => {
await launchSandbox("alpha");
expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled();
- expect(mocks.execSandbox).toHaveBeenCalledTimes(2);
+ expect(mocks.startSandboxExec).toHaveBeenCalledTimes(2);
expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
expect(mocks.completeReadinessQualifiedInteractiveSessionSetup).toHaveBeenCalledTimes(2);
expect(mocks.completeInteractiveSessionSetup).not.toHaveBeenCalled();
@@ -968,7 +976,7 @@ describe("launchSandbox", () => {
await launchSandbox("alpha");
expect(mocks.prepareInteractiveSession).toHaveBeenCalledBefore(mocks.publishLaunchReadiness);
- expect(mocks.publishLaunchReadiness).toHaveBeenCalledBefore(mocks.execSandbox);
+ expect(mocks.publishLaunchReadiness).toHaveBeenCalledBefore(mocks.startSandboxExec);
expect(mocks.publishLaunchReadiness).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
@@ -1066,7 +1074,7 @@ describe("launchSandbox", () => {
publicationRelease.resolve();
await rejection;
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
expect(mocks.startSandboxSession).not.toHaveBeenCalled();
});
@@ -1088,7 +1096,7 @@ describe("launchSandbox", () => {
expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce();
expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("keeps ordinary launch available when evidence observation, hashing, or storage fails (#8942)", async () => {
@@ -1106,31 +1114,56 @@ describe("launchSandbox", () => {
await expect(launchSandbox("alpha")).resolves.toBeUndefined();
expect(mocks.prepareInteractiveSession).toHaveBeenCalled();
- expect(mocks.execSandbox).toHaveBeenCalled();
+ expect(mocks.startSandboxExec).toHaveBeenCalled();
});
- it("runs the complete preflight and interactive command when macOS evidence is unavailable (#8942)", async () => {
- mocks.inspectLaunchReadiness.mockResolvedValue({
- kind: "fallback",
- category: "unsafe",
- fence: null,
- gatewayName: "nemoclaw",
- gatewayPort: 8080,
- fenceFailed: true,
- recoveryBlocked: false,
- authorityUnsupported: true,
- });
-
- await expect(launchSandbox("alpha")).resolves.toBeUndefined();
+ it.each([
+ ["current", {}],
+ ["missing generation", { lifecycleGeneration: undefined }],
+ ["missing live identity", { lifecycleLiveIdentityFingerprint: undefined }],
+ [
+ "missing both",
+ { lifecycleGeneration: undefined, lifecycleLiveIdentityFingerprint: undefined },
+ ],
+ ])(
+ "checks %s cleanup identity when macOS evidence is unavailable (#8942, #11647)",
+ async (_label, identity) => {
+ const agent = loadAgent("openclaw");
+ const entry = { ...sandboxEntry(agent.name), gatewayName: "nemoclaw-8081", ...identity };
+ const before = structuredClone(entry);
+ mocks.inspectLaunchReadiness.mockResolvedValue({
+ kind: "fallback",
+ category: "unsafe",
+ fence: null,
+ gatewayName: "nemoclaw",
+ gatewayPort: 8080,
+ fenceFailed: true,
+ recoveryBlocked: false,
+ authorityUnsupported: true,
+ });
+ mocks.prepareInteractiveSession.mockResolvedValue({
+ agent,
+ sb: entry,
+ hermesPortable: false,
+ });
- expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce();
- expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
- expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith(
- expect.objectContaining({ epochId: null }),
- expect.any(Function),
- );
- expect(mocks.execSandbox).toHaveBeenCalledOnce();
- });
+ await expect(
+ launchSandbox("alpha", {
+ getSandbox: () => entry,
+ observeSandbox: () => ({ state: "ready", liveIdentityFingerprint: "f".repeat(64) }),
+ }),
+ ).resolves.toBeUndefined();
+ expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce();
+ expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
+ expect(mocks.withLaunchReadinessMutationGate).toHaveBeenCalledWith(
+ expect.objectContaining({ epochId: null }),
+ expect.any(Function),
+ );
+ expect(mocks.startSandboxExec).toHaveBeenCalledOnce();
+ expect(mocks.startSandboxSession).not.toHaveBeenCalled();
+ expect(entry).toEqual(before);
+ },
+ );
it("stops before the complete preflight when a prior launch-readiness epoch may remain acceptable (#8942)", async () => {
mocks.inspectLaunchReadiness.mockResolvedValue({
@@ -1149,7 +1182,7 @@ describe("launchSandbox", () => {
expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled();
expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("stops before the complete preflight when the fenced epoch cannot be revalidated (#8942)", async () => {
@@ -1170,7 +1203,7 @@ describe("launchSandbox", () => {
expect(mocks.prepareInteractiveSession).not.toHaveBeenCalled();
expect(mocks.publishLaunchReadiness).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("does not launch after final semantic validation reports unhealthy state (#8942)", async () => {
@@ -1193,7 +1226,7 @@ describe("launchSandbox", () => {
);
expect(mocks.prepareInteractiveSession).toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
});
it("does not launch after final live-policy validation fails", async () => {
@@ -1225,7 +1258,7 @@ describe("launchSandbox", () => {
expect(mocks.prepareInteractiveSession).toHaveBeenCalledOnce();
expect(mocks.prepareHermesLightTerminalSkin).not.toHaveBeenCalled();
- expect(mocks.execSandbox).not.toHaveBeenCalled();
+ expect(mocks.startSandboxExec).not.toHaveBeenCalled();
expect(mocks.startSandboxSession).not.toHaveBeenCalled();
});
@@ -1240,4 +1273,128 @@ describe("launchSandbox", () => {
logSpy.mockRestore();
}
});
+ it("holds lifecycle authority from ordinary readiness through dispatch (#11647)", async () => {
+ const events: string[] = [];
+ const lock = createSerialTestLock(events, "sandbox");
+ const inspected = deferred();
+ const continueInspection = deferred();
+ const childStarted = deferred();
+ const sessionEnded = deferred();
+ mocks.inspectLaunchReadiness.mockImplementationOnce(async () => {
+ events.push("readiness");
+ inspected.resolve();
+ await continueInspection.promise;
+ return {
+ kind: "accepted",
+ category: "accepted",
+ agent: loadAgent("openclaw"),
+ sb: sandboxEntry("openclaw"),
+ };
+ });
+ mocks.startSandboxExec.mockImplementationOnce(async () => {
+ events.push("dispatch");
+ childStarted.resolve();
+ return () => sessionEnded.promise;
+ });
+ const launch = launchSandbox("alpha", { withSandboxMutationLock: lock });
+ await inspected.promise;
+ const contender = lock("alpha", () => {
+ events.push("contender");
+ });
+ continueInspection.resolve();
+ await childStarted.promise;
+ await contender;
+ sessionEnded.resolve();
+ await launch;
+ expect(
+ events.filter((event) => ["readiness", "dispatch", "contender"].includes(event)),
+ ).toEqual(["readiness", "dispatch", "contender"]);
+ });
+
+ it.each([
+ {
+ scenario: "hermes-accepted",
+ agentName: "hermes",
+ portable: true,
+ readiness: "accepted",
+ disposition: activeHermesDisposition(),
+ },
+ {
+ scenario: "hermes-prepared",
+ agentName: "hermes",
+ portable: true,
+ readiness: "fallback",
+ disposition: activeHermesDisposition(),
+ },
+ {
+ scenario: "openclaw-prepared",
+ agentName: "openclaw",
+ portable: false,
+ readiness: "fallback",
+ disposition: { kind: "absent" },
+ },
+ ])(
+ "permits another lifecycle operation while $scenario TUI remains open (#11647)",
+ async ({ agentName, portable, readiness, disposition }) => {
+ mocks.assertCommandCurrent.mockReset().mockImplementation(() => undefined);
+ const agent = loadAgent(agentName);
+ const entry = sandboxEntry(agent.name);
+ prepareSession(agent.name, agent, portable);
+ mocks.inspectPortableReceiptDisposition.mockReturnValue(disposition);
+ mocks.inspectLaunchReadiness.mockResolvedValue({
+ kind: readiness,
+ category: "missing",
+ fence: null,
+ gatewayName: "nemoclaw",
+ gatewayPort: 8080,
+ fenceFailed: true,
+ recoveryBlocked: false,
+ agent,
+ sb: entry,
+ });
+ const sessionEnded = deferred();
+ const childStarted = deferred();
+ mocks.startSandboxSession.mockImplementation(() => {
+ childStarted.resolve();
+ return {
+ completion: sessionEnded.promise.then(() => ({
+ outcome: { kind: "exited", exitCode: 0 },
+ stdout: "",
+ stderr: "",
+ release: mocks.releaseSession,
+ })),
+ cancel: vi.fn(),
+ };
+ });
+ mocks.startSandboxExec.mockImplementation(async () => {
+ childStarted.resolve();
+ return async () => {
+ await sessionEnded.promise;
+ };
+ });
+ const events: string[] = [];
+ const lock = createSerialTestLock(events, "sandbox");
+ const launch = launchSandbox("alpha", {
+ getSandbox: () => entry,
+ resolveSandboxGatewayName: () => "gateway-alpha",
+ withSandboxMutationLock: lock,
+ });
+ await Promise.race([
+ childStarted.promise,
+ launch.then(() => {
+ throw new Error("launch ended without starting a session");
+ }),
+ ]);
+ let anotherOperationEntered = false;
+ const anotherOperation = lock("alpha", () => {
+ anotherOperationEntered = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+ const enteredWhileSessionOpen = anotherOperationEntered;
+ sessionEnded.resolve();
+ await Promise.all([launch, anotherOperation]);
+ expect(anotherOperationEntered).toBe(true);
+ expect(enteredWhileSessionOpen).toBe(true);
+ },
+ );
});
diff --git a/src/lib/actions/sandbox/launch.ts b/src/lib/actions/sandbox/launch.ts
index 3bde0a4fd3a..e05d566f2f5 100644
--- a/src/lib/actions/sandbox/launch.ts
+++ b/src/lib/actions/sandbox/launch.ts
@@ -13,14 +13,19 @@ import {
} from "../../adapters/openshell/sandbox-command-cli";
import { resolveSandboxGatewayName } from "../../gateway-runtime-action";
import { emitPortableOpenClawAlreadyRunningTiming } from "../../onboard/experimental/portable-demo-lifecycle-timing";
+import {
+ observeSandboxOnGateway,
+ type SandboxRecreateObserver,
+} from "../../onboard/sandbox-recreate-probe";
import type { SandboxEntry } from "../../state/registry";
+import { enforceRemovedImmutabilityMigrationBoundary } from "../../state/migrations/removed-immutability";
import {
completeReadinessQualifiedInteractiveSessionSetup,
prepareInteractiveSession,
printInteractiveSessionHints,
} from "./connect";
import { prepareHermesLightTerminalSkin } from "./connect-hermes-light-skin";
-import { execSandbox, wrapExecCommandWithRuntimeEnv } from "./exec";
+import { startSandboxExec, wrapExecCommandWithRuntimeEnv } from "./exec";
import {
inspectPortableAgentReceiptDisposition,
captureHermesPortableAcceptedReadinessObservation,
@@ -33,7 +38,7 @@ import {
type HermesPortableActiveLifecycleAuthority,
withSandboxLifecycleLock as withSandboxMutationLock,
} from "./gateway-state";
-import { getKnownSandboxTarget } from "./gateway-target";
+import { getKnownSandboxTarget, getPersistedSandboxTargetGateway } from "./gateway-target";
import {
createBoundLaunchReadinessDeps,
inspectLaunchReadiness,
@@ -58,6 +63,7 @@ const sandboxCommandExecutor = createCliOpenShellSandboxCommandExecutor({
*/
interface LaunchSandboxDeps {
getSandbox?: typeof getKnownSandboxTarget;
+ observeSandbox?: SandboxRecreateObserver;
resolveSandboxGatewayName?: typeof resolveSandboxGatewayName;
withSandboxMutationLock?: typeof withSandboxMutationLock;
inspectLaunchReadiness?: typeof inspectLaunchReadiness;
@@ -180,62 +186,51 @@ async function inspectLaunchReadinessForLaunch(
throw new Error("Hermes portable registry authority changed before launch readiness.");
}
- const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock;
- return lockSandbox(sandboxName, async () => {
- const lifecycleDeps = { readRegistry: readSandbox };
- let active = requireHermesPortableActiveLifecycleAuthority(
- sandboxName,
- undefined,
- lifecycleDeps,
- );
- let qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName);
- if (qualified.kind === "requalification-required") {
- const requalified = requalifyPortableAgentSandboxAuthority(sandboxName, lifecycleDeps);
- if (requalified.kind === "not-installed" || requalified.kind === "not-hermes") {
- throw new Error("Hermes portable lifecycle authority changed before launch readiness.");
- }
- active = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps);
- qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName, {
- priorReceiptAuthority: requalified,
- });
- if (qualified.kind === "requalification-required") {
- throw new Error("Hermes portable schema-6 authority was not published before launch.");
- }
+ const lifecycleDeps = { readRegistry: readSandbox };
+ let active = requireHermesPortableActiveLifecycleAuthority(sandboxName, undefined, lifecycleDeps);
+ let qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName);
+ if (qualified.kind === "requalification-required") {
+ const requalified = requalifyPortableAgentSandboxAuthority(sandboxName, lifecycleDeps);
+ if (requalified.kind === "not-installed" || requalified.kind === "not-hermes") {
+ throw new Error("Hermes portable lifecycle authority changed before launch readiness.");
}
- const command = qualified.commandAuthority;
- const capture = (args: string[], options = {}) =>
- captureHermesPortableAcceptedReadinessObservation(command, args, options);
- const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor(
- {
- resolveBinary: () => command.executablePath,
- hostCwd: REPOSITORY_ROOT,
- hostEnv: command.env,
- },
- command.assertCurrent,
- );
- command.assertCurrent();
- const decision = await inspect(sandboxName, {
- ...createBoundLaunchReadinessDeps(capture, commandExecutor),
- getSandbox: readSandbox,
- withSandboxLock: async (_name, operation) => operation(),
+ active = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps);
+ qualified = qualifyHermesPortableAcceptedReadinessAuthority(sandboxName, {
+ priorReceiptAuthority: requalified,
});
- command.assertCurrent();
- const current = requireHermesPortableActiveLifecycleAuthority(
- sandboxName,
- active,
- lifecycleDeps,
- );
- if (decision.kind === "accepted" && !isDeepStrictEqual(decision.sb, current.entry)) {
- throw new Error("Hermes portable registry authority changed during launch readiness.");
+ if (qualified.kind === "requalification-required") {
+ throw new Error("Hermes portable schema-6 authority was not published before launch.");
}
- return {
- decision,
- hermesAuthority: { active: current, command },
- };
+ }
+ const command = qualified.commandAuthority;
+ const capture = (args: string[], options = {}) =>
+ captureHermesPortableAcceptedReadinessObservation(command, args, options);
+ const commandExecutor = createCurrentnessBoundCliOpenShellSandboxBufferedCommandExecutor(
+ {
+ resolveBinary: () => command.executablePath,
+ hostCwd: REPOSITORY_ROOT,
+ hostEnv: command.env,
+ },
+ command.assertCurrent,
+ );
+ command.assertCurrent();
+ const decision = await inspect(sandboxName, {
+ ...createBoundLaunchReadinessDeps(capture, commandExecutor),
+ getSandbox: readSandbox,
+ withSandboxLock: async (_name, operation) => operation(),
});
+ command.assertCurrent();
+ const current = requireHermesPortableActiveLifecycleAuthority(sandboxName, active, lifecycleDeps);
+ if (decision.kind === "accepted" && !isDeepStrictEqual(decision.sb, current.entry)) {
+ throw new Error("Hermes portable registry authority changed during launch readiness.");
+ }
+ return {
+ decision,
+ hermesAuthority: { active: current, command },
+ };
}
-async function launchAgentWithPortableAuthority(
+async function startAgentWithPortableAuthority(
sandboxName: string,
agent: AgentDefinition | null,
entry: SandboxEntry | null,
@@ -245,20 +240,64 @@ async function launchAgentWithPortableAuthority(
acceptedHermesAuthority: HermesPortableLaunchAuthority | null,
beforeOrdinaryLaunch?: () => Promise,
beforeAgentExec?: () => void,
-): Promise {
- const runOrdinaryAgent = async (): Promise => {
+): Promise<{ finish: () => Promise }> {
+ const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock;
+ const startOrdinaryAgent = async (): Promise<{ finish: () => Promise }> => {
+ const readSandbox = deps.getSandbox ?? getKnownSandboxTarget;
+ const launchedEntry = structuredClone(readSandbox(sandboxName));
+ const legacyTarget =
+ launchedEntry &&
+ (launchedEntry.agent ?? "openclaw") === "openclaw" &&
+ (!launchedEntry.lifecycleGeneration || !launchedEntry.lifecycleLiveIdentityFingerprint)
+ ? { sandboxName, ...getPersistedSandboxTargetGateway(launchedEntry) }
+ : null;
+ const observeSandbox = deps.observeSandbox ?? observeSandboxOnGateway;
+ // Older registrations have no recorded identity. Bind cleanup to the live ID
+ // without changing their registration or requiring a sandbox replacement.
+ const launchedLive = legacyTarget ? observeSandbox(legacyTarget) : null;
+ if (launchedLive && (launchedLive.state !== "ready" || !launchedLive.liveIdentityFingerprint)) {
+ throw new Error(
+ `Cannot verify the live identity of sandbox '${sandboxName}' before launch. Run the sandbox doctor and retry.`,
+ );
+ }
prepareHermesLightTerminalSkin(sandboxName, agent, process.env);
beforeAgentExec?.();
- await execSandbox(sandboxName, command, {
- tty: true,
- stdin: true,
- timeoutSeconds: 0,
- });
+ const finish = await startSandboxExec(
+ sandboxName,
+ command,
+ { tty: true, stdin: true, timeoutSeconds: 0 },
+ {
+ withCleanupAuthority: (cleanup) =>
+ lockSandbox(sandboxName, () => {
+ enforceRemovedImmutabilityMigrationBoundary(sandboxName);
+ const current = readSandbox(sandboxName);
+ if (
+ !launchedEntry ||
+ !current ||
+ current.agent !== launchedEntry.agent ||
+ current.gatewayName !== launchedEntry.gatewayName ||
+ current.gatewayPort !== launchedEntry.gatewayPort ||
+ current.lifecycleGeneration !== launchedEntry.lifecycleGeneration ||
+ current.lifecycleLiveIdentityFingerprint !==
+ launchedEntry.lifecycleLiveIdentityFingerprint
+ )
+ return null;
+ if (
+ legacyTarget &&
+ observeSandbox(legacyTarget).liveIdentityFingerprint !==
+ launchedLive?.liveIdentityFingerprint
+ )
+ return null;
+ return cleanup();
+ }),
+ },
+ );
+ return { finish };
};
- const runHermesPortableAgent = async (
+ const startHermesPortableAgent = (
gatewayName: string,
commandAuthority: HermesPortableReadinessCommandAuthority,
- ): Promise => {
+ ): { finish: () => Promise } => {
commandAuthority.assertCurrent();
beforeAgentExec?.();
const session = createCliOpenShellSandboxSessionExecutor({
@@ -273,94 +312,104 @@ async function launchAgentWithPortableAuthority(
output: "inherit",
timeoutSeconds: 0,
});
- const result = await session.completion;
- try {
- if (result.outcome.kind === "failed" && result.outcome.reason !== "transport") {
- throw new Error(result.outcome.message);
- }
- if (result.outcome.exitCode !== 0) process.exit(result.outcome.exitCode);
- } finally {
- result.release();
- }
+ return {
+ finish: async () => {
+ const result = await session.completion;
+ try {
+ if (result.outcome.kind === "failed" && result.outcome.reason !== "transport") {
+ throw new Error(result.outcome.message);
+ }
+ } finally {
+ result.release();
+ }
+ if (result.outcome.exitCode !== 0) process.exit(result.outcome.exitCode);
+ },
+ };
};
- const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock;
- await lockSandbox(sandboxName, async () => {
- const current = inspectPortableAgentReceiptDisposition(sandboxName);
- if ((current.kind === "hermes") !== hermesPortableSnapshot) {
- throw new Error("Hermes portable lifecycle authority changed before agent launch.");
- }
- if (current.kind !== "hermes") {
- await beforeOrdinaryLaunch?.();
- await runOrdinaryAgent();
- return;
- }
- if (current.phase !== "active") {
- throw new Error("Hermes portable lifecycle authority changed before agent launch.");
- }
- const readSandbox = deps.getSandbox ?? getKnownSandboxTarget;
- const registered = readSandbox(sandboxName);
- if (
- agent?.name !== "hermes" ||
- entry?.agent !== "hermes" ||
- !registered ||
- registered.agent !== "hermes" ||
- registered.gatewayName !== entry.gatewayName ||
- registered.lifecycleGeneration !== entry.lifecycleGeneration ||
- current.gatewayName !== entry.gatewayName ||
- current.lifecycleGeneration !== entry.lifecycleGeneration
- ) {
+ const current = inspectPortableAgentReceiptDisposition(sandboxName);
+ if ((current.kind === "hermes") !== hermesPortableSnapshot) {
+ throw new Error("Hermes portable lifecycle authority changed before agent launch.");
+ }
+ if (current.kind !== "hermes") {
+ await beforeOrdinaryLaunch?.();
+ return await startOrdinaryAgent();
+ }
+ if (current.phase !== "active") {
+ throw new Error("Hermes portable lifecycle authority changed before agent launch.");
+ }
+ const readSandbox = deps.getSandbox ?? getKnownSandboxTarget;
+ const registered = readSandbox(sandboxName);
+ if (
+ agent?.name !== "hermes" ||
+ entry?.agent !== "hermes" ||
+ !registered ||
+ registered.agent !== "hermes" ||
+ registered.gatewayName !== entry.gatewayName ||
+ registered.lifecycleGeneration !== entry.lifecycleGeneration ||
+ current.gatewayName !== entry.gatewayName ||
+ current.lifecycleGeneration !== entry.lifecycleGeneration
+ ) {
+ throw new Error("Hermes portable registry authority changed before agent launch.");
+ }
+ const gatewayName = (deps.resolveSandboxGatewayName ?? resolveSandboxGatewayName)(registered);
+ if (acceptedHermesAuthority) {
+ requireHermesPortableActiveLifecycleAuthority(sandboxName, acceptedHermesAuthority.active, {
+ readRegistry: readSandbox,
+ });
+ if (!isDeepStrictEqual(registered, acceptedHermesAuthority.active.entry)) {
throw new Error("Hermes portable registry authority changed before agent launch.");
}
- const gatewayName = (deps.resolveSandboxGatewayName ?? resolveSandboxGatewayName)(registered);
- if (acceptedHermesAuthority) {
- requireHermesPortableActiveLifecycleAuthority(sandboxName, acceptedHermesAuthority.active, {
- readRegistry: readSandbox,
- });
- if (!isDeepStrictEqual(registered, acceptedHermesAuthority.active.entry)) {
- throw new Error("Hermes portable registry authority changed before agent launch.");
- }
- acceptedHermesAuthority.command.assertCurrent();
- await runHermesPortableAgent(gatewayName, acceptedHermesAuthority.command);
- return;
- }
- const recovery = recoverPortableDemoSandboxLifecycleForConnect(
- sandboxName,
- registered,
- gatewayName,
- );
- if (recovery.kind === "not-installed") {
- throw new Error("Hermes portable lifecycle authority disappeared before agent launch.");
- }
- const finalReceipt = inspectPortableAgentReceiptDisposition(sandboxName);
- const finalRegistered = readSandbox(sandboxName);
- if (
- finalReceipt.kind !== "hermes" ||
- finalReceipt.phase !== "active" ||
- !finalRegistered ||
- finalRegistered.agent !== "hermes" ||
- finalRegistered.gatewayName !== registered.gatewayName ||
- finalRegistered.lifecycleGeneration !== registered.lifecycleGeneration ||
- finalRegistered.lifecycleLiveIdentityFingerprint !==
- registered.lifecycleLiveIdentityFingerprint ||
- finalRegistered.openshellDriver !== registered.openshellDriver ||
- finalRegistered.openshellVersion !== registered.openshellVersion ||
- finalReceipt.gatewayName !== registered.gatewayName ||
- finalReceipt.lifecycleGeneration !== registered.lifecycleGeneration ||
- finalReceipt.liveIdentityFingerprint !== registered.lifecycleLiveIdentityFingerprint
- ) {
- throw new Error("Hermes portable lifecycle authority changed at agent launch.");
- }
- await runHermesPortableAgent(
- gatewayName,
- qualifyHermesPortableOperatingCommandAuthority(sandboxName),
- );
- });
+ acceptedHermesAuthority.command.assertCurrent();
+ return startHermesPortableAgent(gatewayName, acceptedHermesAuthority.command);
+ }
+ const recovery = recoverPortableDemoSandboxLifecycleForConnect(
+ sandboxName,
+ registered,
+ gatewayName,
+ );
+ if (recovery.kind === "not-installed") {
+ throw new Error("Hermes portable lifecycle authority disappeared before agent launch.");
+ }
+ const finalReceipt = inspectPortableAgentReceiptDisposition(sandboxName);
+ const finalRegistered = readSandbox(sandboxName);
+ if (
+ finalReceipt.kind !== "hermes" ||
+ finalReceipt.phase !== "active" ||
+ !finalRegistered ||
+ finalRegistered.agent !== "hermes" ||
+ finalRegistered.gatewayName !== registered.gatewayName ||
+ finalRegistered.lifecycleGeneration !== registered.lifecycleGeneration ||
+ finalRegistered.lifecycleLiveIdentityFingerprint !==
+ registered.lifecycleLiveIdentityFingerprint ||
+ finalRegistered.openshellDriver !== registered.openshellDriver ||
+ finalRegistered.openshellVersion !== registered.openshellVersion ||
+ finalReceipt.gatewayName !== registered.gatewayName ||
+ finalReceipt.lifecycleGeneration !== registered.lifecycleGeneration ||
+ finalReceipt.liveIdentityFingerprint !== registered.lifecycleLiveIdentityFingerprint
+ ) {
+ throw new Error("Hermes portable lifecycle authority changed at agent launch.");
+ }
+ return startHermesPortableAgent(
+ gatewayName,
+ qualifyHermesPortableOperatingCommandAuthority(sandboxName),
+ );
}
export async function launchSandbox(
sandboxName: string,
deps: LaunchSandboxDeps = {},
): Promise {
+ const lockSandbox = deps.withSandboxMutationLock ?? withSandboxMutationLock;
+ const started = await lockSandbox(sandboxName, () => prepareLaunchSession(sandboxName, deps));
+ // Completion runs outside the lock's async context; cleanup acquires fresh authority.
+ await started.finish();
+}
+
+async function prepareLaunchSession(
+ sandboxName: string,
+ deps: LaunchSandboxDeps,
+): Promise<{ finish: () => Promise }> {
+ enforceRemovedImmutabilityMigrationBoundary(sandboxName);
const launchTiming = createLaunchPreExecTiming(deps);
const enterMutationGate = deps.withLaunchReadinessMutationGate ?? withLaunchReadinessMutationGate;
let inspection = await inspectLaunchReadinessForLaunch(sandboxName, deps);
@@ -462,7 +511,7 @@ export async function launchSandbox(
// part of prepareInteractiveSession, so `launch` must call it too: without it
// a Hermes TUI on a light-background terminal keeps the default dark skin,
// and a switch back to a dark terminal never removes the managed skin.
- // Run the agent through a login shell. execSandbox wraps every command in
+ // Run the agent through a login shell. startSandboxExec wraps every command in
// wrapExecCommandWithRuntimeEnv (runtime-env.ts), which sources
// /tmp/nemoclaw-proxy-env.sh and then unsets OPENCLAW_GATEWAY_TOKEN so
// ordinary caller argv cannot inherit it (#6291). The SSH path that
@@ -471,7 +520,7 @@ export async function launchSandbox(
// agent under a different auth mode than `connect` gives it, so `-l` is
// load-bearing: do not flatten this to `bash -c` or to the split command.
const command = ["bash", "-lc", agentCommand];
- await launchAgentWithPortableAuthority(
+ return startAgentWithPortableAuthority(
sandboxName,
agent,
sb,
diff --git a/src/lib/cli/nemoclaw-oclif-command.test.ts b/src/lib/cli/nemoclaw-oclif-command.test.ts
index a98400f2121..d7d5049009f 100644
--- a/src/lib/cli/nemoclaw-oclif-command.test.ts
+++ b/src/lib/cli/nemoclaw-oclif-command.test.ts
@@ -7,6 +7,7 @@ import path from "node:path";
import { Args, Flags } from "@oclif/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { launchSandbox } from "../actions/sandbox/launch";
import * as portableAgentLifecycle from "../onboard/experimental/portable-agent-lifecycle";
import * as receiptAuthority from "../onboard/experimental/hermes-portable-receipt";
import * as portableHostAuthority from "../state/portable-uninstall-retirement";
@@ -163,10 +164,12 @@ class PortableLaunchCommand extends NemoClawCommand {
static args = { sandboxName: Args.string({ required: true }) };
static flags = {};
static observed = { host: false, lifecycle: false, portableLifecycle: false };
+ static operation: (sandboxName: string) => Promise = async () => undefined;
public async run(): Promise {
const { args } = await this.parse(PortableLaunchCommand);
PortableLaunchCommand.observed = observeLifecycleAuthority(args.sandboxName!);
+ await PortableLaunchCommand.operation(args.sandboxName!);
}
}
@@ -242,6 +245,7 @@ describe("NemoClawCommand", () => {
ProbeOnlyConnectCommand.operation = () => undefined;
PortableStartCommand.observed = { host: false, lifecycle: false, portableLifecycle: false };
PortableLaunchCommand.observed = { host: false, lifecycle: false, portableLifecycle: false };
+ PortableLaunchCommand.operation = async () => undefined;
PortableStopCommand.observed = { host: false, lifecycle: false, portableLifecycle: false };
});
@@ -393,7 +397,7 @@ describe("NemoClawCommand", () => {
});
});
- it("uses the same Portable host and lifecycle fences for launch and stop", async () => {
+ it("leaves interactive launch locking to the action while fencing stop (#11647)", async () => {
vi.stubEnv("NEMOCLAW_GATEWAY_PORT", "18080");
useHermesPortableAuthority();
@@ -401,13 +405,78 @@ describe("NemoClawCommand", () => {
await PortableStopCommand.run(["alpha"], process.cwd());
expect(PortableLaunchCommand.observed).toEqual({
+ host: false,
+ lifecycle: false,
+ portableLifecycle: false,
+ });
+ expect(PortableStopCommand.observed).toEqual({
host: true,
lifecycle: false,
portableLifecycle: true,
});
- expect(PortableStopCommand.observed).toEqual(PortableLaunchCommand.observed);
});
+ it.each([
+ { record: "shields-alpha.json", error: /mutable posture cannot be proven/u },
+ { record: "shields-timer-alpha.json", error: /recovery artifacts from the removed Shields/u },
+ ])(
+ "rejects launch when $record appears while its action waits for authority (#11647)",
+ async ({ record, error }) => {
+ let acquired!: () => void;
+ const mutationStarted = new Promise((resolve) => {
+ acquired = resolve;
+ });
+ let waiting!: () => void;
+ const launchWaiting = new Promise((resolve) => {
+ waiting = resolve;
+ });
+ let update!: () => void;
+ const publishRecord = new Promise((resolve) => {
+ update = resolve;
+ });
+ const inspect = vi.fn(async () => {
+ throw new Error("readiness reached before migration rejection");
+ });
+ PortableLaunchCommand.operation = (sandboxName) =>
+ launchSandbox(sandboxName, {
+ inspectLaunchReadiness: inspect,
+ withSandboxMutationLock: (name, operation) => {
+ waiting();
+ return withMcpLifecycleLock(name, operation, { stateDir });
+ },
+ });
+ const recordPath = path.join(stateDir, record);
+ const mutation = withMcpLifecycleLock(
+ "alpha",
+ async () => {
+ acquired();
+ await publishRecord;
+ fs.writeFileSync(recordPath, "legacy state\n");
+ },
+ { stateDir },
+ );
+ try {
+ await mutationStarted;
+ const launch = PortableLaunchCommand.run(["alpha"], process.cwd());
+ const rejected = expect(launch).rejects.toThrow(error);
+ await launchWaiting;
+ update();
+ await Promise.all([mutation, rejected]);
+ expect(inspect).not.toHaveBeenCalled();
+ expect(fs.readFileSync(recordPath, "utf8")).toBe("legacy state\n");
+ const reacquired = await withMcpLifecycleLock(
+ "alpha",
+ () => isMcpLifecycleLockHeld("alpha", stateDir),
+ { stateDir, timeoutMs: 1000 },
+ );
+ expect(reacquired).toBe(true);
+ } finally {
+ update();
+ await mutation;
+ }
+ },
+ );
+
it("selects the gateway lifecycle lock under the host fence when there is no Hermes receipt", async () => {
vi.stubEnv("HOME", stateDir);
vi.stubEnv("NEMOCLAW_TEST_BASE_HOME", stateDir);
diff --git a/src/lib/cli/nemoclaw-oclif-command.ts b/src/lib/cli/nemoclaw-oclif-command.ts
index 3915d289319..cc3345951f1 100644
--- a/src/lib/cli/nemoclaw-oclif-command.ts
+++ b/src/lib/cli/nemoclaw-oclif-command.ts
@@ -129,7 +129,7 @@ export abstract class NemoClawCommand extends Command {
enforceRemovedImmutabilityMigrationBoundary(sandboxName, {
allowStateRecord: allowRemovedImmutabilityStateRecord,
});
- if (this.isInteractiveConnect(commandId)) {
+ if (this.isInteractiveSession(commandId)) {
return await super._run();
}
const runLocked = () => {
@@ -144,9 +144,10 @@ export abstract class NemoClawCommand extends Command {
return await withSandboxLifecycleLock(sandboxName, runLocked);
}
- private isInteractiveConnect(commandId: string | undefined): boolean {
+ private isInteractiveSession(commandId: string | undefined): boolean {
return (
- commandId === "sandbox:connect" && this.lifecycleParserOutput?.flags["probe-only"] !== true
+ commandId === "launch" ||
+ (commandId === "sandbox:connect" && this.lifecycleParserOutput?.flags["probe-only"] !== true)
);
}