Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions scripts/checks/legacy-sandbox-transports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ type ReviewedSiteTuple = readonly [string, LegacySandboxTransportKind, number];

const REVIEWED_SITE_TUPLES = [
["src/lib/actions/sandbox/sessions/passthrough.ts", "grpc-cli-read-only-fallback", 1],
["src/lib/actions/sandbox/process-recovery.ts", "grpc-cli-read-only-fallback", 1],
["src/lib/actions/sandbox/process-recovery.ts", "privileged-sandbox-exec", 2],
["src/lib/actions/sandbox/snapshot.ts", "grpc-cli-read-only-fallback", 1],
["src/lib/diagnostics/debug.ts", "grpc-cli-read-only-fallback", 1],
["src/lib/sandbox/config.ts", "privileged-sandbox-exec", 2],
["src/lib/sandbox/version.ts", "grpc-cli-read-only-fallback", 1],
Expand Down
47 changes: 47 additions & 0 deletions src/lib/actions/sandbox/process-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,20 @@

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

const readOnlyExecMock = vi.hoisted(() => vi.fn());

vi.mock("../../adapters/openshell/sandbox-control-routing", async (importOriginal) => ({
...(await importOriginal<typeof import("../../adapters/openshell/sandbox-control-routing")>()),
execSandboxReadOnlyWithGrpcFallback: readOnlyExecMock,
}));

import * as agentRuntime from "../../agent/runtime";
import * as registry from "../../state/registry";

// Import source directly so this test cannot pass against a stale build.
import {
confirmRecoveredSandboxGatewayManaged,
isSandboxGatewayRunningForStatus,
waitForRecoveredSandboxGateway,
waitForRecreatedSandboxOpenShellReady,
} from "./process-recovery";
Expand All @@ -14,6 +25,42 @@ const OPENSHELL_SANDBOX_NOT_READY_STDERR = `Error: × code: 'The system is not
│ execution', message: "sandbox is not ready"
`;

describe("read-only sandbox gateway status probe", () => {
afterEach(() => {
vi.restoreAllMocks();
readOnlyExecMock.mockReset();
});

it("routes through direct gRPC on the sandbox's registered gateway", async () => {
vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null);
vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", gatewayPort: 9090 });
readOnlyExecMock.mockResolvedValue({ status: 0, stdout: "RUNNING\n", stderr: "" });

await expect(isSandboxGatewayRunningForStatus("alpha")).resolves.toBe(true);
expect(readOnlyExecMock).toHaveBeenCalledWith("nemoclaw-9090", {
sandboxName: "alpha",
command: ["sh", "-c", expect.stringContaining("HTTP_CODE=")],
timeoutMs: 15_000,
});
});

it("reports a stopped gateway from a successful read-only probe", async () => {
vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null);
vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", gatewayPort: 9090 });
readOnlyExecMock.mockResolvedValue({ status: 0, stdout: "STOPPED\n", stderr: "" });

await expect(isSandboxGatewayRunningForStatus("alpha")).resolves.toBe(false);
});

it("keeps gateway status indeterminate when the read-only route rejects", async () => {
vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue(null);
vi.spyOn(registry, "getSandbox").mockReturnValue({ name: "alpha", gatewayPort: 9090 });
readOnlyExecMock.mockRejectedValue(new Error("read-only route unavailable"));

await expect(isSandboxGatewayRunningForStatus("alpha")).resolves.toBeNull();
});
});

describe("recreated sandbox OpenShell readiness", () => {
it("retries only the structured not-ready state until OpenShell accepts the sandbox", () => {
const notReady = {
Expand Down
32 changes: 17 additions & 15 deletions src/lib/actions/sandbox/process-recovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ import { dockerSpawnSync } from "../../adapters/docker";
import { stripAnsi } from "../../adapters/openshell/client";
import {
captureOpenshell,
captureOpenshellForStatus,
getOpenshellBinary,
isCommandTimeout,
getStatusProbeTimeoutMs,
} from "../../adapters/openshell/runtime";
import { execSandboxReadOnlyWithGrpcFallback } from "../../adapters/openshell/sandbox-control-routing";
import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts";
import * as agentRuntime from "../../agent/runtime";
import { G, R } from "../../cli/terminal-style";
import { sleepSeconds, waitUntil } from "../../core/wait";
import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard";
import { resolveSandboxGatewayName } from "../../onboard/gateway-binding";
import { ROOT, shellQuote } from "../../runner";
import {
isDirectSandboxFallbackUnavailableError,
Expand Down Expand Up @@ -259,19 +260,20 @@ async function executeSandboxExecCommandForStatus(
sandboxName: string,
command: string,
): Promise<SandboxCommandResult | null> {
const markedCommand = buildSandboxExecMarkedCommand(command);
const result = await captureOpenshellForStatus(
["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", markedCommand],
{ ignoreError: true },
);
if (isCommandTimeout(result) || result.error) return null;
const commandStdout = extractSandboxExecCommandStdout(result.output || "");
if (commandStdout === null) return null;
return {
status: result.status ?? 1,
stdout: commandStdout,
stderr: "",
};
try {
const result = await execSandboxReadOnlyWithGrpcFallback(
resolveSandboxGatewayName(registry.getSandbox(sandboxName)),
{
sandboxName,
command: ["sh", "-c", command],
timeoutMs: getStatusProbeTimeoutMs(),
},
);
if (result.error || result.signal || result.status === null) return null;
return { status: result.status, stdout: result.stdout.trim(), stderr: result.stderr.trim() };
} catch {
return null;
}
}

function parseSandboxGatewayProbe(result: SandboxCommandResult | null): boolean | null {
Expand Down
5 changes: 0 additions & 5 deletions src/lib/actions/sandbox/snapshot-restore-clone-ports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ describe("runSandboxSnapshot restore: new Kubernetes destination", () => {
);
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("idle") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down Expand Up @@ -114,7 +113,6 @@ describe("runSandboxSnapshot restore: clone dashboard port identity", () => {
);
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("idle") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down Expand Up @@ -171,7 +169,6 @@ describe("runSandboxSnapshot restore: clone dashboard port identity", () => {
);
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down Expand Up @@ -237,7 +234,6 @@ describe("runSandboxSnapshot restore: clone dashboard port identity", () => {
f.parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"]));
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down Expand Up @@ -274,7 +270,6 @@ describe("runSandboxSnapshot restore: clone dashboard port identity", () => {
);
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("idle") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down
2 changes: 0 additions & 2 deletions src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,6 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => {
f.parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"]));
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down Expand Up @@ -319,7 +318,6 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => {
f.parseLiveSandboxNamesMock.mockReturnValue(new Set(["alpha", "beta"]));
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("no-runtime") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ describe("runSandboxSnapshot restore: observability policy replay", () => {
);
f.captureOpenshellMock.mockImplementation((args) =>
f.openshellResponses(args, {
"sandbox exec": { status: 0, output: f.dcodeProbeOutput("idle") },
"sandbox list": { status: 0, output: "alpha Ready\nbeta Ready\n" },
}),
);
Expand Down
24 changes: 3 additions & 21 deletions src/lib/actions/sandbox/snapshot-restore-test-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0

import { vi } from "vitest";
import { SANDBOX_EXEC_STARTED_MARKER } from "./sandbox-exec-output";
import type { SnapshotStreamSandboxCreateMock } from "./snapshot-create-stream-test-types";

export type OpenshellCaptureResult = {
Expand All @@ -29,24 +28,6 @@ export type SandboxRecord = {
hermesDashboardInternalPort?: number | null;
hermesDashboardTui?: boolean;
};
export type DcodeProbeState = "active" | "idle" | "unverifiable" | "no-runtime";

export function dcodeProbeOutput(state: DcodeProbeState, extra = ""): string {
return `${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=${state}\n${extra}`;
}

export function captureOpenshellStreams(
args: string[],
result: OpenshellCaptureResult,
): OpenshellCaptureResult {
const command = String(args.at(-1) ?? "");
const marker = command.match(/printf '%s\\n' '([^']+)'/)?.[1] ?? SANDBOX_EXEC_STARTED_MARKER;
const replaceMarker = (value: string) => value.replaceAll(SANDBOX_EXEC_STARTED_MARKER, marker);
const stdout = replaceMarker(result.stdout ?? result.output);
const stderr = replaceMarker(result.stderr ?? "");
return { ...result, output: stdout, stdout, stderr };
}

export function openshellResponses(
args: string[],
responses: Record<string, OpenshellCaptureResult>,
Expand All @@ -55,12 +36,13 @@ export function openshellResponses(
status: 0,
output: "",
};
return captureOpenshellStreams(args, result);
const stdout = result.stdout ?? result.output;
const stderr = result.stderr ?? "";
return { ...result, output: stdout, stdout, stderr };
}

export function defaultOpenshellResponses(args: string[]): OpenshellCaptureResult {
return openshellResponses(args, {
"sandbox exec": { status: 0, output: dcodeProbeOutput("no-runtime") },
"sandbox list": {
status: 0,
output: "alpha Ready\n",
Expand Down
Loading