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
199 changes: 193 additions & 6 deletions src/lib/onboard/sandbox-create/provider-publication.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@
import { describe, expect, it, vi } from "vitest";

import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter";
import { endpointlessProviderProfilePath } from "../../adapters/openshell/provider-profile";
import { REPOSITORY_ROOT } from "../../core/repository-root";
import { nativeNvidiaProviderProfilePath } from "../../inference/native-nvidia";
import {
messagingCredentialProviderProfilePath,
MESSAGING_CREDENTIAL_PROVIDER_TYPE,
} from "../../messaging/provider-profile";
import {
publishAttachedProvidersBeforeDockerSandboxCreation,
validateAttachedMessagingProvidersBeforeSandboxCreation,
validateAttachedOwnedProfilesBeforeSandboxCreation,
} from "./provider-publication";
import { createProviderEffectBoundary, runSandboxCreateWithProviderEffects } from "./orchestration";

Expand Down Expand Up @@ -105,9 +108,27 @@ async function prepareProviders(
}

describe("sandbox provider preparation", () => {
it.each(["brave", "google-chat-bridge", "generic"])(
it.each([
["brave", true, expect.anything()],
["google-chat-bridge", true, expect.anything()],
[
"langfuse-hermes-v1",
true,
{
target,
profilePath: endpointlessProviderProfilePath(REPOSITORY_ROOT, "langfuse-hermes-v1"),
},
],
[
"nemoclaw-nvidia-inference-v1",
true,
{ target, profilePath: nativeNvidiaProviderProfilePath() },
],
["generic", false, undefined],
["operator-custom-v1", false, undefined],
] as const)(
"checks an attached %s provider only when its profile is NemoClaw-owned",
async (type) => {
async (type, owned, profileImport) => {
const warningCheck = vi.fn();
const adapter = Object.assign(
typedProviderAdapter({
Expand Down Expand Up @@ -150,14 +171,180 @@ describe("sandbox provider preparation", () => {
route: "none",
revalidateSandboxIdentity: vi.fn(),
});
expect(adapter.importProviderProfile).toHaveBeenCalledTimes(type === "generic" ? 0 : 1);
expect(warningCheck).toHaveBeenCalledTimes(type === "generic" ? 0 : 1);
expect(warningCheck.mock.calls[0] ?? null).toEqual(
type === "generic" ? null : [{ target }, [type]],
expect(vi.mocked(adapter.importProviderProfile).mock.calls).toEqual(
owned ? [[profileImport]] : [],
);
expect(warningCheck).toHaveBeenCalledTimes(owned ? 1 : 0);
expect(warningCheck.mock.calls[0] ?? null).toEqual(owned ? [{ target }, [type]] : null);
},
);

it.each(
["langfuse-hermes-v1", "nemoclaw-nvidia-inference-v1"].flatMap((type) =>
(
[
["profile_incompatible", "Resolve the conflicting same-ID profile"],
["not_found", "resolve the missing resource"],
["failed", "resolve the OpenShell command failure"],
] as const
).map(([reason, recovery]) => ({
type,
reason,
recovery,
})),
),
)(
"blocks $type on $reason and verifies the profile on retry (#13345)",
async ({ type, reason, recovery }) => {
const secret = "unrecognized-private-provider-value";
const adapter = typedProviderAdapter({
getProvider: vi.fn(async () => ({
ok: true as const,
value: { name: "extra-provider", type, credentialKeys: ["TOKEN"], configKeys: [] },
})),
importProviderProfile: vi
.fn<OpenShellProviderAdapter["importProviderProfile"]>()
.mockResolvedValueOnce({
ok: false,
error: { kind: "command", reason, message: `command output: ${secret}` },
})
.mockResolvedValue({ ok: true }),
});
const harness = createHarness(adapter);
const boundary = createProviderEffectBoundary({
deferred: false,
sandboxName: "alpha",
gatewayName: "nemoclaw",
preparationInput: publicationInput({
messagingProviders: [],
messagingProviderRequests: [],
extraProviders: ["extra-provider"],
directCreateProviderNames: ["extra-provider"],
}),
preparationDeps: harness.deps,
runVerifiedSandboxCreateEffects: null,
activateDeferredProviderEffects: null,
revalidateSandboxIdentityBeforeCreate: vi.fn(),
});

const failure = await boundary.validateBeforeCreate().catch((error: unknown) => error);
expect(failure).toBeInstanceOf(Error);
expect((failure as Error).message).toContain(
`Could not verify provider profile '${type}' before sandbox creation.`,
);
expect((failure as Error).message).toContain(`Profile verify failed (command/${reason}).`);
expect((failure as Error).message).toContain(recovery);
expect((failure as Error).message).not.toContain(secret);
expect((failure as Error).cause).toBeUndefined();
expect(harness.cleanupCreateSources).toHaveBeenCalledOnce();
expect(adapter.createProvider).not.toHaveBeenCalled();
expect(adapter.updateProvider).not.toHaveBeenCalled();
expect(adapter.attachProvider).not.toHaveBeenCalled();
expect(harness.runOpenshell).not.toHaveBeenCalled();

await expect(boundary.validateBeforeCreate()).resolves.toBeUndefined();
expect(adapter.importProviderProfile).toHaveBeenCalledTimes(2);
},
);

it.each([
["validation", "read", "Restore the bundled provider profile"],
["validation", "inspect", "Check the selected gateway configuration"],
["authentication", "inspect", "Restore authentication"],
["schema", "verify", "supported OpenShell CLI and gateway versions"],
["timeout", "import", "Confirm the selected OpenShell gateway is available"],
] as const)("reports safe %s recovery during profile %s", async (kind, operation, recovery) => {
const secret = "unrecognized-private-provider-value";
const harness = createHarness(
typedProviderAdapter({
getProvider: vi.fn(async () => ({
ok: true as const,
value: {
name: "extra-provider",
type: "langfuse-hermes-v1",
credentialKeys: [],
configKeys: [],
},
})),
importProviderProfile: vi.fn(async () => ({
ok: false as const,
error: { kind, message: secret },
operation,
})),
}),
);
const failure = await validateAttachedOwnedProfilesBeforeSandboxCreation(
publicationInput({
messagingProviders: [],
messagingProviderRequests: [],
extraProviders: ["extra-provider"],
}),
harness.deps,
).catch((error: unknown) => error);

expect(failure).toBeInstanceOf(Error);
expect((failure as Error).message).toContain(`Profile ${operation} failed (${kind}).`);
expect((failure as Error).message).toContain(recovery);
expect((failure as Error).message).not.toContain(secret);
expect((failure as Error).cause).toBeUndefined();
expect(harness.cleanupCreateSources).toHaveBeenCalledOnce();
expect(harness.runOpenshell).not.toHaveBeenCalled();
});

it("preserves profile recovery and cleanup failures without exposing adapter output", async () => {
const secret = "unrecognized-private-provider-value";
const cleanupFailure = new Error("Temporary sources could not be removed.");
const harness = createHarness(
typedProviderAdapter({
getProvider: vi.fn(async () => ({
ok: true as const,
value: {
name: "extra-provider",
type: "nemoclaw-nvidia-inference-v1",
credentialKeys: [],
configKeys: [],
},
})),
importProviderProfile: vi.fn(async () => ({
ok: false as const,
error: {
kind: "transport" as const,
reason: "connection_loss" as const,
message: secret,
},
operation: "import" as const,
})),
}),
vi.fn(() => {
throw cleanupFailure;
}),
);
const failure = await validateAttachedOwnedProfilesBeforeSandboxCreation(
publicationInput({
messagingProviders: [],
messagingProviderRequests: [],
extraProviders: ["extra-provider"],
}),
harness.deps,
).catch((error: unknown) => error);

expect(failure).toBeInstanceOf(AggregateError);
expect((failure as AggregateError).message).toContain(
"Profile import failed (transport/connection_loss).",
);
expect((failure as AggregateError).message).toContain(
"Check the OpenShell CLI and the selected gateway's identity and connectivity",
);
expect((failure as AggregateError).message).not.toContain(secret);
expect((failure as AggregateError).errors).toEqual([
expect.objectContaining({ message: expect.not.stringContaining(secret) }),
cleanupFailure,
]);
expect((failure as AggregateError).errors[0].cause).toBeUndefined();
expect(harness.cleanupCreateSources).toHaveBeenCalledOnce();
expect(harness.runOpenshell).not.toHaveBeenCalled();
});

it("stops direct create when an attached provider cannot be inspected", async () => {
const adapter = typedProviderAdapter({
getProvider: vi.fn(async () => ({
Expand Down
53 changes: 50 additions & 3 deletions src/lib/onboard/sandbox-create/provider-publication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,21 @@ import type { SandboxCreateOrchestrationRuntime } from "../../onboard";
import type {
OpenShellProviderAdapter,
OpenShellProviderError,
OpenShellProviderProfileMutationResult,
} from "../../adapters/openshell/provider-adapter";
import {
createCliOpenShellProviderAdapter,
type CliOpenShellProviderAdapter,
} from "../../adapters/openshell/provider-adapter-cli";
import type { OpenShellGatewayEndpointEnvironment } from "../../adapters/openshell/gateway-scope";
import { endpointlessProviderProfilePath } from "../../adapters/openshell/provider-profile";
import { namedOpenShellGateway } from "../../adapters/openshell/sandbox-observer";
import { REPOSITORY_ROOT } from "../../core/repository-root";
import { messagingProviderProfileForType } from "../../messaging/applier/provider-application";
import {
ensureNativeNvidiaProviderAttached,
nativeNvidiaProviderProfilePath,
NVIDIA_HOSTED_NATIVE_PROFILE_ID,
NVIDIA_HOSTED_NATIVE_PROVIDER,
requireNativeNvidiaProviderProfileBoundary,
} from "../../inference/native-nvidia";
Expand Down Expand Up @@ -77,7 +81,38 @@ function expectedMessagingBindings(input: ProviderPreparationInput) {
);
}

/** Recheck only profiles already owned by messaging or web-search setup. */
function ownedProfileFailureDetail(
failure: Extract<OpenShellProviderProfileMutationResult, { ok: false }>,
): string {
const { error, operation = "verify" } = failure;
const classification = "reason" in error ? `${error.kind}/${error.reason}` : error.kind;
const guidance = (() => {
if (error.kind === "command" && error.reason === "profile_incompatible") {
return "Resolve the conflicting same-ID profile on the selected gateway, then retry.";
}
if (error.kind === "command" && error.reason === "not_found") {
return "Inspect the selected gateway's provider profile and resolve the missing resource, then retry.";
}
if (error.kind === "validation" && operation === "read") {
return "Restore the bundled provider profile from this NemoClaw release, then retry.";
}
return {
authentication: "Restore authentication for the selected OpenShell gateway, then retry.",
schema:
"Use this NemoClaw release's supported OpenShell CLI and gateway versions, then retry.",
timeout: "Confirm the selected OpenShell gateway is available, then retry verification.",
validation:
"Check the selected gateway configuration and provider-profile inputs, then retry.",
transport:
"Check the OpenShell CLI and the selected gateway's identity and connectivity, then retry.",
command:
"Inspect the selected gateway's provider profile and resolve the OpenShell command failure, then retry.",
}[error.kind];
})();
return `Profile ${operation} failed (${classification}). ${guidance}`;
}

/** Recheck known owned profiles before binding previously registered providers. */
export async function validateAttachedOwnedProfilesBeforeSandboxCreation(
input: ProviderPreparationInput,
deps: ProviderPreparationDeps,
Expand Down Expand Up @@ -109,11 +144,23 @@ export async function validateAttachedOwnedProfilesBeforeSandboxCreation(
);
}
if (observed.value.type === "generic") continue;
const directProfile = messagingProviderProfileForType(
let directProfile = messagingProviderProfileForType(
REPOSITORY_ROOT,
observed.value.type,
undefined,
);
if (observed.value.type === "langfuse-hermes-v1") {
directProfile = {
profileType: observed.value.type,
profilePath: endpointlessProviderProfilePath(REPOSITORY_ROOT, observed.value.type),
};
}
if (observed.value.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID) {
directProfile = {
profileType: NVIDIA_HOSTED_NATIVE_PROFILE_ID,
profilePath: nativeNvidiaProviderProfilePath(),
};
}
if (!directProfile) {
bridgeProfiles ??= new Map(
listMessagingBridgeProfiles({ root: REPOSITORY_ROOT }).map((entry) => [
Expand All @@ -137,7 +184,7 @@ export async function validateAttachedOwnedProfilesBeforeSandboxCreation(
if (!imported.ok) {
throwAfterCleanup(
deps,
`Could not verify provider profile '${profile.profileType}' before sandbox creation.`,
`Could not verify provider profile '${profile.profileType}' before sandbox creation. ${ownedProfileFailureDetail(imported)}`,
);
}
profileIds.add(profile.profileType);
Expand Down