diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index c806ab66b06..716dec32ec9 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -8,7 +8,7 @@ "test/generation/generate-openclaw-config.test.ts": 1906, "test/installer-integration/install-preflight.test.ts": 3025, "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 4671, - "test/onboarding/onboard-messaging.test.ts": 2021, + "test/onboarding/onboard-messaging.test.ts": 2016, "test/onboarding/onboard-selection.test.ts": 4176 } } diff --git a/src/lib/onboard/initial-policy.ts b/src/lib/onboard/initial-policy.ts index 4e05baef0c2..341a335c110 100644 --- a/src/lib/onboard/initial-policy.ts +++ b/src/lib/onboard/initial-policy.ts @@ -36,6 +36,8 @@ import { isPortableExperimentalProfile } from "./experimental/portable-profile"; export type InitialSandboxPolicy = { policyPath: string; appliedPresets: string[]; + /** Exact provider names referenced by credential-bound endpoints in this policy. */ + credentialBindingProviders?: string[]; sourceBytes?: Buffer; cleanup?: () => boolean; cleanupExact?: () => boolean; @@ -361,6 +363,32 @@ export function getNetworkPolicyNames(policyContent: string): Set | null } } +function getCredentialBindingProviders(policyContent: string): string[] { + const parsed = YAML.parse(policyContent); + if (!isObjectRecord(parsed) || !isObjectRecord(parsed.network_policies)) return []; + + const providers = new Set(); + for (const policy of Object.values(parsed.network_policies)) { + if (!isObjectRecord(policy) || !Array.isArray(policy.endpoints)) continue; + for (const endpoint of policy.endpoints) { + if (!isObjectRecord(endpoint) || endpoint.credential_binding === undefined) continue; + const binding = endpoint.credential_binding; + if ( + !isObjectRecord(binding) || + typeof binding.provider !== "string" || + binding.provider.length === 0 || + binding.provider.trim() !== binding.provider + ) { + throw new Error( + "Cannot prepare sandbox create policy; a credential binding has no exact provider name.", + ); + } + providers.add(binding.provider); + } + } + return [...providers]; +} + function filterHermesInactiveMessagingPolicies( policyContent: string, activeMessagingChannels: string[], @@ -444,12 +472,16 @@ function resolveInitialSandboxCreatePolicy( .every(Boolean) : undefined; const exactCleanupResult = () => (exactCleanup ? { cleanupExact: buildExactCleanup() } : {}); - const result = (appliedPresets: string[]): InitialSandboxPolicy => ({ - ...effectivePolicy, - appliedPresets, - cleanup: buildCleanup(), - ...exactCleanupResult(), - }); + const result = (appliedPresets: string[]): InitialSandboxPolicy => { + const credentialBindingProviders = getCredentialBindingProviders(basePolicy); + return { + ...effectivePolicy, + appliedPresets, + ...(credentialBindingProviders.length > 0 ? { credentialBindingProviders } : {}), + cleanup: buildCleanup(), + ...exactCleanupResult(), + }; + }; const cleanupOnError = () => { for (const cleanup of [...cleanupFns].reverse()) { try { diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 1e20b20625e..3f225114d0c 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -254,21 +254,17 @@ export function computeSetupPresetSuggestions( const activeMessagingPresets = Array.isArray(enabledChannels) ? new Set(allMessagingChannelPolicyPresets(enabledChannels)) : null; - const hermesAgent = typeof agent === "string" && agent.trim().toLowerCase() === "hermes"; const supportOptions = { webSearchSupported: options.webSearchSupported }; const suggestions = deps.tiers .resolveTierPresets(tierName) .map((preset) => preset.name) .filter((name) => setupPolicyPresetAppliesToAgent(name, agent)) - // Hermes Discord egress names a sandbox-scoped credential provider. An - // open tier may contain the preset, but OpenShell rejects it unless the - // channel is active and its provider is attached to the sandbox. + // Discord egress names a sandbox-scoped credential provider. An open tier + // may contain the preset, but OpenShell rejects it unless the channel is + // active and its provider is attached to the sandbox. .filter( (name) => - !hermesAgent || - name !== "discord" || - activeMessagingPresets === null || - activeMessagingPresets.has(name), + name !== "discord" || activeMessagingPresets === null || activeMessagingPresets.has(name), ) .filter( (name) => diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index 2d34fe67553..07d28b1db0a 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -11,6 +11,7 @@ import { resolveSandboxCreateMessagingProviderRequests, } from "./sandbox-create-intent"; import type { SandboxCreateIntent } from "./sandbox-create-intent-types"; +import { getActiveChannelsFromPlan } from "./messaging-plan-session"; import { resolveSandboxCreatePolicyTier } from "./sandbox-create-plan"; import { selectHermesPortableExtraProviderPlan, @@ -67,6 +68,22 @@ export function createSandboxCreateIntentResolver< return deps.filterEnabledChannelsByAgent(enabledChannels ? [...enabledChannels] : null, agent); } + function resolveSelectedChannels( + input: Pick< + CompleteSandboxCreateIntentInput, + "sandboxName" | "enabledChannels" | "agent" + >, + ): string[] | null { + const selected = filterEnabledChannels(input.enabledChannels, input.agent); + if (selected !== null) return selected; + const stagedPlan = deps.messagingPreflightDeps.readMessagingPlanFromEnv(); + if (stagedPlan?.sandboxName === input.sandboxName) { + return filterEnabledChannels(getActiveChannelsFromPlan(stagedPlan), input.agent) ?? []; + } + const agentName = input.agent?.name?.trim().toLowerCase(); + return agentName && agentName !== "openclaw" ? null : []; + } + async function prepareMessagingCapabilities( input: Pick< CompleteSandboxCreateIntentInput, @@ -91,7 +108,7 @@ export function createSandboxCreateIntentResolver< const result = await prepareSandboxMessagingPreflight( { channels: deps.channels, - enabledChannels: filterEnabledChannels(input.enabledChannels, input.agent), + enabledChannels: resolveSelectedChannels(input), sandboxName: input.sandboxName, agentName: input.agent?.name ?? "openclaw", requireExactProviderBinding: @@ -133,7 +150,7 @@ export function createSandboxCreateIntentResolver< inferenceProvider: input.inferenceProvider, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, - enabledChannels: filterEnabledChannels(input.enabledChannels, input.agent), + enabledChannels: resolveSelectedChannels(input), disabledChannelNames: messaging.disabledChannelNames, messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( messaging.messagingTokenDefs, diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index d7372fd70ba..eede9fae3e3 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -22,29 +22,31 @@ function filterEnabledChannelNames( function filterMessagingProviderRequestsByEnabledChannel( requests: readonly SandboxCreateMessagingProviderRequest[], + selectedChannelNames: ReadonlySet | null, disabledChannelNames: ReadonlySet, ): SandboxCreateMessagingProviderRequest[] { - return requests.filter(({ channel }) => !channel || !disabledChannelNames.has(channel)); + return requests.filter( + ({ channel }) => + !channel || + ((!selectedChannelNames || selectedChannelNames.has(channel)) && + !disabledChannelNames.has(channel)), + ); } -function resolveTokenProviderChannelMap( +export function filterMessagingProvidersForSandboxCreate( + providerNames: readonly string[], requests: readonly SandboxCreateMessagingProviderRequest[], -): Map { + activeChannelNames: Iterable, + disabledChannelNames: Iterable, +): string[] { const providerChannels = new Map(); for (const { channel, name } of requests) { if (channel) providerChannels.set(name, channel); } - return providerChannels; -} - -function filterMessagingProvidersByEnabledChannel( - providerNames: string[], - providerChannels: ReadonlyMap, - disabledChannelNames: ReadonlySet, -): string[] { - return providerNames.filter((providerName) => { + const eligibleChannels = new Set([...activeChannelNames, ...disabledChannelNames]); + return [...new Set(providerNames)].filter((providerName) => { const channel = providerChannels.get(providerName); - return !channel || !disabledChannelNames.has(channel); + return !channel || eligibleChannels.has(channel); }); } @@ -64,6 +66,7 @@ function resolveActiveMessagingChannels({ | "primaryMessagingCredentialEnvKeys" | "reusableMessagingChannels" >): string[] { + const selectedChannelNames = enabledChannels == null ? null : new Set(enabledChannels); const primaryCredentialEnvKeys = new Set(primaryMessagingCredentialEnvKeys); const qrSelectedChannels = resolveQrSelectedChannels( [...channels], @@ -76,9 +79,15 @@ function resolveActiveMessagingChannels({ ...messagingProviderRequests .filter(({ credentialConfigured }) => credentialConfigured) .flatMap(({ channel, envKey }) => { - return channel && primaryCredentialEnvKeys.has(envKey) ? [channel] : []; + return channel && + (!selectedChannelNames || selectedChannelNames.has(channel)) && + primaryCredentialEnvKeys.has(envKey) + ? [channel] + : []; }), - ...reusableMessagingChannels, + ...reusableMessagingChannels.filter( + (channel) => !selectedChannelNames || selectedChannelNames.has(channel), + ), ...qrSelectedChannels, ]), ], @@ -153,11 +162,12 @@ export function resolveSandboxCreateIntent({ policyTier, baselineExclusions = [], }: ResolveSandboxCreateIntentInput): SandboxCreateIntent { + const selectedChannelNames = enabledChannels == null ? null : new Set(enabledChannels); const enabledMessagingProviderRequests = filterMessagingProviderRequestsByEnabledChannel( messagingProviderRequests, + selectedChannelNames, disabledChannelNames, ); - const providerChannels = resolveTokenProviderChannelMap(messagingProviderRequests); const activeMessagingChannels = resolveActiveMessagingChannels({ channels, disabledChannelNames, @@ -166,9 +176,10 @@ export function resolveSandboxCreateIntent({ primaryMessagingCredentialEnvKeys, reusableMessagingChannels, }); - const enabledReusableMessagingProviders = filterMessagingProvidersByEnabledChannel( - [...new Set(reusableMessagingProviders)], - providerChannels, + const enabledReusableMessagingProviders = filterMessagingProvidersForSandboxCreate( + reusableMessagingProviders, + messagingProviderRequests, + activeMessagingChannels, disabledChannelNames, ); diff --git a/src/lib/onboard/sandbox-create-plan-materialization.ts b/src/lib/onboard/sandbox-create-plan-materialization.ts index b7d06179b96..7f5886aaddf 100644 --- a/src/lib/onboard/sandbox-create-plan-materialization.ts +++ b/src/lib/onboard/sandbox-create-plan-materialization.ts @@ -4,6 +4,7 @@ import type { InitialSandboxPolicy } from "./initial-policy"; import type { SandboxPolicyAuthority } from "../adapters/openshell/policy-authority"; import type { MessagingTokenDef } from "./messaging-prep"; +import { filterMessagingProvidersForSandboxCreate } from "./sandbox-create-intent"; import type { MaterializeSandboxCreatePlanInput, SandboxCreateIntent, @@ -174,8 +175,10 @@ export function validateSandboxCreateIntentBindings( messagingTokenDefs: readonly MessagingTokenDef[], ): MessagingTokenDef[] { const disabledChannelNames = new Set(intent.disabledChannelNames); + const activeChannelNames = new Set(intent.policy.activeMessagingChannels); const enabledRequests = intent.messagingProviderRequests.filter( - ({ channel }) => !channel || !disabledChannelNames.has(channel), + ({ channel }) => + !channel || (activeChannelNames.has(channel) && !disabledChannelNames.has(channel)), ); const intentRequestKeys = new Set( intent.messagingProviderRequests.map(messagingProviderRequestKey), @@ -221,25 +224,32 @@ export function validateSandboxCreateIntentBindings( }); } -function resolveProviderChannelMap( - requests: readonly SandboxCreateMessagingProviderRequest[], -): Map { - const providerChannels = new Map(); - for (const { channel, name } of requests) { - if (channel) providerChannels.set(name, channel); +function assertCredentialBindingProvidersAttached( + policy: InitialSandboxPolicy, + createProviders: ReadonlySet, +): void { + for (const provider of policy.credentialBindingProviders ?? []) { + if (createProviders.has(provider)) continue; + policy.cleanup?.(); + throw new Error( + `Cannot create sandbox; create-time policy requires credential provider '${provider}', but the sandbox create plan does not attach it.`, + ); } - return providerChannels; } -function filterDisabledMessagingProviders( - providerNames: string[], - providerChannels: ReadonlyMap, - disabledChannelNames: ReadonlySet, -): string[] { - return providerNames.filter((providerName) => { - const channel = providerChannels.get(providerName); - return !channel || !disabledChannelNames.has(channel); - }); +function buildCreateProviderSet( + intent: SandboxCreateIntent, + messagingProviders: readonly string[], + hermesToolGatewayProvider: string | null, +): Set { + return new Set( + [ + intent.inferenceProvider, + ...messagingProviders, + hermesToolGatewayProvider, + ...intent.extraProviders, + ].filter((provider): provider is string => Boolean(provider)), + ); } /** Materialize policy, route metadata, resources, and providers from a secretless intent. */ @@ -276,14 +286,6 @@ export function materializeSandboxCreatePlan({ intent.gpuRoutePlan, prepareInitialSandboxCreatePolicy, ); - if (policyAuthority === "nemoclaw-managed") { - try { - discloseInitialSandboxPolicy?.(initialSandboxPolicy); - } catch (error) { - initialSandboxPolicy.cleanup?.(); - throw error; - } - } const createArgs = [ "--from", fromRef, @@ -297,34 +299,59 @@ export function materializeSandboxCreatePlan({ ...intent.resourceCreateArgs, ]; + const hermesToolGatewayProvider = + intent.hermesToolGateways.length > 0 + ? getHermesToolGatewayProviderName(intent.sandboxName) + : null; + const plannedMessagingProviders = filterMessagingProvidersForSandboxCreate( + [ + ...enabledMessagingTokenDefs.filter(({ token }) => Boolean(token)).map(({ name }) => name), + ...intent.reusableMessagingProviders, + ], + intent.messagingProviderRequests, + intent.policy.activeMessagingChannels, + intent.disabledChannelNames, + ); + if (policyAuthority === "nemoclaw-managed") { + assertCredentialBindingProvidersAttached( + initialSandboxPolicy, + buildCreateProviderSet(intent, plannedMessagingProviders, hermesToolGatewayProvider), + ); + try { + discloseInitialSandboxPolicy?.(initialSandboxPolicy); + } catch (error) { + initialSandboxPolicy.cleanup?.(); + throw error; + } + } + runProviderPreDeleteCleanup(); - const providerChannels = resolveProviderChannelMap(intent.messagingProviderRequests); - const messagingProviders = filterDisabledMessagingProviders( + const messagingProviders = filterMessagingProvidersForSandboxCreate( [ - ...new Set([ - ...upsertMessagingProviders(enabledMessagingTokenDefs, { - replaceExisting: true, - allowedSandboxes: [intent.sandboxName], - }), - ...intent.reusableMessagingProviders, - ]), + ...upsertMessagingProviders(enabledMessagingTokenDefs, { + replaceExisting: true, + allowedSandboxes: [intent.sandboxName], + }), + ...intent.reusableMessagingProviders, ], - providerChannels, - new Set(intent.disabledChannelNames), + intent.messagingProviderRequests, + intent.policy.activeMessagingChannels, + intent.disabledChannelNames, + ); + const createProviders = buildCreateProviderSet( + intent, + messagingProviders, + hermesToolGatewayProvider, ); - const createProviders = new Set(); - if (intent.inferenceProvider) createProviders.add(intent.inferenceProvider); - for (const provider of messagingProviders) createProviders.add(provider); - if (intent.hermesToolGateways.length > 0) { - createProviders.add(getHermesToolGatewayProviderName(intent.sandboxName)); + if (policyAuthority === "nemoclaw-managed") { + assertCredentialBindingProvidersAttached(initialSandboxPolicy, createProviders); } - for (const provider of intent.extraProviders) createProviders.add(provider); for (const provider of createProviders) { createArgs.push("--provider", provider); } return { - activeMessagingChannels: [...intent.activeMessagingChannels], + activeMessagingChannels: [...intent.policy.activeMessagingChannels], initialSandboxPolicy, policyTier: intent.policy.options.policyTier, policyAuthority, @@ -352,7 +379,7 @@ export function materializeHermesPortableCreatePlan(input: { intent.policy.options.agentName !== "hermes" || !["none", "native-only"].includes(intent.gpuRoutePlan) || (intent.hostMounts?.length ?? 0) > 0 || - intent.activeMessagingChannels.length > 0 || + intent.policy.activeMessagingChannels.length > 0 || intent.messagingProviderRequests.length > 0 || intent.reusableMessagingProviders.length > 0 || intent.extraProviders.length > 0 || diff --git a/src/lib/onboard/sandbox-create-plan.test.ts b/src/lib/onboard/sandbox-create-plan.test.ts index 50a9a8f1b70..4f1b4424677 100644 --- a/src/lib/onboard/sandbox-create-plan.test.ts +++ b/src/lib/onboard/sandbox-create-plan.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { afterEach, describe, expect, it, vi } from "vitest"; +import { MESSAGING_CREDENTIAL_PROVIDER_TYPE } from "../messaging/provider-profile"; import type { MessagingTokenDef } from "./messaging-prep"; import { materializeHermesPortableCreatePlan } from "./sandbox-create-plan-materialization"; import { @@ -34,6 +35,13 @@ afterEach(() => { }); const channels = [ + { + name: "discord", + envKey: "DISCORD_BOT_TOKEN", + label: "Discord", + description: "Discord", + help: "Discord", + }, { name: "telegram", envKey: "TELEGRAM_BOT_TOKEN", @@ -58,6 +66,66 @@ const channels = [ }, ]; +const discordProviderName = "sandbox-discord-bridge"; + +function resolveDiscordCreateIntent(input: { selected: boolean; reusable?: boolean }) { + const messagingTokenDefs: MessagingTokenDef[] = [ + { + name: discordProviderName, + envKey: "DISCORD_BOT_TOKEN", + token: "discord-secret", + providerType: MESSAGING_CREDENTIAL_PROVIDER_TYPE, + }, + ]; + const intent = resolveSandboxCreateIntent({ + basePolicyPath: "nemoclaw-blueprint/policies/openclaw-sandbox.yaml", + sandboxName: "sandbox", + channels, + enabledChannels: input.selected ? ["discord"] : [], + disabledChannelNames: new Set(), + messagingProviderRequests: resolveSandboxCreateMessagingProviderRequests( + messagingTokenDefs, + () => "discord", + ), + primaryMessagingCredentialEnvKeys: ["DISCORD_BOT_TOKEN"], + reusableMessagingChannels: input.reusable ? ["discord"] : [], + reusableMessagingProviders: input.reusable ? [discordProviderName] : [], + hermesToolGateways: [], + sandboxGpuConfig: disabledSandboxGpuConfig, + gpuCreateArgs: [], + gpuRoutePlan: "none", + sandboxGpuLogMessage: null, + agentName: "openclaw", + policyTier: "balanced", + }); + return { intent, messagingTokenDefs }; +} + +type DiscordPlanOverrides = Partial< + Pick< + Parameters[0], + | "prepareInitialSandboxCreatePolicy" + | "runProviderPreDeleteCleanup" + | "upsertMessagingProviders" + | "getHermesToolGatewayProviderName" + > +>; + +function materializeDiscordCreatePlan( + resolved: ReturnType, + overrides: DiscordPlanOverrides = {}, +) { + return materializeSandboxCreatePlan({ + ...resolved, + fromRef: "/tmp/Dockerfile", + policyAuthority: "nemoclaw-managed", + runProviderPreDeleteCleanup: vi.fn(), + upsertMessagingProviders: vi.fn(() => [discordProviderName]), + getHermesToolGatewayProviderName: vi.fn(), + ...overrides, + }); +} + function expectCredentialBindingFailure({ expectedMessage, materializedTokenDefs, @@ -208,12 +276,15 @@ describe("resolveSandboxCreateIntent", () => { const second = resolveSandboxCreateIntent(input); expect(first).toEqual(second); - expect(first.activeMessagingChannels).toEqual(["telegram", "discord", "whatsapp"]); + expect(first.activeMessagingChannels).toEqual(["telegram", "whatsapp"]); expect(first.messagingProviderRequests.map(({ name }) => name)).toEqual([ "sandbox-telegram-bridge", "sandbox-slack-bridge", ]); - expect(first.reusableMessagingProviders).toEqual(["sandbox-existing-discord"]); + expect(first.reusableMessagingProviders).toEqual([ + "sandbox-existing-discord", + "sandbox-slack-bridge", + ]); expect(first.extraProviders).toEqual(["custom-provider"]); expect(first.staleExtraProviders).toEqual(["stale-provider"]); expect(first.resourceCreateArgs).toEqual(["--cpu", "4", "--memory", "16Gi"]); @@ -221,7 +292,7 @@ describe("resolveSandboxCreateIntent", () => { expect(first.sandboxGpuDevice).toBe("nvidia.com/gpu=0"); expect(first.policy).toEqual({ basePolicyPath: "/repo/policy.yaml", - activeMessagingChannels: ["telegram", "discord", "whatsapp"], + activeMessagingChannels: ["telegram", "whatsapp"], options: { directGpu: true, hostGpuAvailable: true, @@ -244,6 +315,95 @@ describe("resolveSandboxCreateIntent", () => { expect(JSON.stringify(first)).not.toContain("/tmp/"); }); + it("omits Discord create-time effects when an unselected credential is available", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: false, + reusable: true, + }); + const upsertMessagingProviders = vi.fn((tokenDefs: MessagingTokenDef[]) => + tokenDefs.map(({ name }) => name), + ); + + const plan = materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { upsertMessagingProviders }, + ); + + expect(intent.reusableMessagingProviders).toEqual([]); + expect(plan.activeMessagingChannels).toEqual([]); + expect(plan.initialSandboxPolicy.appliedPresets).not.toContain("discord"); + expect(plan.initialSandboxPolicy.credentialBindingProviders ?? []).not.toContain( + discordProviderName, + ); + expect(plan.messagingProviders).not.toContain(discordProviderName); + expect(plan.createArgs).not.toContain(discordProviderName); + expect(upsertMessagingProviders).toHaveBeenCalledWith([], { + replaceExisting: true, + allowedSandboxes: ["sandbox"], + }); + plan.initialSandboxPolicy.cleanup?.(); + }); + + it("attaches the selected Discord provider to its create-time policy", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + + const plan = materializeDiscordCreatePlan({ intent, messagingTokenDefs }); + + expect(plan.activeMessagingChannels).toEqual(["discord"]); + expect(plan.initialSandboxPolicy.appliedPresets).toContain("discord"); + expect(plan.initialSandboxPolicy.credentialBindingProviders).toEqual([discordProviderName]); + expect(plan.messagingProviders).toEqual([discordProviderName]); + expect(plan.createArgs).toContain(discordProviderName); + plan.initialSandboxPolicy.cleanup?.(); + }); + + it("rejects selected Discord when its provider cannot be prepared", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + + expect(() => + materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { upsertMessagingProviders: vi.fn(() => []) }, + ), + ).toThrow( + `Cannot create sandbox; create-time policy requires credential provider '${discordProviderName}', but the sandbox create plan does not attach it.`, + ); + }); + + it("rejects every create-time policy credential binding missing from the provider set", () => { + const { intent, messagingTokenDefs } = resolveDiscordCreateIntent({ + selected: true, + }); + const cleanupPolicy = vi.fn(() => true); + const cleanupProviders = vi.fn(); + const upsertMessagingProviders = vi.fn(() => [discordProviderName]); + + expect(() => + materializeDiscordCreatePlan( + { intent, messagingTokenDefs }, + { + prepareInitialSandboxCreatePolicy: vi.fn(() => ({ + policyPath: "/tmp/policy.yaml", + appliedPresets: ["discord"], + credentialBindingProviders: [discordProviderName, "sandbox-missing-provider"], + cleanup: cleanupPolicy, + })), + runProviderPreDeleteCleanup: cleanupProviders, + upsertMessagingProviders, + }, + ), + ).toThrow( + "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(); + }); + it("attaches a retained static provider while its channel runtime is stopped (#9773)", () => { const intent = resolveSandboxCreateIntent({ basePolicyPath: "/repo/hermes-policy.yaml", @@ -286,6 +446,7 @@ describe("resolveSandboxCreateIntent", () => { replaceExisting: true, allowedSandboxes: ["sandbox"], }); + expect(intent.reusableMessagingProviders).toEqual(["sandbox-discord-bridge"]); expect(plan.messagingProviders).toEqual(["sandbox-discord-bridge"]); expect(plan.createArgs).toContain("sandbox-discord-bridge"); }); @@ -401,7 +562,7 @@ describe("resolveSandboxCreateIntent", () => { }, }); - expect(events).toEqual(["policy", "disclose", "cleanup", "upsert", "hermes"]); + expect(events).toEqual(["policy", "hermes", "disclose", "cleanup", "upsert"]); expect(result.createArgs).toEqual([ "--from", "/tmp/nemoclaw-build-1/Dockerfile", @@ -745,13 +906,13 @@ describe("resolveSandboxCreateIntent", () => { plannedTokenDef: { name: "sandbox-telegram-bridge", envKey: "TELEGRAM_BOT_TOKEN", - token: null, + token: "telegram-secret", }, materializedTokenDefs: [ { name: "sandbox-telegram-bridge", envKey: "TELEGRAM_BOT_TOKEN", - token: "new-secret", + token: null, }, ], expectedMessage: diff --git a/test/e2e/live/openclaw-pairing-helpers.ts b/test/e2e/live/openclaw-pairing-helpers.ts index 708a3be0273..55c90556f9d 100644 --- a/test/e2e/live/openclaw-pairing-helpers.ts +++ b/test/e2e/live/openclaw-pairing-helpers.ts @@ -195,16 +195,17 @@ export async function applyFakePolicy(options: { redactions: string[]; artifactName: string; }): Promise { + const policyHost = "host.openshell.internal"; const methods = options.protocol === "rest" ? ["GET", "POST"] : ["GET", "WEBSOCKET_TEXT"]; const args = [ "policy", "update", options.sandboxName, "--add-endpoint", - `host.openshell.internal:${options.api.port}:read-write:${options.protocol}:enforce:${options.rewrite},allowed-ip=10.0.0.0/8,allowed-ip=172.16.0.0/12,allowed-ip=192.168.0.0/16`, + `${policyHost}:${options.api.port}:read-write:${options.protocol}:enforce:${options.rewrite},allowed-ip=10.0.0.0/8,allowed-ip=172.16.0.0/12,allowed-ip=192.168.0.0/16`, ]; for (const method of methods) - args.push("--add-allow", `host.openshell.internal:${options.api.port}:${method}:/**`); + args.push("--add-allow", `${policyHost}:${options.api.port}:${method}:/**`); args.push("--binary", "/usr/local/bin/node", "--binary", "/usr/bin/node", "--wait"); const result = await options.host.command("openshell", args, { artifactName: options.artifactName, @@ -228,7 +229,7 @@ node --import tsx "$7" "$policy_file" "$3" "$4" "$5" "$6" options.host.openshellCommandPath, options.sandboxName, options.providerName, - "host.openshell.internal", + policyHost, String(options.api.port), options.protocol, path.join(REPO_ROOT, "test/e2e/fixtures/hermes-discord-policy-binding.ts"), @@ -354,23 +355,19 @@ console.log("DISCORD_PAIRING_E2E_RESULT " + JSON.stringify({ code: result.code, NODE `.replace("__LOAD_CONVERSATION_RUNTIME_SOURCE__", LOAD_CONVERSATION_RUNTIME_SOURCE); -// Source-of-truth boundary: the Slack live probe owns only validation for its -// localized fake API port and proxy environment because those values are injected -// by the Vitest harness before the probe opens direct Node socket/http clients. -// Invalid state: a malformed fake port or proxy env, or a proxy destination other -// than the NemoClaw/OpenShell gateway proxy emitted by scripts/nemoclaw-start.sh, -// would otherwise hide the real pairing failure behind a low-level network error -// or route the fake Slack websocket through an unexpected host. Source-fix -// constraint: do not change global sandbox proxy generation for this probe; fail -// closed here before network access. Support tests cover malformed values and an -// unexpected-but-valid HTTP proxy host. Remove this localized parser once the -// Slack probe delegates Socket Mode/REST traffic to a shared fake-provider client -// instead of hand-rolled sockets. +// Source-of-truth boundary: the Slack live probe validates its localized fake API +// ports, proxy environment, and the revision-scoped credential references issued +// to the sandbox before it opens direct Node socket/http clients. Invalid state +// would otherwise hide the real pairing failure behind a low-level network error, +// route the fake Slack websocket through an unexpected host, or send a credential +// reference that OpenShell must reject for an endpoint-bound provider. Remove this +// localized parser once the Slack probe delegates Socket Mode/REST traffic to a +// shared fake-provider client instead of hand-rolled sockets. export const SLACK_PROBE_INPUT_VALIDATION_SOURCE = String.raw` -function parseFakeSlackPort() { - const raw = process.env.FAKE_SLACK_API_PORT || ""; +function parseFakeSlackPort(envKey = "FAKE_SLACK_API_PORT") { + const raw = process.env[envKey] || ""; const port = Number(raw); - if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("FAKE_SLACK_API_PORT must be an integer in 1..65535"); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(envKey + " must be an integer in 1..65535"); return port; } function parseProxyTarget() { @@ -388,6 +385,14 @@ function parseProxyTarget() { if (parsed.hostname !== "10.200.0.1" || port !== 3128) throw new Error("unexpected HTTP proxy for Slack pairing probe"); return { host: parsed.hostname, port }; } +function parseManagedCredentialReference(name) { + if (name !== "SLACK_APP_TOKEN" && name !== "SLACK_BOT_TOKEN") throw new Error("unexpected Slack credential reference name"); + const value = process.env[name] || ""; + if (!new RegExp("^openshell:resolve:env:v[0-9]{1,20}_" + name + "$").test(value)) { + throw new Error(name + " must be the revision-scoped OpenShell credential reference issued to the sandbox"); + } + return value; +} `; export const SLACK_PAIRING_SCRIPT = String.raw` @@ -396,12 +401,13 @@ set -a [ -f /tmp/nemoclaw-proxy-env.sh ] && . /tmp/nemoclaw-proxy-env.sh set +a fake_slack_api_port="$1" -slack_pairing_user="$2" +fake_slack_websocket_port="$2" +slack_pairing_user="$3" : "${"$"}{OPENCLAW_HOME:?OPENCLAW_HOME missing}" : "${"$"}{OPENCLAW_STATE_DIR:?OPENCLAW_STATE_DIR missing}" : "${"$"}{OPENCLAW_CONFIG_PATH:?OPENCLAW_CONFIG_PATH missing}" : "${"$"}{OPENCLAW_OAUTH_DIR:?OPENCLAW_OAUTH_DIR missing}" -exec env HOME=/sandbox PATH="/usr/local/bin:/usr/bin:/bin:${"$"}{PATH:-}" OPENCLAW_HOME="$OPENCLAW_HOME" OPENCLAW_STATE_DIR="$OPENCLAW_STATE_DIR" OPENCLAW_CONFIG_PATH="$OPENCLAW_CONFIG_PATH" OPENCLAW_OAUTH_DIR="$OPENCLAW_OAUTH_DIR" HTTP_PROXY="${"$"}{HTTP_PROXY:-}" HTTPS_PROXY="${"$"}{HTTPS_PROXY:-}" http_proxy="${"$"}{http_proxy:-}" https_proxy="${"$"}{https_proxy:-}" NO_PROXY="${"$"}{NO_PROXY:-}" no_proxy="${"$"}{no_proxy:-}" NODE_OPTIONS="${"$"}{NODE_OPTIONS:-}" FAKE_SLACK_API_HOST="host.openshell.internal" FAKE_SLACK_API_PORT="$fake_slack_api_port" SLACK_PAIRING_USER="$slack_pairing_user" node --input-type=module <<'NODE' +exec env HOME=/sandbox PATH="/usr/local/bin:/usr/bin:/bin:${"$"}{PATH:-}" OPENCLAW_HOME="$OPENCLAW_HOME" OPENCLAW_STATE_DIR="$OPENCLAW_STATE_DIR" OPENCLAW_CONFIG_PATH="$OPENCLAW_CONFIG_PATH" OPENCLAW_OAUTH_DIR="$OPENCLAW_OAUTH_DIR" HTTP_PROXY="${"$"}{HTTP_PROXY:-}" HTTPS_PROXY="${"$"}{HTTPS_PROXY:-}" http_proxy="${"$"}{http_proxy:-}" https_proxy="${"$"}{https_proxy:-}" NO_PROXY="${"$"}{NO_PROXY:-}" no_proxy="${"$"}{no_proxy:-}" NODE_OPTIONS="${"$"}{NODE_OPTIONS:-}" FAKE_SLACK_API_HOST="host.openshell.internal" FAKE_SLACK_API_PORT="$fake_slack_api_port" FAKE_SLACK_WEBSOCKET_PORT="$fake_slack_websocket_port" SLACK_PAIRING_USER="$slack_pairing_user" node --input-type=module <<'NODE' __LOAD_CONVERSATION_RUNTIME_SOURCE__ import crypto from "node:crypto"; import http from "node:http"; @@ -439,8 +445,9 @@ function decodeServerFrame(buffer) { } function receiveSlackSocketEvent() { const host = "host.openshell.internal"; - const port = parseFakeSlackPort(); + const port = parseFakeSlackPort("FAKE_SLACK_WEBSOCKET_PORT"); const proxy = parseProxyTarget(); + const appToken = parseManagedCredentialReference("SLACK_APP_TOKEN"); return new Promise((resolve, reject) => { const socket = proxy ? net.createConnection({ host: proxy.host, port: proxy.port }) : net.createConnection({ host, port }); const timer = setTimeout(() => { socket.destroy(); reject(new Error("timed out waiting for fake Slack Socket Mode event")); }, 30000); @@ -474,7 +481,7 @@ function receiveSlackSocketEvent() { } upgraded = true; framed = Buffer.concat([framed, handshake.slice(end + 4)]); - socket.write(encodeClientText(JSON.stringify({ type: "socket_mode_client_hello", token: "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN" }))); + socket.write(encodeClientText(JSON.stringify({ type: "socket_mode_client_hello", token: appToken }))); } else { framed = Buffer.concat([framed, chunk]); } @@ -498,7 +505,7 @@ function receiveSlackSocketEvent() { function postPairingReply(text, channel) { const host = "host.openshell.internal"; const port = parseFakeSlackPort(); - const token = "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN"; + const token = parseManagedCredentialReference("SLACK_BOT_TOKEN"); const data = new URLSearchParams({ token, channel, text }).toString(); return new Promise((resolve, reject) => { const req = http.request({ @@ -583,11 +590,16 @@ export async function issuePairingRequest(options: { channel: PairingChannel; redactions: string[]; fakeSlackPort?: string; + fakeSlackWebSocketPort?: string; }): Promise { const script = options.channel === "slack" ? SLACK_PAIRING_SCRIPT : DISCORD_PAIRING_SCRIPT; const args = options.channel === "slack" - ? [options.fakeSlackPort ?? "", PAIRING_USER.slack] + ? [ + options.fakeSlackPort ?? "", + options.fakeSlackWebSocketPort ?? "", + PAIRING_USER.slack, + ] : [PAIRING_USER.discord, DISCORD_DM_CHANNEL]; return sandboxShWithArgs(options.sandbox, options.sandboxName, script, args, { artifactName: `${options.channel}-issue-pairing-request`, diff --git a/test/e2e/live/openclaw-slack-pairing.test.ts b/test/e2e/live/openclaw-slack-pairing.test.ts index 195cea5b89f..ad02c20ac69 100644 --- a/test/e2e/live/openclaw-slack-pairing.test.ts +++ b/test/e2e/live/openclaw-slack-pairing.test.ts @@ -32,13 +32,19 @@ const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN ?? "xoxb-fake-slack-pairing- const SLACK_APP_TOKEN = process.env.SLACK_APP_TOKEN ?? "xapp-fake-slack-pairing-e2e"; const LIVE_TIMEOUT_MS = 55 * 60_000; -function assertSlackCapture(captureFile: string, expectedCode: string, expectedUser: string): void { - const rows = fs - .readFileSync(captureFile, "utf8") - .trim() - .split(/\n+/) - .filter(Boolean) - .map((line) => JSON.parse(line) as Record); +function assertSlackCapture( + captureFiles: string[], + expectedCode: string, + expectedUser: string, +): void { + const rows = captureFiles.flatMap((captureFile) => + fs + .readFileSync(captureFile, "utf8") + .trim() + .split(/\n+/) + .filter(Boolean) + .map((line) => JSON.parse(line) as Record), + ); const ws = rows .filter( (row) => row.event === "websocket-message" && row.messageType === "socket_mode_client_hello", @@ -154,7 +160,15 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap }); progress.phase("route Slack API and websocket traffic through managed policies"); - const fakeSlack = await startFakeSlackApi( + const fakeSlackRest = await startFakeSlackApi( + host, + cleanup, + env, + SLACK_BOT_TOKEN, + SLACK_APP_TOKEN, + redactions, + ); + const fakeSlackWebSocket = await startFakeSlackApi( host, cleanup, env, @@ -165,7 +179,7 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap await applyFakePolicy({ host, sandboxName: SANDBOX_NAME, - api: fakeSlack, + api: fakeSlackRest, protocol: "rest", rewrite: "request-body-credential-rewrite", providerName: `${SANDBOX_NAME}-slack-bridge`, @@ -176,7 +190,7 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap await applyFakePolicy({ host, sandboxName: SANDBOX_NAME, - api: fakeSlack, + api: fakeSlackWebSocket, protocol: "websocket", rewrite: "websocket-credential-rewrite", providerName: `${SANDBOX_NAME}-slack-app`, @@ -191,11 +205,16 @@ test("OpenClaw Slack Socket Mode pairing request is shared with connect-shell ap sandboxName: SANDBOX_NAME, channel: "slack", redactions, - fakeSlackPort: fakeSlack.port, + fakeSlackPort: fakeSlackRest.port, + fakeSlackWebSocketPort: fakeSlackWebSocket.port, }); expectExitZero(issue, "Slack pairing request creation"); const code = extractPairingCode(resultText(issue), "PAIRING_E2E_RESULT"); - assertSlackCapture(fakeSlack.captureFile, code, PAIRING_USER.slack); + assertSlackCapture( + [fakeSlackRest.captureFile, fakeSlackWebSocket.captureFile], + code, + PAIRING_USER.slack, + ); await writePairingArtifacts(artifacts, "slack", { code, user: PAIRING_USER.slack }); progress.phase("approve the Slack code through connect-shell"); diff --git a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts index 8200cc9d8bf..6550cebc123 100644 --- a/test/e2e/support/openclaw-discord-pairing-helpers.test.ts +++ b/test/e2e/support/openclaw-discord-pairing-helpers.test.ts @@ -17,6 +17,7 @@ import { buildPairingApproveCommand, buildPairingPendingCommand, LOAD_CONVERSATION_RUNTIME_SOURCE, + SLACK_PAIRING_SCRIPT, SLACK_PROBE_INPUT_VALIDATION_SOURCE, } from "../live/openclaw-pairing-helpers.ts"; import { sandboxNode } from "../live/phase6-messaging-helpers.ts"; @@ -286,6 +287,53 @@ describe("OpenClaw Discord pairing helper contracts", () => { expect(DISCORD_GATEWAY_CLIENT_SOURCE).toContain("IDENTIFY_SENT_PLACEHOLDER"); }); + it("uses distinct ports on the OpenShell host for Slack REST and websocket traffic", () => { + expect(SLACK_PAIRING_SCRIPT).toContain( + 'function receiveSlackSocketEvent() {\n const host = "host.openshell.internal";', + ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'function postPairingReply(text, channel) {\n const host = "host.openshell.internal";', + ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseFakeSlackPort("FAKE_SLACK_WEBSOCKET_PORT")', + ); + }); + + it("uses the revision-scoped Slack credential references issued to the sandbox", () => { + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseManagedCredentialReference("SLACK_APP_TOKEN")', + ); + expect(SLACK_PAIRING_SCRIPT).toContain( + 'parseManagedCredentialReference("SLACK_BOT_TOKEN")', + ); + expect(SLACK_PAIRING_SCRIPT).not.toContain( + "xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN", + ); + expect(SLACK_PAIRING_SCRIPT).not.toContain( + "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN", + ); + }); + + it.each([ + { name: "missing", value: "" }, + { name: "unscoped", value: "openshell:resolve:env:SLACK_APP_TOKEN" }, + { name: "wrong credential", value: "openshell:resolve:env:v2_SLACK_BOT_TOKEN" }, + { name: "raw token", value: "xapp-raw-slack-token" }, + ])("rejects a $name Slack app credential before network access", ({ value }) => { + const result = spawnSync(process.execPath, ["--input-type=module"], { + input: `${SLACK_PROBE_INPUT_VALIDATION_SOURCE}\nlet networkAttempted = false;\ntry { parseManagedCredentialReference("SLACK_APP_TOKEN"); networkAttempted = true; } catch (error) { console.error(error.message); console.error("NETWORK_ATTEMPTED=" + networkAttempted); process.exit(1); }\n`, + encoding: "utf8", + env: { ...process.env, SLACK_APP_TOKEN: value }, + }); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "SLACK_APP_TOKEN must be the revision-scoped OpenShell credential reference", + ); + expect(result.stderr).toContain("NETWORK_ATTEMPTED=false"); + expect(result.stderr).not.toContain("xapp-raw-slack-token"); + }); + it("sends the revision-scoped Discord placeholder through the shared gateway client (#10155)", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "discord-gateway-proof-revision-")); const captureFile = path.join(tmp, "capture.jsonl"); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index af9263f9938..3a1de449a42 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -1208,7 +1208,7 @@ const { createSandbox } = require(${onboardPath}); }); it( - "reuses sandbox when messaging providers already exist in gateway", + "reuses sandbox without refreshing unselected ambient messaging providers (#10277)", { timeout: 60_000, }, @@ -1289,19 +1289,14 @@ const { createSandbox } = require(${onboardPath}); "should NOT delete sandbox when providers already exist in gateway", ); - // Reuse refreshes credentials only after the mock returns the endpointless identity. + // Existing gateway providers do not select messaging for this onboarding request. const providerUpserts = payload.commands.filter((entry: CommandEntry) => entry.command.includes("provider update"), ); - assert.ok( - providerUpserts.some((e: CommandEntry) => - e.command.includes("my-assistant-discord-bridge"), - ), - "should upsert discord provider on reuse to refresh credentials", - ); - assert.ok( - providerUpserts.some((e: CommandEntry) => e.command.includes("my-assistant-slack-bridge")), - "should upsert slack provider on reuse to refresh credentials", + assert.equal( + providerUpserts.length, + 0, + "should not refresh ambient messaging providers without a selected channel plan", ); }, ); @@ -1442,7 +1437,7 @@ const { createSandbox } = require(${onboardPath}); ); it( - "creates no messaging providers when enabledChannels is empty", + "does not create messaging providers from ambient credentials without a selected plan (#10277)", { timeout: 60_000, }, @@ -1519,9 +1514,9 @@ const { createSandbox } = require(${onboardPath}); process.env.DISCORD_BOT_TOKEN = "test-discord-token-value"; process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token-value"; process.env.TELEGRAM_BOT_TOKEN = "123456:ABC-test-telegram-token"; - // Empty array — user deselected all channels + // No selected messaging plan — ambient repository credentials are unrelated to this request. const sandboxName = await createSandbox( - null, "gpt-5.4", "nvidia-prod", null, "my-assistant", null, [], + null, "gpt-5.4", "nvidia-prod", null, "my-assistant", null, null, ); console.log(JSON.stringify({ sandboxName, commands })); })().catch((error) => { @@ -1552,7 +1547,7 @@ const { createSandbox } = require(${onboardPath}); assert.equal( providerCommands.length, 0, - "no providers should be created when enabledChannels is empty", + "no providers should be created without a selected messaging plan", ); // Sandbox create should have no --provider flags for messaging bridges diff --git a/test/onboarding/onboard-policy-suggestions.test.ts b/test/onboarding/onboard-policy-suggestions.test.ts index f7ac5261b85..bbf153f1f4f 100644 --- a/test/onboarding/onboard-policy-suggestions.test.ts +++ b/test/onboarding/onboard-policy-suggestions.test.ts @@ -502,8 +502,11 @@ describe("onboard policy preset suggestions", () => { knownPresetNames: knownWithPricing, agent: "hermes", }); - expect(["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => - hermesOpen.includes(preset))).toBe(true); + expect( + ["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => + hermesOpen.includes(preset), + ), + ).toBe(true); expect(hermesOpen).toContain("weather"); expect(hermesOpen).toContain("public-reference"); expect(hermesOpen).not.toContain("openclaw-pricing"); @@ -513,7 +516,11 @@ describe("onboard policy preset suggestions", () => { knownPresetNames: knownWithPricing, agent: "openclaw", }); - expect(["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every((preset) => !openclawOpen.includes(preset))).toBe(true); + expect( + ["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"].every( + (preset) => !openclawOpen.includes(preset), + ), + ).toBe(true); expect(openclawOpen).toContain("openclaw-pricing"); expect(openclawOpen).toContain("weather"); expect(openclawOpen).toContain("public-reference"); @@ -583,21 +590,26 @@ describe("onboard policy preset suggestions", () => { expect(suggestions.filter((name: string) => name === "slack")).toHaveLength(1); }); - it("omits credential-bound Hermes Discord egress until the channel is active", () => { - const inactive = computeSetupPresetSuggestions("open", { - agent: "hermes", - enabledChannels: [], - knownPresetNames: known, - }); - const active = computeSetupPresetSuggestions("open", { - agent: "hermes", - enabledChannels: ["discord"], - knownPresetNames: known, - }); + it.each(["openclaw", "hermes"])( + "omits credential-bound Discord egress for %s until the channel is selected", + (agent) => { + const inactive = computeSetupPresetSuggestions("open", { + agent, + enabledChannels: [], + knownPresetNames: known, + env: { DISCORD_BOT_TOKEN: "ambient-discord-token" }, + }); + const active = computeSetupPresetSuggestions("open", { + agent, + enabledChannels: ["discord"], + knownPresetNames: known, + env: { DISCORD_BOT_TOKEN: "selected-discord-token" }, + }); - expect(inactive).not.toContain("discord"); - expect(active).toContain("discord"); - }); + expect(inactive).not.toContain("discord"); + expect(active).toContain("discord"); + }, + ); it("drops channel names that are not known presets", () => { const suggestions = computeSetupPresetSuggestions("balanced", {