diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index d69779ff3be..094b3bd6a6c 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -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], diff --git a/src/lib/actions/sandbox/process-recovery.test.ts b/src/lib/actions/sandbox/process-recovery.test.ts index 96bba814c93..c4673f64339 100644 --- a/src/lib/actions/sandbox/process-recovery.test.ts +++ b/src/lib/actions/sandbox/process-recovery.test.ts @@ -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()), + 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"; @@ -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 = { diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index c4f401934d2..0bfad1d2bd7 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -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, @@ -259,19 +260,20 @@ async function executeSandboxExecCommandForStatus( sandboxName: string, command: string, ): Promise { - 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 { diff --git a/src/lib/actions/sandbox/snapshot-restore-clone-ports.test.ts b/src/lib/actions/sandbox/snapshot-restore-clone-ports.test.ts index 3a322cda56f..f1da19296d2 100644 --- a/src/lib/actions/sandbox/snapshot-restore-clone-ports.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-clone-ports.test.ts @@ -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" }, }), ); @@ -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" }, }), ); @@ -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" }, }), ); @@ -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" }, }), ); @@ -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" }, }), ); diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index 855cf456b30..73ab0f46397 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -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" }, }), ); @@ -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" }, }), ); diff --git a/src/lib/actions/sandbox/snapshot-restore-observability-policy.test.ts b/src/lib/actions/sandbox/snapshot-restore-observability-policy.test.ts index 08aa8e6005e..6d5dc761364 100644 --- a/src/lib/actions/sandbox/snapshot-restore-observability-policy.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-observability-policy.test.ts @@ -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" }, }), ); diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index 502746a1154..b946dca6658 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -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 = { @@ -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, @@ -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", diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 9515af756fb..ff394ac1898 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -5,7 +5,11 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { SANDBOX_EXEC_STARTED_MARKER } from "./sandbox-exec-output"; +import type { + SandboxExecRequest, + SandboxExecResult, +} from "../../adapters/openshell/sandbox-control"; +import { DCODE_BUSY_PROBE_SCRIPT } from "./dcode-activity-probe"; import type { SnapshotStreamSandboxCreateMock } from "./snapshot-create-stream-test-types"; type OpenshellCaptureResult = { @@ -20,22 +24,12 @@ type SandboxRecord = { name: string; observabilityEnabled?: boolean } & Record value.replaceAll(SANDBOX_EXEC_STARTED_MARKER, marker); - const stdout = replaceMarker(result.stdout ?? result.output); - const stderr = replaceMarker(result.stderr ?? ""); +function captureOpenshellStreams(result: OpenshellCaptureResult): OpenshellCaptureResult { + const stdout = result.stdout ?? result.output; + const stderr = result.stderr ?? ""; return { ...result, output: stdout, stdout, stderr }; } @@ -47,12 +41,11 @@ function openshellResponses( status: 0, output: "", }; - return captureOpenshellStreams(args, result); + return captureOpenshellStreams(result); } function defaultOpenshellResponses(args: string[]): OpenshellCaptureResult { return openshellResponses(args, { - "sandbox exec": { status: 0, output: dcodeProbeOutput("no-runtime") }, "sandbox list": { status: 0, output: "alpha Ready\n", @@ -113,6 +106,9 @@ const getOpenShellSandboxDescriptorMock = vi.fn( image: `nemoclaw-${sandboxName}:live`, }), ); +const execSandboxReadOnlyMock = vi.fn< + (_gatewayName: string, request: SandboxExecRequest) => Promise +>(async () => ({ status: 0, stdout: dcodeProbeOutput("no-runtime"), stderr: "" })); const applyPresetMock = vi.fn((_sandbox: string, _preset: string) => true); const applyPresetContentMock = vi.fn( (_sandbox: string, _name: string, _content: string, _options?: unknown) => true, @@ -158,11 +154,13 @@ vi.mock("../../adapters/docker", () => ({ vi.mock("../../adapters/openshell/runtime", () => ({ captureOpenshell: captureOpenshellMock, + captureOpenshellBinary: vi.fn(), getOpenshellBinary: vi.fn(() => "openshell"), runOpenshell: runOpenshellMock, })); vi.mock("../../adapters/openshell/sandbox-control-routing", () => ({ + execSandboxReadOnlyWithGrpcFallback: execSandboxReadOnlyMock, getOpenShellSandboxDescriptor: getOpenShellSandboxDescriptorMock, })); @@ -271,6 +269,11 @@ describe("runSandboxSnapshot", () => { name: sandboxName, image: `nemoclaw-${sandboxName}:live`, })); + execSandboxReadOnlyMock.mockResolvedValue({ + status: 0, + stdout: dcodeProbeOutput("no-runtime"), + stderr: "", + }); applyPresetMock.mockReturnValue(true); applyPresetContentMock.mockReturnValue(true); removePresetMock.mockReturnValue(true); @@ -303,23 +306,17 @@ describe("runSandboxSnapshot", () => { } function mockDcodeProbeResult(result: OpenshellCaptureResult) { - captureOpenshellMock.mockImplementation((args: string[]) => { - return openshellResponses(args, { - "sandbox exec": result, - "sandbox list": { - status: 0, - output: "alpha Ready\n", - }, - }); + execSandboxReadOnlyMock.mockResolvedValue({ + status: result.status, + stdout: result.stdout ?? result.output, + stderr: result.stderr ?? "", + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), }); } function capturedDcodeProbeScript(): string { - const execArgs = - captureOpenshellMock.mock.calls - .map(([args]) => args) - .find((args) => args[0] === "sandbox" && args[1] === "exec") ?? []; - return String(execArgs.at(-1) ?? ""); + return String(execSandboxReadOnlyMock.mock.calls.at(-1)?.[1].stdin ?? ""); } function runProbeScriptWithProcesses( @@ -408,15 +405,16 @@ describe("runSandboxSnapshot", () => { }); expect(backupSandboxStateMock).not.toHaveBeenCalled(); - expect( - captureOpenshellMock.mock.calls.some( - ([args]) => - args[0] === "sandbox" && - args[1] === "exec" && - args.includes("--name") && - args.includes("alpha"), - ), - ).toBe(true); + expect(execSandboxReadOnlyMock).toHaveBeenCalledWith("nemoclaw", { + sandboxName: "alpha", + command: ["sh", "-s"], + stdin: DCODE_BUSY_PROBE_SCRIPT, + timeoutMs: 15_000, + }); + const { validateOpenShellExecRequest } = await import( + "../../adapters/openshell/sandbox-control" + ); + expect(validateOpenShellExecRequest(execSandboxReadOnlyMock.mock.calls.at(-1)![1])).toBeNull(); expect(consoleError.mock.calls.flat().join("\n")).toContain( "Sandbox is actively running a dcode task. Please retry after the task completes.", ); @@ -467,115 +465,11 @@ describe("runSandboxSnapshot", () => { expect(consoleLog.mock.calls.flat().join("\n")).toContain("Snapshot v8 name=idle created"); }); - it("allows dcode snapshot creation when OpenShell frames the probe stdout", async () => { - getSandboxMock.mockReturnValue(dcodeSandboxEntry); - mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("idle") }); - const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); - const manifest = { - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - name: "framed-idle", - }; - backupSandboxStateMock.mockReturnValue({ - success: true, - backedUpDirs: ["workspace"], - backedUpFiles: ["config.toml"], - failedDirs: [], - failedFiles: [], - manifest, - }); - findBackupMock.mockReturnValue({ - match: { ...manifest, snapshotVersion: 9, name: "framed-idle" }, - }); - const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { kind: "create", name: "framed-idle" }); - - expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: "framed-idle" }); - expect(consoleLog.mock.calls.flat().join("\n")).toContain( - "Snapshot v9 name=framed-idle created", - ); - const execCall = captureOpenshellMock.mock.calls.find( - ([args]) => args[0] === "sandbox" && args[1] === "exec", - ); - expect(execCall?.[1]).toMatchObject({ ignoreError: true, includeStreams: true }); - expect(execCall?.[0]).toContain("-c"); - expect(execCall?.[0]).not.toContain("-lc"); - expect(String(execCall?.[0].at(-1) ?? "")).toMatch( - new RegExp(`${SANDBOX_EXEC_STARTED_MARKER}_[0-9a-f]{32}`), - ); - }); - - it("refuses an active dcode task when OpenShell frames the probe stdout", async () => { - getSandboxMock.mockReturnValue(dcodeSandboxEntry); - mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("active", "[stdout] ") }); - const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({ - exitCode: 1, - }); - - expect(backupSandboxStateMock).not.toHaveBeenCalled(); - expect(consoleError.mock.calls.flat().join("\n")).toContain( - "Sandbox is actively running a dcode task. Please retry after the task completes.", - ); - }); - - it("refuses a probe that repeats its marker after an active state", async () => { - getSandboxMock.mockReturnValue(dcodeSandboxEntry); - mockDcodeProbeResult({ - status: 0, - output: [ - SANDBOX_EXEC_STARTED_MARKER, - "NEMOCLAW_DCODE_PROBE=active", - SANDBOX_EXEC_STARTED_MARKER, - "NEMOCLAW_DCODE_PROBE=idle", - ].join("\n"), - }); - const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({ - exitCode: 1, - }); - - expect(backupSandboxStateMock).not.toHaveBeenCalled(); - expect(consoleError.mock.calls.flat().join("\n")).toContain( - "Cannot verify whether sandbox 'alpha' is actively running a dcode task.", - ); - }); - - it("refuses conflicting probe states after one valid marker", async () => { + it("refuses conflicting probe states", async () => { getSandboxMock.mockReturnValue(dcodeSandboxEntry); mockDcodeProbeResult({ status: 0, - output: [ - SANDBOX_EXEC_STARTED_MARKER, - "NEMOCLAW_DCODE_PROBE=idle", - "NEMOCLAW_DCODE_PROBE=active", - ].join("\n"), - }); - const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); - const { runSandboxSnapshot } = await import("./snapshot"); - - await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({ - exitCode: 1, - }); - - expect(backupSandboxStateMock).not.toHaveBeenCalled(); - expect(consoleError.mock.calls.flat().join("\n")).toContain( - "Cannot verify whether sandbox 'alpha' is actively running a dcode task.", - ); - }); - - it("refuses conflicting probe markers split across stdout and stderr", async () => { - getSandboxMock.mockReturnValue(dcodeSandboxEntry); - mockDcodeProbeResult({ - status: 0, - output: "", - stdout: dcodeProbeOutput("active"), - stderr: framedDcodeProbeOutput("idle"), + output: ["NEMOCLAW_DCODE_PROBE=idle", "NEMOCLAW_DCODE_PROBE=active"].join("\n"), }); const consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); const { runSandboxSnapshot } = await import("./snapshot"); @@ -697,9 +591,7 @@ describe("runSandboxSnapshot", () => { await runSandboxSnapshot("alpha", { kind: "create" }); - expect( - captureOpenshellMock.mock.calls.some(([args]) => args[0] === "sandbox" && args[1] === "exec"), - ).toBe(false); + expect(execSandboxReadOnlyMock).not.toHaveBeenCalled(); expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: null, }); diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index d34d82d5163..6f1cf0c9af5 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -8,7 +8,10 @@ import { getOpenshellBinary, runOpenshell, } from "../../adapters/openshell/runtime"; -import { getOpenShellSandboxDescriptor } from "../../adapters/openshell/sandbox-control-routing"; +import { + execSandboxReadOnlyWithGrpcFallback, + getOpenShellSandboxDescriptor, +} from "../../adapters/openshell/sandbox-control-routing"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../../adapters/openshell/timeouts"; import { CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt } from "../../credentials/store"; @@ -64,11 +67,6 @@ import { parseDcodeProbeState, } from "./dcode-activity-probe"; import { cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntry } from "./destroy"; -import { - buildSandboxExecMarkedCommand, - createSandboxExecMarker, - extractSandboxExecCommandStdoutFromStreams, -} from "./sandbox-exec-output"; import { probeGatewayRunning, selectSandboxGatewayIfRegistered } from "./sandbox-gateway-routing"; import { runSnapshotRestoreMutationAfterSourceRecheck, @@ -465,7 +463,7 @@ function shouldCheckDcodeActivity(sandboxName: string): boolean { return !entry || entry.agent === DCODE_AGENT_NAME; } -function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean { +async function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): Promise { // Invalid state: backing up .deepagents while dcode is actively mutating it can // produce a snapshot that later restores inconsistent agent state. The source // boundary available today is the live sandbox process table plus runtime @@ -475,31 +473,22 @@ function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean // timeouts, and any detected-but-unverifiable runtime. Remove this workaround // when dcode exposes a wrapper-owned idle/active lock or equivalent snapshot // quiescence signal and the backup path checks that source directly. - const execMarker = createSandboxExecMarker(); - const probe = captureOpenshell( - [ - "sandbox", - "exec", - "--name", - sandboxName, - "--", - "sh", - "-c", - buildSandboxExecMarkedCommand(DCODE_BUSY_PROBE_SCRIPT, execMarker), - ], - { - ignoreError: true, - includeStreams: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }, - ); - const probeCompleted = probe.status === 0 && !probe.error && !probe.signal; - const commandStdout = probeCompleted - ? extractSandboxExecCommandStdoutFromStreams( - { stdout: probe.stdout, stderr: probe.stderr }, - execMarker, - ) - : null; + let probe; + try { + probe = await execSandboxReadOnlyWithGrpcFallback( + resolveSandboxGatewayName(registry.getSandbox(sandboxName)), + { + sandboxName, + command: ["sh", "-s"], + stdin: DCODE_BUSY_PROBE_SCRIPT, + timeoutMs: OPENSHELL_PROBE_TIMEOUT_MS, + }, + ); + } catch { + probe = null; + } + const commandStdout = + probe && probe.status === 0 && !probe.error && !probe.signal ? probe.stdout.trim() : null; const probeState = commandStdout === null ? null : parseDcodeProbeState(commandStdout); if ( probeState === DCODE_PROBE_STATE.idleDcodeRuntime || @@ -546,7 +535,7 @@ async function runSnapshotCreate( } if ( shouldCheckDcodeActivity(sandboxName) && - !isSnapshotCreationAllowedByDcodeActivity(sandboxName) + !(await isSnapshotCreationAllowedByDcodeActivity(sandboxName)) ) { snapshotExit(1); } diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index bd26a87d3aa..05298450410 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -159,6 +159,16 @@ describe("legacy sandbox transport inventory", () => { kind: "grpc-cli-read-only-fallback", calls: 1, }, + { + relativePath: "src/lib/actions/sandbox/process-recovery.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, + { + relativePath: "src/lib/actions/sandbox/snapshot.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, { relativePath: "src/lib/diagnostics/debug.ts", kind: "grpc-cli-read-only-fallback",