Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
16 changes: 16 additions & 0 deletions src/lib/actions/sandbox/docker-health.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { getSandboxDockerHealth, getSandboxDockerRuntime } from "./docker-health
function fixture({
driver = "docker",
psNames = "openshell-cluster-nemoclaw\nopenshell-my-assistant-12ab\nopenshell-other-aa11",
psAllNames = psNames,
healthRaw = "unhealthy\n",
pausedRaw = "false\n",
throwOnInspect = false,
Expand All @@ -16,6 +17,7 @@ function fixture({
}: {
driver?: string | null;
psNames?: string;
psAllNames?: string;
healthRaw?: string;
pausedRaw?: string;
throwOnInspect?: boolean;
Expand All @@ -27,6 +29,7 @@ function fixture({
getSandbox: () => sandbox as SandboxEntry,
listSandboxNames: () => knownSandboxes,
dockerPsNames: () => psNames,
dockerPsAllNames: () => psAllNames,
dockerInspectHealth: () => {
if (throwOnInspect) throw new Error("docker inspect crashed");
return healthRaw;
Expand Down Expand Up @@ -150,6 +153,19 @@ describe("getSandboxDockerHealth", () => {
});

describe("getSandboxDockerRuntime (#4495)", () => {
it("finds an exited container that is absent from the running-only listing (#7222)", () => {
const deps = fixture({
psNames: "openshell-cluster-nemoclaw\n",
psAllNames: "openshell-cluster-nemoclaw\nopenshell-my-assistant-12ab\n",
healthRaw: "none",
});
expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({
health: "none",
paused: false,
containerName: "openshell-my-assistant-12ab",
});
});

it("reports paused=true when the resolved docker-driver container is paused", () => {
const deps = fixture({ healthRaw: "healthy\n", pausedRaw: "true\n" });
expect(getSandboxDockerRuntime("my-assistant", deps)).toEqual({
Expand Down
18 changes: 12 additions & 6 deletions src/lib/actions/sandbox/docker-health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ interface ResolveDeps {
getSandbox: (name: string) => registry.SandboxEntry | null;
listSandboxNames: () => string[];
dockerPsNames: () => string;
dockerPsAllNames: () => string;
dockerInspectHealth: (containerName: string) => string;
dockerInspectPaused: (containerName: string) => string;
}
Expand All @@ -38,6 +39,8 @@ const defaultDeps: ResolveDeps = {
getSandbox: (name) => registry.getSandbox(name),
listSandboxNames: () => registry.listSandboxes().sandboxes.map((entry) => entry.name),
dockerPsNames: () => dockerCapture(["ps", "--format", "{{.Names}}"], { ignoreError: true }),
dockerPsAllNames: () =>
dockerCapture(["ps", "-a", "--format", "{{.Names}}"], { ignoreError: true }),
dockerInspectHealth: (containerName) =>
dockerContainerInspectFormat(
"{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}",
Expand Down Expand Up @@ -106,18 +109,21 @@ function normalizePausedState(raw: string): boolean {
}

/**
* Resolve a docker-driver sandbox container once and read both its HEALTHCHECK
* state and `.State.Paused` flag. Returns `health: "none", paused: false` when
* the sandbox is not on the docker driver or no container is found — same
* resolution contract as {@link getSandboxDockerHealth}. A paused container is
* still listed by `docker ps`, so the existing resolver finds it. See #4495.
* Resolve a docker-driver sandbox container across all states and read both its
* HEALTHCHECK state and `.State.Paused` flag. The all-state lookup is required
* so Error-phase guidance can recognize an exited container that `start` can
* recover (#7222). Returns `health: "none", paused: false` when the sandbox is
* not on the docker driver or no container is found. See #4495.
*/
export function getSandboxDockerRuntime(
sandboxName: string,
depsOverride: Partial<ResolveDeps> = {},
): SandboxDockerRuntime {
const deps: ResolveDeps = { ...defaultDeps, ...depsOverride };
const containerName = resolveDockerDriverSandboxContainer(sandboxName, deps);
const containerName = resolveDockerDriverSandboxContainer(sandboxName, {
...deps,
dockerPsNames: deps.dockerPsAllNames,
});
if (!containerName) return { health: "none", paused: false, containerName: null };
let health: DockerHealthState;
try {
Expand Down
113 changes: 113 additions & 0 deletions src/lib/actions/sandbox/gateway-state-hints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const requireDist = createRequire(import.meta.url);
describe("printGatewayLifecycleHint multi-instance hints", () => {
let gatewayState: GatewayStateModule;
let captureOpenshellSpy: MockInstance;
let getSandboxDockerRuntimeSpy: MockInstance;
let getNamedGatewayLifecycleStateSpy: MockInstance;
let getSandboxSpy: MockInstance;
let recoverNamedGatewayRuntimeSpy: MockInstance;
Expand All @@ -23,6 +24,7 @@ describe("printGatewayLifecycleHint multi-instance hints", () => {
const openshellRuntime = requireDist("../../adapters/openshell/runtime.js");
const gatewayRuntime = requireDist("../../gateway-runtime-action.js");
const registry = requireDist("../../state/registry.js");
const dockerHealth = requireDist("./docker-health.js");
const gatewaySelect = requireDist("./gateway-select.js");
vi.spyOn(gatewayDrift, "detectOpenShellStateRpcPreflightIssue").mockReturnValue(null);
vi.spyOn(gatewayDrift, "detectOpenShellStateRpcResultIssue").mockReturnValue(null);
Expand All @@ -41,6 +43,11 @@ describe("printGatewayLifecycleHint multi-instance hints", () => {
gatewayName: "nemoclaw",
gatewayPort: 8080,
});
getSandboxDockerRuntimeSpy = vi.spyOn(dockerHealth, "getSandboxDockerRuntime").mockReturnValue({
health: "none",
paused: false,
containerName: "openshell-instance-a-abc",
});
vi.spyOn(gatewaySelect, "selectSandboxOwningGateway").mockReturnValue({
outcome: "selected",
gatewayName: "nemoclaw",
Expand Down Expand Up @@ -137,6 +144,112 @@ describe("printGatewayLifecycleHint multi-instance hints", () => {
);
});

it("steers a non-paused Error sandbox to the workspace-preserving start path (#7222)", async () => {
captureOpenshellSpy.mockReturnValue({
status: 0,
output: "Sandbox:\n Name: instance-a\n Phase: Error",
});
const lines: string[] = [];
vi.spyOn(console, "error").mockImplementation((line = "") => {
lines.push(String(line));
});
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow(
"process.exit(1)",
);

const output = lines.join("\n");
expect(output).toContain("nemoclaw instance-a start");
expect(output).toContain("workspace state preserved");
expect(output).not.toContain("docker unpause");
expect(getSandboxDockerRuntimeSpy).toHaveBeenCalledWith("instance-a");
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("keeps rebuild guidance when an Error sandbox has no recoverable container", async () => {
captureOpenshellSpy.mockReturnValue({
status: 0,
output: "Sandbox:\n Name: instance-a\n Phase: Error",
});
getSandboxDockerRuntimeSpy.mockReturnValue({
health: "none",
paused: false,
containerName: null,
});
const lines: string[] = [];
vi.spyOn(console, "error").mockImplementation((line = "") => {
lines.push(String(line));
});
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow(
"process.exit(1)",
);

const output = lines.join("\n");
expect(output).toContain("nemoclaw instance-a rebuild --yes");
expect(output).not.toContain("nemoclaw instance-a start");
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("keeps rebuild guidance for terminal phases other than Error", async () => {
captureOpenshellSpy.mockReturnValue({
status: 0,
output: "Sandbox:\n Name: instance-a\n Phase: Failed",
});
const lines: string[] = [];
vi.spyOn(console, "error").mockImplementation((line = "") => {
lines.push(String(line));
});
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow(
"process.exit(1)",
);

const output = lines.join("\n");
expect(output).toContain("nemoclaw instance-a rebuild --yes");
expect(output).not.toContain("nemoclaw instance-a start");
expect(getSandboxDockerRuntimeSpy).not.toHaveBeenCalled();
expect(exitSpy).toHaveBeenCalledWith(1);
});

it("preserves docker-unpause recovery for a paused Error sandbox (#4495)", async () => {
captureOpenshellSpy.mockReturnValue({
status: 0,
output: "Sandbox:\n Name: instance-a\n Phase: Error",
});
getSandboxDockerRuntimeSpy.mockReturnValue({
health: "none",
paused: true,
containerName: "openshell-instance-a-abc",
});
const lines: string[] = [];
vi.spyOn(console, "error").mockImplementation((line = "") => {
lines.push(String(line));
});
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => {
throw new Error(`process.exit(${code ?? 0})`);
}) as never);

await expect(gatewayState.ensureLiveSandboxOrExit("instance-a")).rejects.toThrow(
"process.exit(1)",
);

const output = lines.join("\n");
expect(output).toContain("docker unpause openshell-instance-a-abc");
expect(output).not.toContain("nemoclaw instance-a start");
expect(output).not.toContain("rebuild --yes");
expect(exitSpy).toHaveBeenCalledWith(1);
});

it.each([
{
lifecycle: {
Expand Down
31 changes: 28 additions & 3 deletions src/lib/actions/sandbox/gateway-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ import {
OPENSHELL_OPERATION_TIMEOUT_MS,
OPENSHELL_PROBE_TIMEOUT_MS,
} from "../../adapters/openshell/timeouts";
import { D, R } from "../../cli/terminal-style";
import {
type DockerDriverRecoveryResult,
recoverDockerDriverSandbox,
} from "../../onboard/docker-driver-sandbox-recovery";
import { getSandboxDockerRuntime } from "./docker-health";
import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier";

export type SandboxGatewayState = {
Expand Down Expand Up @@ -583,14 +585,37 @@ export async function ensureLiveSandboxOrExit(
printDockerRuntimeDownGuidance(sandboxName);
process.exit(1);
}
const dockerRuntime = phase === "Error" ? getSandboxDockerRuntime(sandboxName) : null;
if (dockerRuntime?.paused && dockerRuntime.containerName) {
console.error(` Sandbox '${sandboxName}' is stuck in '${phase}' phase.`);
console.error("");
console.error(
` The Docker-driver container for '${sandboxName}' is paused: ${dockerRuntime.containerName}`,
);
console.error(
" A paused container can report 'Phase: Error' even though the sandbox is intact.",
);
console.error(" Resume it to restore the running phase:");
console.error(` ${D}docker unpause ${dockerRuntime.containerName}${R}`);
process.exit(1);
}
console.error(` Sandbox '${sandboxName}' is stuck in '${phase}' phase.`);
console.error(
" This usually happens when a process crash inside the sandbox prevented clean startup.",
);
console.error("");
console.error(
` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`,
);
if (phase === "Error" && dockerRuntime?.containerName) {
console.error(
` Run \`${CLI_NAME} ${sandboxName} start\` to restart the crashed container and recover the sandbox with workspace state preserved.`,
);
console.error(
` (\`${CLI_NAME} ${sandboxName} rebuild --yes\` recreates the sandbox instead, but its pre-rebuild backup cannot snapshot a stopped container, so start it first.)`,
);
} else {
console.error(
` Run \`${CLI_NAME} ${sandboxName} rebuild --yes\` to recreate the sandbox (--yes skips the confirmation prompt; workspace state will be preserved).`,
);
}
process.exit(1);
}
return lookup;
Expand Down
Loading