diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index 330e4eb46e0..b14fb93c2ef 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -88,6 +88,7 @@ import { import { preflightVllmModelEnvOrExit } from "./connect-vllm-preflight"; import { isDockerRuntimeDown, printDockerRuntimeDownGuidance } from "./gateway-failure-classifier"; import { + createSandboxStartErrorGrace, ensureLiveSandboxOrExit, buildHermesPortableCommandAuthority, defaultPortableDemoStateDir, @@ -1979,16 +1980,6 @@ type WaitForSandboxReadyOptions = { successLogs?: readonly string[]; }; -// OpenShell can transiently publish `Error` immediately after `sandbox start` -// before the same sandbox advances through `Provisioning` to `Ready`. Its list -// output exposes no structured transition reason. A caller opts into twenty -// three-second grace polls only after it starts the container; every other -// terminal phase still fails immediately, and a persistent Error fails after -// the bound. Remove this compatibility exception once OpenShell exposes a -// structured restart signal or guarantees that post-start recovery never emits -// the terminal Error phase. -const START_INITIAL_ERROR_GRACE_POLLS = 20; - // Readiness budget for the repair paths that wait for a restarted sandbox // before they touch in-sandbox processes or host forwards. A cold agent boot on // a constrained host can exceed the interactive budget, and `start` and @@ -2050,9 +2041,9 @@ export async function waitForSandboxReadyOrExit( if (status && /^unknown$/i.test(status)) { await failIfGatewayBlocksConnectReadiness(sandboxName); } - let remainingInitialErrorGracePolls = - allowInitialErrorAfterStart && status === "Error" ? START_INITIAL_ERROR_GRACE_POLLS - 1 : 0; - if (status && TERMINAL_SANDBOX_PHASES.has(status) && remainingInitialErrorGracePolls === 0) { + const allowInitialError = createSandboxStartErrorGrace(allowInitialErrorAfterStart); + const initialErrorAllowed = allowInitialError(status); + if (status && TERMINAL_SANDBOX_PHASES.has(status) && !initialErrorAllowed) { failConnectReadinessTerminalPhase(sandboxName, `is in '${status}'`, { inspectDockerIdentity: allowDockerRuntimeInspection, retryCommand, @@ -2083,12 +2074,7 @@ export async function waitForSandboxReadyOrExit( await failIfGatewayBlocksConnectReadiness(sandboxName); } if (cur !== "unknown") everSeen = true; - const waitingThroughInitialError = cur === "Error" && remainingInitialErrorGracePolls > 0; - if (waitingThroughInitialError) { - remainingInitialErrorGracePolls -= 1; - } else { - remainingInitialErrorGracePolls = 0; - } + const waitingThroughInitialError = allowInitialError(cur); if (TERMINAL_SANDBOX_PHASES.has(cur) && !waitingThroughInitialError) { failConnectReadinessTerminalPhase(sandboxName, `entered '${cur}'`, { inspectDockerIdentity: allowDockerRuntimeInspection, diff --git a/src/lib/actions/sandbox/gateway-state.ts b/src/lib/actions/sandbox/gateway-state.ts index a6ac4e94d86..91edad026a4 100644 --- a/src/lib/actions/sandbox/gateway-state.ts +++ b/src/lib/actions/sandbox/gateway-state.ts @@ -27,6 +27,7 @@ import { TERMINAL_SANDBOX_PHASES, } from "../../state/gateway"; export { isTerminalSandboxPhase, sandboxPhaseNeedsLifecycleStart, TERMINAL_SANDBOX_PHASES }; +export { createSandboxStartErrorGrace } from "../../domain/lifecycle/sandbox-start-error-grace"; import { selectNamedGateway, selectSandboxOwningGateway } from "./gateway-select"; import { gatewayNamePattern, diff --git a/src/lib/actions/sandbox/start-wait.test.ts b/src/lib/actions/sandbox/start-wait.test.ts index 0ca21e1fa09..fe2ead086cb 100644 --- a/src/lib/actions/sandbox/start-wait.test.ts +++ b/src/lib/actions/sandbox/start-wait.test.ts @@ -96,17 +96,23 @@ describe("sandbox start readiness", () => { expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(3); }); - it("waits through the next OpenShell health reconciliation after a slow restart (#9485)", async () => { - const harness = createConnectHarness({ - listOutputs: [...Array.from({ length: 11 }, () => "alpha Error"), "alpha Ready"], - }); + it.each([11, 20])( + "waits through %s initial Error observations after a slow restart (#9485)", + async (errorObservations) => { + const harness = createConnectHarness({ + listOutputs: [ + ...Array.from({ length: errorObservations }, () => "alpha Error"), + "alpha Ready", + ], + }); - await expect( - harness.waitForSandboxReadyOrExit("alpha", { allowInitialErrorAfterStart: true }), - ).resolves.toBeUndefined(); + await expect( + harness.waitForSandboxReadyOrExit("alpha", { allowInitialErrorAfterStart: true }), + ).resolves.toBeUndefined(); - expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(12); - }); + expect(harness.captureOpenshellSpy).toHaveBeenCalledTimes(errorObservations + 1); + }, + ); it("fails after the stopped sandbox Error phase remains terminal (#9753)", async () => { const harness = createConnectHarness({ diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts index 6d407fa076c..66082768c09 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.test.ts @@ -15,29 +15,31 @@ function harness() { const response = { sandbox: { metadata: { id: sandboxId } } }; const startSandbox = vi.fn(async () => response); const stopSandbox = vi.fn(async () => response); - const get = vi.fn(async () => ({ id: sandboxId, phase: "stopped" })); + const get = vi.fn(async () => ({ id: sandboxId, phase: "ready" })); const waitReady = vi.fn(async () => ({ id: sandboxId, phase: "ready" })); const connect = vi.fn(async () => ({ raw: { startSandbox, stopSandbox }, sandbox: { get, waitReady }, })); - const lifecycle = createSdkOpenShellSandboxStateLifecycle({ connect }); - return { connect, get, lifecycle, startSandbox, stopSandbox, waitReady }; + const waitForStartPoll = vi.fn(async () => undefined); + const lifecycle = createSdkOpenShellSandboxStateLifecycle({ connect, waitForStartPoll }); + return { connect, get, lifecycle, startSandbox, stopSandbox, waitForStartPoll, waitReady }; } describe("OpenShell SDK sandbox lifecycle", () => { it("starts and stops the named sandbox through typed SDK RPCs", async () => { - const { connect, get, lifecycle, startSandbox, stopSandbox, waitReady } = harness(); + const { connect, get, lifecycle, startSandbox, stopSandbox } = harness(); await expect(lifecycle.startSandbox(request)).resolves.toEqual({ kind: "accepted", }); + get.mockResolvedValue({ id: sandboxId, phase: "stopped" }); await expect(lifecycle.stopSandbox(request)).resolves.toEqual({ kind: "accepted", }); expect(connect).toHaveBeenCalledTimes(2); - expect(get).toHaveBeenCalledTimes(3); + expect(get).toHaveBeenCalledTimes(4); expect(startSandbox).toHaveBeenCalledWith( { name: "alpha", workspace: "default" }, { signal: expect.any(AbortSignal) }, @@ -46,10 +48,7 @@ describe("OpenShell SDK sandbox lifecycle", () => { { name: "alpha", workspace: "default" }, { signal: expect.any(AbortSignal) }, ); - expect(waitReady).toHaveBeenCalledOnce(); - expect(waitReady).toHaveBeenCalledWith("alpha", 75, { - signal: expect.any(AbortSignal), - }); + expect(get).toHaveBeenCalledWith("alpha", { signal: expect.any(AbortSignal) }); }); it("rejects an invalid name before it connects", async () => { @@ -62,13 +61,124 @@ describe("OpenShell SDK sandbox lifecycle", () => { expect(connect).not.toHaveBeenCalled(); }); + it("waits through the initial restart Error until the same sandbox is Ready", async () => { + const test = harness(); + // The pinned SDK rejects this initial Error as a connect failure. + test.waitReady.mockRejectedValue( + Object.assign(new Error("sandbox entered error phase"), { code: "connect" }), + ); + test.get + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockResolvedValueOnce({ id: sandboxId, phase: "Error" }) + .mockResolvedValueOnce({ id: sandboxId, phase: "Error" }) + .mockResolvedValueOnce({ id: sandboxId, phase: "Provisioning" }); + + await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ kind: "accepted" }); + expect(test.waitForStartPoll).toHaveBeenCalledTimes(3); + expect(test.startSandbox).toHaveBeenCalledOnce(); + expect(test.waitReady).not.toHaveBeenCalled(); + }); + + it("accepts Ready after twenty initial Error observations", async () => { + const test = harness(); + const phases = ["stopped", ...Array(20).fill("Error"), "Ready"]; + test.get.mockImplementation(async () => ({ + id: sandboxId, + phase: phases.shift() ?? "Error", + })); + + await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ kind: "accepted" }); + expect(test.waitForStartPoll).toHaveBeenCalledTimes(20); + expect(test.startSandbox).toHaveBeenCalledOnce(); + }); + + it.each([ + { firstPhase: "Error", expectedPolls: 20 }, + { firstPhase: "Provisioning", expectedPolls: 1 }, + ])("fails on Error after $firstPhase", async ({ firstPhase, expectedPolls }) => { + const test = harness(); + test.get + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockResolvedValueOnce({ id: sandboxId, phase: firstPhase }) + .mockResolvedValue({ id: sandboxId, phase: "Error" }); + + await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ + kind: "failed", + error: { + kind: "command", + reason: "failed", + message: "OpenShell sandbox entered Error while waiting for readiness after start.", + }, + }); + expect(test.waitForStartPoll).toHaveBeenCalledTimes(expectedPolls); + expect(test.startSandbox).toHaveBeenCalledOnce(); + }); + + it("rejects replacement identity during initial Error without retrying the start", async () => { + const test = harness(); + test.get + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockResolvedValueOnce({ id: sandboxId, phase: "Error" }) + .mockResolvedValueOnce({ id: "replacement-id", phase: "Error" }); + + await expect(test.lifecycle.startSandbox(request)).resolves.toEqual({ + kind: "failed", + error: { + kind: "transport", + reason: "identity_mismatch", + message: "OpenShell readiness changed sandbox identity.", + }, + }); + expect(test.startSandbox).toHaveBeenCalledOnce(); + }); + + it.each( + ["Failed", "CrashLoopBackOff", "ImagePullBackOff", "Unknown", "Evicted"].flatMap((phase) => [ + phase, + phase.toLowerCase(), + ]), + )("fails immediately when start reports %s", async (phase) => { + const test = harness(); + test.get + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockResolvedValue({ id: sandboxId, phase }); + test.waitForStartPoll.mockImplementation(() => new Promise(() => undefined)); + + await expect(test.lifecycle.startSandbox({ ...request, timeoutMs: 50 })).resolves.toEqual({ + kind: "failed", + error: { + kind: "command", + reason: "failed", + message: `OpenShell sandbox entered ${phase} while waiting for readiness after start.`, + }, + }); + expect(test.waitForStartPoll).not.toHaveBeenCalled(); + expect(test.get).toHaveBeenCalledTimes(2); + expect(test.startSandbox).toHaveBeenCalledOnce(); + }); + + it.each([ + ["rpc", "14", "transport"], + ["auth", undefined, "authentication"], + ])("fails immediately on a readiness %s failure", async (code, connectCode, kind) => { + const test = harness(); + test.get + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockResolvedValueOnce({ id: sandboxId, phase: "Error" }) + .mockRejectedValueOnce(Object.assign(new Error("secret detail"), { code, connectCode })); + + const result = await test.lifecycle.startSandbox(request); + expect(result.kind === "failed" && result.error.kind).toBe(kind); + expect(test.startSandbox).toHaveBeenCalledOnce(); + expect(test.waitForStartPoll).toHaveBeenCalledOnce(); + }); + it("classifies an SDK authorization denial without exposing its detail", async () => { const denied = Object.assign(new Error("token=secret"), { code: "auth" }); const lifecycle = createSdkOpenShellSandboxStateLifecycle({ connect: async () => ({ sandbox: { get: async () => ({ id: sandboxId, phase: "stopped" }), - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, raw: { startSandbox: async () => Promise.reject(denied), @@ -120,7 +230,7 @@ describe("OpenShell SDK sandbox lifecycle", () => { message: `OpenShell rejected the ${operation === "startSandbox" ? "start" : "stop"} request because the sandbox is in Error state.`, }, }); - expect(test.waitReady).not.toHaveBeenCalled(); + expect(test.get).toHaveBeenCalledOnce(); }, ); @@ -149,7 +259,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get: async () => ({ id: sandboxId, phase: "stopped" }), - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), }); @@ -168,8 +277,10 @@ describe("OpenShell SDK sandbox lifecycle", () => { stopSandbox: async () => ({ sandbox: { metadata: { id: sandboxId } } }), }, sandbox: { - get: async () => ({ id: sandboxId, phase: "stopped" }), - waitReady: () => new Promise(() => undefined), + get: vi + .fn() + .mockResolvedValueOnce({ id: sandboxId, phase: "stopped" }) + .mockImplementation(() => new Promise(() => undefined)), }, }), }); @@ -213,7 +324,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get, - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), }); @@ -245,7 +355,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get, - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), waitForStopPoll, @@ -265,7 +374,6 @@ describe("OpenShell SDK sandbox lifecycle", () => { }, sandbox: { get: async () => ({ id: sandboxId, phase: "stopping" }), - waitReady: async () => ({ id: sandboxId, phase: "ready" }), }, }), waitForStopPoll: async () => await new Promise(() => undefined), diff --git a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts index a6f28228875..feb3170fb25 100644 --- a/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts +++ b/src/lib/adapters/openshell/sandbox-lifecycle-sdk.ts @@ -3,7 +3,9 @@ import { setTimeout as delay } from "node:timers/promises"; +import { createSandboxStartErrorGrace } from "../../domain/lifecycle/sandbox-start-error-grace"; import { isValidName } from "../../name-validation"; +import { isTerminalSandboxPhase } from "../../state/gateway"; import { fingerprintOpenShellSandboxId } from "./sandbox-identity"; import type { OpenShellGatewayTarget, OpenShellSandboxError } from "./sandbox-observer"; @@ -31,7 +33,6 @@ type SdkSandboxMutationResponse = Readonly<{ type SdkClient = Readonly<{ sandbox: Readonly<{ get(name: string, options: CallOptions): Promise; - waitReady(name: string, timeoutSecs: number, options: CallOptions): Promise; }>; raw: Readonly<{ startSandbox( @@ -50,6 +51,7 @@ export type SdkOpenShellSandboxStateLifecycleDeps = Readonly<{ env?: NodeJS.ProcessEnv; homeDir?: string; loadSdk?: () => Promise; + waitForStartPoll?: (signal: AbortSignal) => Promise; waitForStopPoll?: (signal: AbortSignal) => Promise; }>; @@ -113,6 +115,7 @@ async function mutate( action: "start" | "stop", request: MutateOpenShellSandboxRequest, connect: (target: OpenShellGatewayTarget, options: CallOptions) => Promise, + waitForStartPoll: (signal: AbortSignal) => Promise, waitForStopPoll: (signal: AbortSignal) => Promise, ): Promise { if ( @@ -178,44 +181,43 @@ async function mutate( }, }; } - if (action === "start") { - const ready = await Promise.race([ - client.sandbox.waitReady( - request.sandboxName, - Math.max(1, Math.ceil((request.timeoutMs ?? DEFAULT_MUTATION_TIMEOUT_MS) / 1000)), - { signal: controller.signal }, - ), + const allowInitialError = createSandboxStartErrorGrace(action === "start"); + for (;;) { + const current = await Promise.race([ + client.sandbox.get(request.sandboxName, { signal: controller.signal }), aborted, ]); - if (fingerprintOpenShellSandboxId(ready.id) !== request.sandboxIdentityFingerprint) { + if (fingerprintOpenShellSandboxId(current.id) !== request.sandboxIdentityFingerprint) { return { kind: "failed", error: { kind: "transport", reason: "identity_mismatch", - message: "OpenShell readiness changed sandbox identity.", + message: + action === "start" + ? "OpenShell readiness changed sandbox identity." + : "OpenShell stop observation changed sandbox identity.", }, }; } - } else { - for (;;) { - const stopped = await Promise.race([ - client.sandbox.get(request.sandboxName, { signal: controller.signal }), - aborted, - ]); - if (fingerprintOpenShellSandboxId(stopped.id) !== request.sandboxIdentityFingerprint) { - return { - kind: "failed", - error: { - kind: "transport", - reason: "identity_mismatch", - message: "OpenShell stop observation changed sandbox identity.", - }, - }; - } - if (stopped.phase.toLowerCase() === "stopped") break; - await Promise.race([waitForStopPoll(controller.signal), aborted]); + const phase = current.phase.toLowerCase(); + if (phase === (action === "start" ? "ready" : "stopped")) break; + if (action === "start" && !allowInitialError(phase) && isTerminalSandboxPhase(phase)) { + return { + kind: "failed", + error: { + kind: "command", + reason: "failed", + message: `OpenShell sandbox entered ${current.phase} while waiting for readiness after start.`, + }, + }; } + await Promise.race([ + action === "start" + ? waitForStartPoll(controller.signal) + : waitForStopPoll(controller.signal), + aborted, + ]); } return { kind: "accepted" }; } catch (error) { @@ -249,8 +251,10 @@ export function createSdkOpenShellSandboxStateLifecycle( }); const waitForStopPoll = deps.waitForStopPoll ?? ((signal: AbortSignal) => delay(250, undefined, { signal })); + const waitForStartPoll = + deps.waitForStartPoll ?? ((signal: AbortSignal) => delay(3_000, undefined, { signal })); return { - startSandbox: (request) => mutate("start", request, connect, waitForStopPoll), - stopSandbox: (request) => mutate("stop", request, connect, waitForStopPoll), + startSandbox: (request) => mutate("start", request, connect, waitForStartPoll, waitForStopPoll), + stopSandbox: (request) => mutate("stop", request, connect, waitForStartPoll, waitForStopPoll), }; } diff --git a/src/lib/domain/lifecycle/sandbox-start-error-grace.ts b/src/lib/domain/lifecycle/sandbox-start-error-grace.ts new file mode 100644 index 00000000000..968993a0b76 --- /dev/null +++ b/src/lib/domain/lifecycle/sandbox-start-error-grace.ts @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// OpenShell can transiently report Error after start before advancing to Ready. +// Opt into twenty initial Error observations only after starting the sandbox; +// observing another phase ends the grace. Remove this compatibility exception +// when OpenShell exposes a structured restart signal or guarantees that restart +// recovery never emits the terminal Error phase. +const START_INITIAL_ERROR_GRACE_POLLS = 20; + +export function createSandboxStartErrorGrace( + enabled: boolean, +): (phase: string | null | undefined) => boolean { + let remainingPolls = enabled ? START_INITIAL_ERROR_GRACE_POLLS : 0; + return (phase) => { + const allowed = phase?.toLowerCase() === "error" && remainingPolls > 0; + remainingPolls = allowed ? remainingPolls - 1 : 0; + return allowed; + }; +} diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts index babd6c317fc..f0f57fba2f6 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.test.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.test.ts @@ -616,7 +616,6 @@ describe("managed workload onboard orchestration", () => { plan: { intent: { sandboxGpuLogMessage: null }, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), @@ -699,7 +698,6 @@ describe("managed workload onboard orchestration", () => { plan: { intent: { sandboxGpuLogMessage: null }, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), @@ -1022,7 +1020,6 @@ describe("managed workload onboard orchestration", () => { intent: {}, portableLifecycle: testCase.portableLifecycle === true, rebindMessagingTokenDefs: async () => [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "unused"), discloseInitialSandboxPolicy: vi.fn(), diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index 4a0902cbb90..b5f7a09a559 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -461,7 +461,6 @@ export interface PrepareOnboardSandboxWorkloadLaunchInput { readonly deferSandboxEffectsUntilIdentityVerification?: boolean; readonly skipProviderEffects?: boolean; readonly rebindMessagingTokenDefs: () => Promise; - readonly runProviderPreDeleteCleanup: MaterializeSandboxCreatePlanInput["runProviderPreDeleteCleanup"]; readonly upsertMessagingProviders: MaterializeSandboxCreatePlanInput["upsertMessagingProviders"]; readonly getHermesToolGatewayProviderName: (sandboxName: string) => string; readonly discloseInitialSandboxPolicy: (policy: InitialSandboxPolicy) => void; @@ -551,7 +550,6 @@ export async function prepareOnboardSandboxWorkloadLaunch( messagingTokenDefs: [...messagingTokenDefs], messagingConfig: input.messagingConfig ?? getMessagingChannelConfigFromPlan(input.plannedMessagingPlan), - runProviderPreDeleteCleanup: input.plan.runProviderPreDeleteCleanup, upsertMessagingProviders: input.plan.upsertMessagingProviders, getHermesToolGatewayProviderName: input.plan.getHermesToolGatewayProviderName, discloseInitialSandboxPolicy: input.plan.discloseInitialSandboxPolicy, diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index 2fabf1ebc3c..d12c693881f 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -109,9 +109,6 @@ export type MaterializeSandboxCreatePlanInput = { messagingTokenDefs: MessagingTokenDef[]; /** Non-secret config captured in the messaging plan that owns exact policy endpoints. */ messagingConfig?: MessagingChannelConfig | null; - runProviderPreDeleteCleanup( - revalidateSandboxIdentity?: (operation: string) => void, - ): Promise; upsertMessagingProviders( tokenDefs: MessagingTokenDef[], options: { diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index b6d19cdd8ec..20554567474 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -367,7 +367,6 @@ export async function materializeSandboxCreatePlan({ skipProviderEffects = false, messagingTokenDefs, messagingConfig, - runProviderPreDeleteCleanup, upsertMessagingProviders, getHermesToolGatewayProviderName, discloseInitialSandboxPolicy, @@ -423,7 +422,6 @@ export async function materializeSandboxCreatePlan({ const activateProviderEffects = async ( revalidateSandboxIdentity?: (operation: string) => void, ): Promise => { - await runProviderPreDeleteCleanup(revalidateSandboxIdentity); const activatedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ ...(await upsertMessagingProviders(enabledMessagingTokenDefs, { diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 290dc824992..55835208b33 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -118,7 +118,6 @@ type DiscordPlanOverrides = Partial< Pick< Parameters[0], | "prepareInitialSandboxCreatePolicy" - | "runProviderPreDeleteCleanup" | "upsertMessagingProviders" | "getHermesToolGatewayProviderName" > @@ -131,7 +130,6 @@ function materializeDiscordCreatePlan( return materializeSandboxCreatePlan({ ...resolved, fromRef: "/tmp/Dockerfile", - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [discordProviderName]), getHermesToolGatewayProviderName: vi.fn(), ...overrides, @@ -170,7 +168,6 @@ async function expectCredentialBindingFailure({ policyPath: "/tmp/policy.yaml", appliedPresets: [], })); - const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -179,13 +176,11 @@ async function expectCredentialBindingFailure({ fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: materializedTokenDefs, prepareInitialSandboxCreatePolicy: preparePolicy, - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders: upsertProviders, getHermesToolGatewayProviderName: vi.fn(), }), ).rejects.toThrow(expectedMessage); expect(preparePolicy).not.toHaveBeenCalled(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertProviders).not.toHaveBeenCalled(); } @@ -274,7 +269,6 @@ describe("prepareSandboxCreatePolicy", () => { fromRef: "/tmp/Dockerfile", messagingTokenDefs, messagingConfig: { WECHAT_BASE_URL: "https://idc-37.weixin.qq.com" }, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [providerName]), getHermesToolGatewayProviderName: vi.fn(), }); @@ -512,7 +506,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/Dockerfile", portableLifecycle: true, messagingTokenDefs, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => [discordProviderName]), getHermesToolGatewayProviderName: vi.fn(), }); @@ -547,7 +540,6 @@ describe("resolveSandboxCreateIntent", () => { selected: true, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(async () => {}); const upsertMessagingProviders = vi.fn(() => [discordProviderName]); await expect( @@ -560,7 +552,6 @@ describe("resolveSandboxCreateIntent", () => { credentialBindingProviders: [discordProviderName, "sandbox-missing-provider"], cleanup: cleanupPolicy, })), - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders, }, ), @@ -568,7 +559,6 @@ describe("resolveSandboxCreateIntent", () => { "Cannot create sandbox; create-time policy requires credential provider 'sandbox-missing-provider', but the sandbox create plan does not attach it.", ); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertMessagingProviders).not.toHaveBeenCalled(); }); @@ -599,7 +589,6 @@ describe("resolveSandboxCreateIntent", () => { intent, fromRef: "/tmp/Dockerfile", messagingTokenDefs: [], - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders, getHermesToolGatewayProviderName: vi.fn(), prepareInitialSandboxCreatePolicy: vi.fn(() => ({ @@ -647,7 +636,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: preparePolicy, - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(() => "sandbox-hermes-tools"), }); @@ -695,16 +683,7 @@ describe("resolveSandboxCreateIntent", () => { }); const serializedIntent = JSON.stringify(intent); const events: string[] = []; - let completeCleanup!: () => void; - let cleanupStarted!: () => void; - const pendingCleanup = new Promise((resolve) => { - completeCleanup = resolve; - }); - const started = new Promise((resolve) => { - cleanupStarted = resolve; - }); - - const materializing = materializeSandboxCreatePlan({ + const result = await materializeSandboxCreatePlan({ intent, fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: tokenDefs, @@ -716,11 +695,6 @@ describe("resolveSandboxCreateIntent", () => { events.push("disclose"); expect(policy.appliedPresets).toEqual(["telegram"]); }, - runProviderPreDeleteCleanup: async () => { - cleanupStarted(); - await pendingCleanup; - events.push("cleanup"); - }, upsertMessagingProviders: vi.fn((receivedTokenDefs, options) => { events.push("upsert"); expect(receivedTokenDefs).toEqual(tokenDefs); @@ -736,14 +710,7 @@ describe("resolveSandboxCreateIntent", () => { }, }); - try { - await Promise.race([started, materializing]); - expect(events).not.toContain("upsert"); - } finally { - completeCleanup(); - } - const result = await materializing; - expect(events).toEqual(["policy", "hermes", "disclose", "cleanup", "upsert"]); + expect(events).toEqual(["policy", "hermes", "disclose", "upsert"]); expect(result.createRequest).toEqual({ sandboxName: "sandbox", source: { reference: "/tmp/nemoclaw-build-1/Dockerfile" }, @@ -798,9 +765,6 @@ describe("resolveSandboxCreateIntent", () => { events.push("policy-cleanup"); return true; }); - const runProviderPreDeleteCleanup = vi.fn(async () => { - events.push("provider-cleanup"); - }); const upsertMessagingProviders = vi.fn(() => { events.push("upsert"); return ["sandbox-telegram-bridge"]; @@ -821,7 +785,6 @@ describe("resolveSandboxCreateIntent", () => { appliedPresets: ["telegram"], cleanup: cleanupPolicy, }), - runProviderPreDeleteCleanup, upsertMessagingProviders, getHermesToolGatewayProviderName, }), @@ -829,7 +792,6 @@ describe("resolveSandboxCreateIntent", () => { expect(events).toEqual(["policy-cleanup"]); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(runProviderPreDeleteCleanup).not.toHaveBeenCalled(); expect(upsertMessagingProviders).not.toHaveBeenCalled(); expect(getHermesToolGatewayProviderName).not.toHaveBeenCalled(); }); @@ -863,7 +825,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], }), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -934,7 +895,6 @@ describe("resolveSandboxCreateIntent", () => { fromRef: "/tmp/nemoclaw-build-1/Dockerfile", messagingTokenDefs: [], prepareInitialSandboxCreatePolicy: vi.fn(), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -968,7 +928,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1026,7 +985,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1079,7 +1037,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); @@ -1126,7 +1083,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }), @@ -1151,7 +1107,6 @@ describe("resolveSandboxCreateIntent", () => { sandboxGpuLogMessage: null, }); const cleanupPolicy = vi.fn(() => true); - const cleanupProviders = vi.fn(async () => {}); const upsertProviders = vi.fn(() => []); await expect( @@ -1167,13 +1122,11 @@ describe("resolveSandboxCreateIntent", () => { discloseInitialSandboxPolicy: () => { throw new Error("disclosure failed"); }, - runProviderPreDeleteCleanup: cleanupProviders, upsertMessagingProviders: upsertProviders, getHermesToolGatewayProviderName: vi.fn(), }), ).rejects.toThrow("disclosure failed"); expect(cleanupPolicy).toHaveBeenCalledOnce(); - expect(cleanupProviders).not.toHaveBeenCalled(); expect(upsertProviders).not.toHaveBeenCalled(); }); @@ -1191,7 +1144,6 @@ describe("resolveSandboxCreateIntent", () => { appliedPresets: [], cleanup: cleanupPolicy, })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: async () => { throw providerFailure; }, @@ -1282,7 +1234,6 @@ describe("resolveSandboxCreateIntent", () => { policyPath: "/tmp/policy.yaml", appliedPresets: [], })), - runProviderPreDeleteCleanup: vi.fn(async () => {}), upsertMessagingProviders: vi.fn(() => []), getHermesToolGatewayProviderName: vi.fn(), }); diff --git a/src/lib/onboard/sandbox-create/orchestration.test.ts b/src/lib/onboard/sandbox-create/orchestration.test.ts index 433fd5c9490..a54d5a2f7d7 100644 --- a/src/lib/onboard/sandbox-create/orchestration.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration.test.ts @@ -10,7 +10,6 @@ import { describe, expect, it, vi } from "vitest"; import * as processRecovery from "../../actions/sandbox/process-recovery"; import { createHermesCredentialEnvReconciliationRuntime } from "../../actions/sandbox/runtime/hermes-lifecycle"; import type { SandboxEntry } from "../../state/registry"; -import { runSandboxProviderPreDeleteCleanup } from "../sandbox-provider-cleanup"; import { releaseManagedStartupHoldWithRetry } from "../managed-startup/provider-root-apply"; import { assertApfCreateIntent, @@ -556,36 +555,6 @@ describe("deferred provider effect authority", () => { ]); }); - it("refuses provider cleanup when a sandbox appears after verified absence (#9833)", async () => { - let observationCount = 0; - const revalidateSandboxIdentity = vi.fn(); - const runOpenshell = vi.fn(() => ({ - pid: 1, - output: [null, "", ""], - stdout: "", - stderr: "", - status: 0, - signal: null, - })); - - await expect( - runAuthorityBoundProviderCleanup({ - sandboxName: "alpha", - observeSandbox: () => - observationCount++ === 0 - ? { state: "missing", liveIdentityFingerprint: null } - : { state: "ready", liveIdentityFingerprint: "f".repeat(64) }, - revalidateSandboxIdentity, - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, - runOpenshell, - redact: (value) => value, - tolerateMissingSandbox: true, - }), - ).rejects.toThrow(/appeared after absence was verified/u); - expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); - expect(runOpenshell).not.toHaveBeenCalled(); - }); - it("refuses every deferred provider attachment before a same-name replacement can receive credentials (#9833)", async () => { const revalidateSandboxIdentity = vi.fn(); const runOpenshell = vi.fn(() => ({ status: 0 })); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index a97bdda5c04..8c917761415 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -1503,42 +1503,18 @@ export function createProviderEffectBoundary(input: { }; } -type SandboxProviderCleanupAuthority = - | { - readonly revalidateSandboxIdentity: (operation: string) => void; - } - | { - readonly observeSandbox: () => ReturnType< - SandboxCreateOrchestrationRuntime["getSandboxRecreateObservation"] - >; - readonly revalidateSandboxIdentity: (operation: string) => void; - }; - -export async function runAuthorityBoundProviderCleanup( - input: { - readonly sandboxName: string; - readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; - readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; - readonly redact: SandboxCreateOrchestrationRuntime["redact"]; - readonly tolerateMissingSandbox?: boolean; - } & SandboxProviderCleanupAuthority, -): Promise { - const revalidateSandboxIdentity = - "observeSandbox" in input - ? (operation: string): void => { - if (input.observeSandbox().state !== "missing") { - throw new Error( - `Cannot clean up providers for sandbox '${input.sandboxName}': a sandbox with that name appeared after absence was verified while ${operation}.`, - ); - } - input.revalidateSandboxIdentity(operation); - } - : input.revalidateSandboxIdentity; +export async function runAuthorityBoundProviderCleanup(input: { + readonly sandboxName: string; + readonly runProviderPreDeleteCleanup: SandboxCreateOrchestrationRuntime["runSandboxProviderPreDeleteCleanup"]; + readonly runOpenshell: SandboxCreateOrchestrationRuntime["runOpenshell"]; + readonly redact: SandboxCreateOrchestrationRuntime["redact"]; + readonly revalidateSandboxIdentity: (operation: string) => void; +}): Promise { + const { revalidateSandboxIdentity } = input; revalidateSandboxIdentity(`cleaning up providers for sandbox '${input.sandboxName}'`); await input.runProviderPreDeleteCleanup(input.sandboxName, { runOpenshell: input.runOpenshell, redact: input.redact, - ...(input.tolerateMissingSandbox ? { tolerateMissingSandbox: true } : {}), revalidateSandboxIdentity, }); } @@ -2738,25 +2714,6 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche ) ).messagingTokenDefs; }, - runProviderPreDeleteCleanup: async (verifiedIdentityRevalidation) => { - await runAuthorityBoundProviderCleanup({ - sandboxName, - runProviderPreDeleteCleanup: runSandboxProviderPreDeleteCleanup, - runOpenshell, - redact, - tolerateMissingSandbox: true, - ...(verifiedIdentityRevalidation - ? { - revalidateSandboxIdentity: verifiedIdentityRevalidation, - } - : { - observeSandbox: () => - getSandboxRecreateObservation(sandboxName, GATEWAY_NAME), - revalidateSandboxIdentity: (operation: string) => - revalidateSandboxIdentity(false, operation), - }), - }); - }, upsertMessagingProviders: (tokenDefs, options) => applyMessagingProviders(tokenDefs, { ...options, diff --git a/src/lib/onboard/sandbox-provider-cleanup.ts b/src/lib/onboard/sandbox-provider-cleanup.ts index b383e743009..3ff7bea32b8 100644 --- a/src/lib/onboard/sandbox-provider-cleanup.ts +++ b/src/lib/onboard/sandbox-provider-cleanup.ts @@ -46,13 +46,6 @@ export type DetachSandboxProvidersDeps = { runOpenshell?: SandboxProviderRunOpenshell; providerAdapter?: OpenShellProviderAdapter; revalidateSandboxIdentity?: (operation: string) => void; - /** - * Treat OpenShell `sandbox not found` outputs as success-equivalent. Used - * by the resume-after-prune call site where the sandbox is expected to be - * gone — the call exists only to clear any stale gateway-side attachment - * record, so a missing-sandbox response means there is nothing to clean. - */ - tolerateMissingSandbox?: boolean; }; export type DeleteProviderWithRecoveryDeps = DetachSandboxProvidersDeps & { @@ -113,7 +106,6 @@ function identityRedact(input: string): string { /** * Detach owned messaging and search providers before sandbox removal. * Return failures to the lifecycle owner; it decides whether cleanup can continue. - * Missing sandboxes are tolerated only by the explicit resume-after-prune caller. */ export async function detachSandboxProviders( sandboxName: string, @@ -142,13 +134,6 @@ export async function detachSandboxProviders( } const output = result.error.message; if (result.error.kind === "command" && result.error.reason === "not_found") continue; - if ( - deps.tolerateMissingSandbox && - result.error.kind === "command" && - result.error.reason === "sandbox_not_found" - ) { - continue; - } failures.push({ name, output: output.trim() }); } return { detached, failures }; @@ -163,7 +148,6 @@ export async function runSandboxProviderPreDeleteCleanup( providerAdapter: deps.providerAdapter, runOpenshell: deps.runOpenshell, revalidateSandboxIdentity: deps.revalidateSandboxIdentity, - tolerateMissingSandbox: deps.tolerateMissingSandbox, }); if (result.failures.length === 0) return result; const warn = deps.warn ?? ((message: string) => console.warn(message)); diff --git a/src/lib/state/gateway.ts b/src/lib/state/gateway.ts index 862d8b26f47..25a35d4bf46 100644 --- a/src/lib/state/gateway.ts +++ b/src/lib/state/gateway.ts @@ -114,7 +114,10 @@ export const TERMINAL_SANDBOX_PHASES = new Set([ ]); export function isTerminalSandboxPhase(phase: string | null | undefined): boolean { - return !!phase && TERMINAL_SANDBOX_PHASES.has(phase); + return ( + !!phase && + [...TERMINAL_SANDBOX_PHASES].some((terminal) => terminal.toLowerCase() === phase.toLowerCase()) + ); } export function getSandboxStateFromOutputs( diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index fe8e9849d09..92871d0b571 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -168,6 +168,12 @@ const { createSandbox, setupMessagingChannels } = require(${onboardPath}); assert.equal(result.status, 0, result.stderr); const payload = parseStdoutJson(result.stdout); + assert.deepEqual( + payload.commands.filter((e: CommandEntry) => e.command.includes("sandbox provider detach")), + [], + "new sandbox creation should not detach providers", + ); + const providerCommands = payload.commands.filter((e: CommandEntry) => e.command.includes("provider create"), ); @@ -273,14 +279,8 @@ const { createSandbox, setupMessagingChannels } = require(${onboardPath}); ); const envString = JSON.stringify(createCommand.env); - assert.ok( - !envString.includes("test-discord-token-value"), - "Discord token value must not leak into sandbox env", - ); - assert.ok( - !envString.includes("xoxb-test-slack-token-value"), - "Slack bot token value must not leak into sandbox spawn env", - ); + assert.ok(!envString.includes("test-discord-token-value"), "Discord token in sandbox env"); + assert.ok(!envString.includes("xoxb-test-slack-token-value"), "Slack bot token in env"); assert.ok( !envString.includes("xapp-test-slack-app-token-value"), "Slack app token value must not leak into sandbox spawn env", diff --git a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts index e38b4b6ea69..e77d7f1f6c8 100644 --- a/test/runtime/sandbox/sandbox-provider-cleanup.test.ts +++ b/test/runtime/sandbox/sandbox-provider-cleanup.test.ts @@ -182,7 +182,7 @@ describe("detachSandboxProviders", () => { ]); }); - it("retains a detach failure for a different missing sandbox even when absence is tolerated", async () => { + it("retains a detach failure for a different missing sandbox", async () => { const { runOpenshell } = buildRunOpenshell( new Map([ [ @@ -196,7 +196,6 @@ describe("detachSandboxProviders", () => { ); const result = await detachSandboxProviders("phantom", { runOpenshell, - tolerateMissingSandbox: true, }); expect(result.failures).toEqual([ { @@ -206,45 +205,6 @@ describe("detachSandboxProviders", () => { ]); }); - it("tolerates sandbox-not-found when tolerateMissingSandbox is set (opportunistic call)", async () => { - const responses = new Map([ - [ - "sandbox provider detach phantom phantom-telegram-bridge", - { status: 1, stderr: "Error: status: NotFound, sandbox 'phantom' not found" }, - ], - ]); - const { runOpenshell } = buildRunOpenshell(responses); - - const result = await detachSandboxProviders("phantom", { - runOpenshell, - tolerateMissingSandbox: true, - }); - - expect(result.failures).toEqual([]); - }); - - it("suppresses output for tolerated missing-sandbox detach probes", async () => { - const { runOpenshell } = buildRunOpenshell(new Map(), { - status: 1, - stderr: "Error: status: NotFound, sandbox 'phantom' not found", - }); - - const result = await detachSandboxProviders("phantom", { - runOpenshell, - tolerateMissingSandbox: true, - }); - - expect(result.failures).toEqual([]); - expect(runOpenshell).toHaveBeenCalledTimes(SANDBOX_PROVIDER_SUFFIXES.length); - runOpenshell.mock.calls.forEach(([, opts]) => { - expect(opts).toMatchObject({ - ignoreError: true, - suppressOutput: true, - stdio: ["ignore", "pipe", "pipe"], - }); - }); - }); - it("collects non-tolerated failures without aborting the loop", async () => { const responses = new Map([ [ diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index cdc6cb7256f..ca94625f81e 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -621,6 +621,9 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne .spyOn(openShellSdk, "connectManagedOpenShellSdk") .mockImplementation(async (...args: unknown[]) => { const target = args[0] as { kind: string; gatewayName?: string }; + let sandboxPhase = String( + options.sandboxGetPhase ?? (options.registryEntry?.stopped === true ? "Stopped" : "Ready"), + ).toLowerCase(); return { raw: { startSandbox: async ({ name }: { name: string }) => { @@ -639,6 +642,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne code: String(completion.status ?? "unknown"), }); } + sandboxPhase = "ready"; return { sandbox: { metadata: { id: "alpha-sandbox-id" } } }; }, stopSandbox: async () => ({ sandbox: { metadata: { id: "alpha-sandbox-id" } } }), @@ -646,10 +650,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne sandbox: { get: async () => ({ id: "alpha-sandbox-id", - phase: String( - options.sandboxGetPhase ?? - (options.registryEntry?.stopped === true ? "Stopped" : "Ready"), - ).toLowerCase(), + phase: sandboxPhase, }), waitReady: async () => ({ id: "alpha-sandbox-id", phase: "ready" }), },