diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index 3fce13f7438..d0fa8650932 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -681,13 +681,12 @@ async function planSandboxChannelAdd( hydrateAddChannelEnvFromSession(sandboxName, channelId); try { - const plan = await planner.buildPlan({ + const plan = await planner.buildChannelAddPlanFromSandboxEntry({ sandboxName, agent: toMessagingAgentId(agent), - workflow: "add-channel", isInteractive: !isNonInteractive(), - configuredChannels: [channelId], - disabledChannels: [], + channelId, + sandboxEntry: registry.getSandbox(sandboxName), supportedChannelIds, credentialAvailability: buildCredentialAvailability([channelId]), }); @@ -700,6 +699,46 @@ async function planSandboxChannelAdd( } } +async function persistManifestChannelDisabledPlan( + sandboxName: string, + channelId: string, + disabled: boolean, +): Promise { + const entry = registry.getSandbox(sandboxName); + if (!entry) return; + const agent = resolveAgentForSandbox(sandboxName); + const planner = new MessagingWorkflowPlanner(messagingManifestRegistry); + const context = { + sandboxName, + agent: toMessagingAgentId(agent), + channelId, + sandboxEntry: entry, + supportedChannelIds: availableManifestChannelsForAgent(agent).map((manifest) => manifest.id), + }; + const plan = disabled + ? await planner.buildChannelStopPlanFromSandboxEntry(context) + : await planner.buildChannelStartPlanFromSandboxEntry(context); + if (plan) MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan); +} + +async function persistManifestChannelRemovePlan( + sandboxName: string, + channelId: string, +): Promise { + const entry = registry.getSandbox(sandboxName); + if (!entry) return; + const agent = resolveAgentForSandbox(sandboxName); + const planner = new MessagingWorkflowPlanner(messagingManifestRegistry); + const plan = await planner.buildChannelRemovePlanFromSandboxEntry({ + sandboxName, + agent: toMessagingAgentId(agent), + channelId, + sandboxEntry: entry, + supportedChannelIds: availableManifestChannelsForAgent(agent).map((manifest) => manifest.id), + }); + if (plan) MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan); +} + function buildCredentialAvailability(channelIds: readonly string[]): Record { const availability: Record = {}; for (const channelId of channelIds) { @@ -923,7 +962,7 @@ export async function addSandboxChannel( } await applyChannelAddToGatewayAndRegistry(sandboxName, canonical, {}); persistManifestAddState(sandboxName, manifest); - MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan, { mode: "merge" }); + MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan); console.log(""); const help = manifest.enrollmentHelp ?? manifest.inputs[0]?.prompt?.help; if (help) console.log(` ${help}`); @@ -982,7 +1021,7 @@ export async function addSandboxChannel( } persistManifestAddState(sandboxName, manifest); - MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan, { mode: "merge" }); + MessagingHostStateApplier.applyPlanToRegistry(sandboxName, plan); const rebuilt = await promptAndRebuild(sandboxName, `add '${canonical}'`); if (rebuilt) verifyChannelBridgeAfterRebuild(sandboxName, canonical); @@ -1290,6 +1329,7 @@ export async function removeSandboxChannel( } removeChannelPresetIfPresent(sandboxName, canonical); + await persistManifestChannelRemovePlan(sandboxName, canonical); // Token-based channels: best-effort tidy of any leftover dir. Token // revocation already prevents the bot from authenticating, so a @@ -1345,6 +1385,7 @@ async function sandboxChannelsSetEnabled( console.error(` Sandbox '${sandboxName}' not found in the registry.`); process.exit(1); } + await persistManifestChannelDisabledPlan(sandboxName, normalized, disabled); const state = disabled ? "disabled" : "enabled"; console.log(` ${G}✓${R} Marked ${normalized} ${state} for '${sandboxName}'.`); await promptAndRebuild(sandboxName, `${verb} '${normalized}'`); diff --git a/src/lib/actions/sandbox/rebuild.ts b/src/lib/actions/sandbox/rebuild.ts index b010b436dc2..1edfb71a3ee 100644 --- a/src/lib/actions/sandbox/rebuild.ts +++ b/src/lib/actions/sandbox/rebuild.ts @@ -41,6 +41,12 @@ import * as agentRuntime from "../../agent/runtime"; import { RD as _RD, B, D, G, R, YW } from "../../cli/terminal-style"; import { getSandboxDeleteOutcome } from "../../domain/sandbox/destroy"; import * as nim from "../../inference/nim"; +import { + createBuiltInChannelManifestRegistry, + MessagingSetupApplier, + MessagingWorkflowPlanner, + toMessagingAgentId, +} from "../../messaging"; import { pruneDisabledMessagingPolicyPresets } from "../../onboard/messaging-policy-presets"; import { captureSandboxListWithGatewayRecovery, @@ -162,6 +168,33 @@ function preflightHermesProviderCredentials( return false; } +async function stageMessagingManifestPlanForRebuild( + sandboxName: string, + sandboxEntry: registry.SandboxEntry, + rebuildAgent: string | null, + log: (msg: string) => void, +): Promise { + const agent = loadAgent(rebuildAgent || "openclaw"); + const planner = new MessagingWorkflowPlanner(createBuiltInChannelManifestRegistry()); + const plan = await planner.buildRebuildPlanFromSandboxEntry({ + sandboxName, + agent: toMessagingAgentId(agent), + sandboxEntry, + supportedChannelIds: agent.messagingPlatforms, + }); + if (!plan || plan.channels.length === 0) { + MessagingSetupApplier.clearPlanEnv(); + log("Messaging manifest rebuild plan: no configured channels"); + return; + } + MessagingSetupApplier.writePlanToEnv(plan); + log( + `Messaging manifest rebuild plan staged: ${plan.channels + .map((channel) => channel.channelId) + .join(",")}`, + ); +} + /** * Rebuild a live sandbox while preserving registered agent state and policies. * @@ -392,6 +425,21 @@ export async function rebuildSandbox( ); } + try { + await stageMessagingManifestPlanForRebuild(sandboxName, sb, rebuildAgent, log); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + console.error(""); + console.error( + ` ${_RD}Rebuild preflight failed:${R} messaging manifest plan could not be staged.`, + ); + console.error(` ${message}`); + console.error(""); + console.error(" Sandbox is untouched — no data was lost."); + bail(message); + return; + } + // Step 1: Ensure sandbox is live for backup log("Checking sandbox liveness: openshell sandbox list"); const liveRecovery = await captureSandboxListWithGatewayRecovery(); diff --git a/src/lib/messaging/compiler/workflow-planner.test.ts b/src/lib/messaging/compiler/workflow-planner.test.ts index c7bb68bcd89..9a07b5f3078 100644 --- a/src/lib/messaging/compiler/workflow-planner.test.ts +++ b/src/lib/messaging/compiler/workflow-planner.test.ts @@ -195,9 +195,15 @@ describe("MessagingWorkflowPlanner", () => { const outputs: Record = {}; for (const output of context.outputDeclarations ?? []) { if (output.kind === "secret") { + const value = + context.channelId === "slack" && output.id === "botToken" + ? "xoxb-test-slack-bot-token" + : context.channelId === "slack" && output.id === "appToken" + ? "xapp-test-slack-app-token" + : `test-${context.channelId}-${output.id}`; outputs[output.id] = { kind: "secret", - value: `test-${context.channelId}-${output.id}`, + value, }; } } @@ -249,6 +255,10 @@ describe("MessagingWorkflowPlanner", () => { id: "common.configPrompt", handler: () => ({ outputs: {} }), }, + { + id: "slack.validateCredentials", + handler: () => ({}), + }, ]); await withEnv( @@ -418,6 +428,253 @@ describe("MessagingWorkflowPlanner", () => { ]); }); + it("adds one manifest channel into an existing sandbox entry plan", async () => { + const existingPlan = await planner().buildPlan({ + sandboxName: "demo", + agent: "openclaw", + workflow: "onboard", + isInteractive: false, + configuredChannels: ["telegram"], + credentialAvailability: { + TELEGRAM_BOT_TOKEN: true, + }, + }); + const hooks = new MessagingHookRegistry([ + { + id: "common.tokenPaste", + handler: (context) => { + if (context.channelId === "telegram") { + throw new Error("existing channels should not re-enroll"); + } + const outputs: Record = {}; + for (const output of context.outputDeclarations ?? []) { + if (output.kind === "secret") { + const value = + context.channelId === "slack" && output.id === "botToken" + ? "xoxb-test-slack-bot-token" + : context.channelId === "slack" && output.id === "appToken" + ? "xapp-test-slack-app-token" + : `test-${context.channelId}-${output.id}`; + outputs[output.id] = { + kind: "secret", + value, + }; + } + } + return { outputs }; + }, + }, + { + id: "common.configPrompt", + handler: () => ({ outputs: {} }), + }, + { + id: "slack.validateCredentials", + handler: () => ({}), + }, + ]); + + const plan = await new MessagingWorkflowPlanner( + createBuiltInChannelManifestRegistry(), + hooks, + ).buildChannelAddPlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messaging: { + schemaVersion: 1, + plan: existingPlan, + }, + }, + channelId: "slack", + isInteractive: true, + supportedChannelIds: ["telegram", "slack"], + }); + + expect(plan.workflow).toBe("add-channel"); + expect(plan.channels.map((channel) => channel.channelId)).toEqual([ + "telegram", + "slack", + ]); + expect(plan.channels.find((channel) => channel.channelId === "telegram")).toMatchObject({ + active: true, + configured: true, + }); + expect(plan.channels.find((channel) => channel.channelId === "slack")).toMatchObject({ + active: true, + configured: true, + disabled: false, + }); + expect(plan.credentialBindings.map((binding) => binding.channelId)).toEqual([ + "telegram", + "slack", + "slack", + ]); + }); + + it("mutates disabled channel state in an existing sandbox entry plan", async () => { + const existingPlan = await planner().buildPlan({ + sandboxName: "demo", + agent: "openclaw", + workflow: "onboard", + isInteractive: false, + configuredChannels: ["telegram", "slack"], + credentialAvailability: { + TELEGRAM_BOT_TOKEN: true, + SLACK_BOT_TOKEN: true, + SLACK_APP_TOKEN: true, + }, + }); + + const stopped = await planner().buildChannelStopPlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messaging: { + schemaVersion: 1, + plan: existingPlan, + }, + }, + channelId: "telegram", + }); + + expect(stopped?.workflow).toBe("stop-channel"); + expect(stopped?.disabledChannels).toEqual(["telegram"]); + expect(stopped?.channels.find((channel) => channel.channelId === "telegram")).toMatchObject({ + active: false, + disabled: true, + }); + + const started = await planner().buildChannelStartPlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messaging: { + schemaVersion: 1, + plan: stopped!, + }, + }, + channelId: "telegram", + }); + + expect(started?.workflow).toBe("start-channel"); + expect(started?.disabledChannels).toEqual([]); + expect(started?.channels.find((channel) => channel.channelId === "telegram")).toMatchObject({ + active: true, + disabled: false, + }); + }); + + it("removes a channel and its dependent plan entries from an existing sandbox entry plan", async () => { + const existingPlan = await planner().buildPlan({ + sandboxName: "demo", + agent: "openclaw", + workflow: "onboard", + isInteractive: false, + configuredChannels: ["telegram", "slack"], + credentialAvailability: { + TELEGRAM_BOT_TOKEN: true, + SLACK_BOT_TOKEN: true, + SLACK_APP_TOKEN: true, + }, + }); + + const removed = await planner().buildChannelRemovePlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messaging: { + schemaVersion: 1, + plan: existingPlan, + }, + }, + channelId: "telegram", + }); + + expect(removed?.workflow).toBe("remove-channel"); + expect(removed?.channels.map((channel) => channel.channelId)).toEqual(["slack"]); + expect(removed?.disabledChannels).toEqual([]); + expect( + removed?.credentialBindings.some((binding) => binding.channelId === "telegram"), + ).toBe(false); + expect( + removed?.networkPolicy.entries.some((entry) => entry.channelId === "telegram"), + ).toBe(false); + expect(removed?.agentRender.some((entry) => entry.channelId === "telegram")).toBe(false); + }); + + it("rebuilds from stored plan input values when config env is unavailable", async () => { + const existingPlan = await withEnv( + { + TELEGRAM_REQUIRE_MENTION: "1", + }, + () => + planner().buildPlan({ + sandboxName: "demo", + agent: "openclaw", + workflow: "onboard", + isInteractive: false, + configuredChannels: ["telegram"], + credentialAvailability: { + TELEGRAM_BOT_TOKEN: true, + }, + }), + ); + + await withEnv( + { + TELEGRAM_REQUIRE_MENTION: undefined, + }, + async () => { + const rebuilt = await planner().buildRebuildPlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messagingChannels: ["telegram"], + messaging: { + schemaVersion: 1, + plan: existingPlan, + }, + }, + }); + + expect(rebuilt?.workflow).toBe("rebuild"); + expect( + rebuilt?.channels + .find((channel) => channel.channelId === "telegram") + ?.inputs.find((input) => input.inputId === "requireMention"), + ).toMatchObject({ + value: "1", + }); + expect(rebuilt?.channels.find((channel) => channel.channelId === "telegram")).toMatchObject({ + active: true, + disabled: false, + }); + }, + ); + }); + + it("does not compile a rebuild plan when the sandbox entry has no stored plan", async () => { + const rebuilt = await planner().buildRebuildPlanFromSandboxEntry({ + sandboxName: "demo", + agent: "openclaw", + sandboxEntry: { + name: "demo", + messagingChannels: ["telegram"], + providerCredentialHashes: { + TELEGRAM_BOT_TOKEN: "sha256:test", + }, + }, + }); + + expect(rebuilt).toBeNull(); + }); + it("reports unsupported channels deterministically before compiling", async () => { await expect( planner().buildPlan({ diff --git a/src/lib/messaging/compiler/workflow-planner.ts b/src/lib/messaging/compiler/workflow-planner.ts index 8371b2d1ade..853ff39456a 100644 --- a/src/lib/messaging/compiler/workflow-planner.ts +++ b/src/lib/messaging/compiler/workflow-planner.ts @@ -7,6 +7,7 @@ import type { MessagingAgentId, MessagingChannelId, MessagingCompilerWorkflow, + SandboxMessagingChannelPlan, SandboxMessagingPlan, } from "../manifest"; import { ManifestCompiler } from "./manifest-compiler"; @@ -56,6 +57,65 @@ export class MessagingWorkflowPlanner { return this.compiler.compile(compilerContext); } + async buildChannelAddPlanFromSandboxEntry( + context: MessagingWorkflowPlannerChannelAddContext, + ): Promise { + const existingPlan = readSandboxEntryPlan(context); + const compiledPlan = await this.buildPlan({ + sandboxName: context.sandboxName, + agent: context.agent, + workflow: "add-channel", + isInteractive: context.isInteractive, + configuredChannels: [context.channelId], + disabledChannels: [], + supportedChannelIds: context.supportedChannelIds, + credentialAvailability: mergeAvailability( + credentialAvailabilityFromPlan(existingPlan), + this.credentialAvailabilityFromSandboxEntry( + context.sandboxEntry, + [context.channelId], + ), + context.credentialAvailability, + ), + }); + return existingPlan + ? mergeSandboxMessagingPlans(existingPlan, compiledPlan) + : compiledPlan; + } + + async buildChannelStopPlanFromSandboxEntry( + context: MessagingWorkflowPlannerChannelMutationContext, + ): Promise { + const plan = await this.planForSandboxEntryMutation(context, "stop-channel"); + return plan ? setPlanChannelDisabled(plan, context.channelId, true, "stop-channel") : null; + } + + async buildChannelStartPlanFromSandboxEntry( + context: MessagingWorkflowPlannerChannelMutationContext, + ): Promise { + const plan = await this.planForSandboxEntryMutation(context, "start-channel"); + return plan ? setPlanChannelDisabled(plan, context.channelId, false, "start-channel") : null; + } + + async buildChannelRemovePlanFromSandboxEntry( + context: MessagingWorkflowPlannerChannelMutationContext, + ): Promise { + const plan = await this.planForSandboxEntryMutation(context, "remove-channel"); + return plan ? removePlanChannel(plan, context.channelId, "remove-channel") : null; + } + + async buildRebuildPlanFromSandboxEntry( + context: MessagingWorkflowPlannerSandboxRebuildContext, + ): Promise { + const existingPlan = readSandboxEntryPlan(context); + if (!existingPlan) return null; + return setPlanDisabledChannels( + existingPlan, + disabledChannelsFromSandboxEntry(context.sandboxEntry, existingPlan), + "rebuild", + ); + } + private assertSupportedChannels( channelIds: readonly MessagingChannelId[], context: Pick< @@ -92,8 +152,74 @@ export class MessagingWorkflowPlanner { .filter((manifest) => !supportedFilter || supportedFilter.has(manifest.id)) .map((manifest) => manifest.id); } + + private async planForSandboxEntryMutation( + context: MessagingWorkflowPlannerChannelMutationContext, + workflow: MessagingCompilerWorkflow, + ): Promise { + const existingPlan = readSandboxEntryPlan(context); + if (existingPlan) return { ...clonePlan(existingPlan), workflow }; + return null; + } + + private credentialAvailabilityFromSandboxEntry( + sandboxEntry: MessagingWorkflowPlannerSandboxEntry | null | undefined, + channelIds: readonly MessagingChannelId[], + ): MessagingCompilerCredentialAvailability | undefined { + const hashes = sandboxEntry?.providerCredentialHashes; + if (!hashes || Object.keys(hashes).length === 0) return undefined; + + const availability: Record = {}; + for (const channelId of channelIds) { + const manifest = this.registry.get(channelId); + if (!manifest) continue; + for (const credential of manifest.credentials) { + if (!hashes[credential.providerEnvKey]) continue; + availability[credential.sourceInput] = true; + availability[`${manifest.id}.${credential.sourceInput}`] = true; + availability[credential.id] = true; + availability[`${manifest.id}.${credential.id}`] = true; + availability[credential.providerEnvKey] = true; + } + } + return Object.keys(availability).length > 0 ? availability : undefined; + } +} + +export interface MessagingWorkflowPlannerSandboxEntry { + readonly name: string; + readonly agent?: string | null; + readonly messagingChannels?: readonly MessagingChannelId[] | null; + readonly disabledChannels?: readonly MessagingChannelId[] | null; + readonly providerCredentialHashes?: Readonly> | null; + readonly messaging?: { + readonly schemaVersion: 1; + readonly plan: SandboxMessagingPlan; + } | null; +} + +export interface MessagingWorkflowPlannerSandboxContext { + readonly sandboxName: string; + readonly agent: MessagingAgentId; + readonly sandboxEntry?: MessagingWorkflowPlannerSandboxEntry | null; + readonly supportedChannelIds?: readonly MessagingChannelId[]; + readonly credentialAvailability?: MessagingCompilerCredentialAvailability; } +export interface MessagingWorkflowPlannerChannelAddContext + extends MessagingWorkflowPlannerSandboxContext { + readonly channelId: MessagingChannelId; + readonly isInteractive: boolean; +} + +export interface MessagingWorkflowPlannerChannelMutationContext + extends MessagingWorkflowPlannerSandboxContext { + readonly channelId: MessagingChannelId; +} + +export type MessagingWorkflowPlannerSandboxRebuildContext = + MessagingWorkflowPlannerSandboxContext; + function uniqueChannels( channelIds: readonly MessagingChannelId[] | undefined, ): MessagingChannelId[] { @@ -107,3 +233,235 @@ function onlyConfiguredChannels( const configured = new Set(configuredChannels); return uniqueChannels(channelIds).filter((channelId) => configured.has(channelId)); } + +function readSandboxEntryPlan( + context: Pick< + MessagingWorkflowPlannerSandboxContext, + "agent" | "sandboxEntry" | "sandboxName" + >, +): SandboxMessagingPlan | null { + const plan = context.sandboxEntry?.messaging?.plan; + if ( + !plan || + plan.schemaVersion !== 1 || + plan.sandboxName !== context.sandboxName || + plan.agent !== context.agent + ) { + return null; + } + return clonePlan(plan); +} + +function disabledChannelsFromSandboxEntry( + sandboxEntry: MessagingWorkflowPlannerSandboxEntry | null | undefined, + fallbackPlan: SandboxMessagingPlan | null, +): MessagingChannelId[] { + return uniqueChannels( + Array.isArray(sandboxEntry?.disabledChannels) + ? sandboxEntry.disabledChannels + : fallbackPlan?.disabledChannels ?? [], + ); +} + +function clonePlan(plan: SandboxMessagingPlan): SandboxMessagingPlan { + return JSON.parse(JSON.stringify(plan)) as SandboxMessagingPlan; +} + +function mergeSandboxMessagingPlans( + existing: SandboxMessagingPlan, + incoming: SandboxMessagingPlan, +): SandboxMessagingPlan { + if ( + existing.schemaVersion !== incoming.schemaVersion || + existing.sandboxName !== incoming.sandboxName || + existing.agent !== incoming.agent + ) { + return clonePlan(incoming); + } + + const incomingChannelIds = new Set(incoming.channels.map((channel) => channel.channelId)); + const mergedChannels = [ + ...existing.channels.filter((channel) => !incomingChannelIds.has(channel.channelId)), + ...incoming.channels, + ]; + const activeIncomingChannels = new Set( + incoming.channels + .filter((channel) => channel.active && !channel.disabled) + .map((channel) => channel.channelId), + ); + const disabledChannels = uniqueSortedStrings([ + ...existing.disabledChannels.filter((channelId) => !activeIncomingChannels.has(channelId)), + ...incoming.disabledChannels, + ]); + const networkEntries = mergePlanEntriesByChannel( + existing.networkPolicy.entries, + incoming.networkPolicy.entries, + ); + + return clonePlan({ + ...incoming, + channels: mergedChannels, + disabledChannels, + credentialBindings: mergePlanEntriesByChannel( + existing.credentialBindings, + incoming.credentialBindings, + ), + networkPolicy: { + presets: uniqueSortedStrings(networkEntries.map((entry) => entry.presetName)), + entries: networkEntries, + }, + agentRender: mergePlanEntriesByChannel(existing.agentRender, incoming.agentRender), + buildSteps: mergePlanEntriesByChannel(existing.buildSteps, incoming.buildSteps), + stateUpdates: mergePlanEntriesByChannel(existing.stateUpdates, incoming.stateUpdates), + healthChecks: mergePlanEntriesByChannel(existing.healthChecks, incoming.healthChecks), + }); +} + +function setPlanChannelDisabled( + plan: SandboxMessagingPlan, + channelId: MessagingChannelId, + disabled: boolean, + workflow: MessagingCompilerWorkflow, +): SandboxMessagingPlan { + const nextChannels = plan.channels.map((channel) => { + if (channel.channelId !== channelId) return channel; + const nextChannel = { ...channel, disabled }; + return { + ...nextChannel, + active: !disabled && isChannelPlanStartable(nextChannel), + }; + }); + const configuredIds = new Set(nextChannels.map((channel) => channel.channelId)); + const disabledChannels = disabled + ? uniqueSortedStrings([...plan.disabledChannels, channelId]).filter((id) => + configuredIds.has(id), + ) + : plan.disabledChannels.filter((id) => id !== channelId); + + return clonePlan({ + ...plan, + workflow, + channels: nextChannels, + disabledChannels, + }); +} + +function setPlanDisabledChannels( + plan: SandboxMessagingPlan, + disabledChannelIds: readonly MessagingChannelId[], + workflow: MessagingCompilerWorkflow, +): SandboxMessagingPlan { + const configuredIds = new Set(plan.channels.map((channel) => channel.channelId)); + const disabledChannels = uniqueSortedStrings(disabledChannelIds).filter((id) => + configuredIds.has(id), + ); + const disabledSet = new Set(disabledChannels); + const channels = plan.channels.map((channel) => { + const disabled = disabledSet.has(channel.channelId); + const nextChannel = { ...channel, disabled }; + return { + ...nextChannel, + active: !disabled && isChannelPlanStartable(nextChannel), + }; + }); + + return clonePlan({ + ...plan, + workflow, + channels, + disabledChannels, + }); +} + +function removePlanChannel( + plan: SandboxMessagingPlan, + channelId: MessagingChannelId, + workflow: MessagingCompilerWorkflow, +): SandboxMessagingPlan { + const channels = plan.channels.filter((channel) => channel.channelId !== channelId); + const remainingChannelIds = new Set(channels.map((channel) => channel.channelId)); + const networkEntries = plan.networkPolicy.entries.filter( + (entry) => entry.channelId !== channelId, + ); + const keepEntry = (entry: T) => + entry.channelId !== channelId && remainingChannelIds.has(entry.channelId); + + return clonePlan({ + ...plan, + workflow, + channels, + disabledChannels: plan.disabledChannels.filter( + (id) => id !== channelId && remainingChannelIds.has(id), + ), + credentialBindings: plan.credentialBindings.filter(keepEntry), + networkPolicy: { + presets: uniqueSortedStrings(networkEntries.map((entry) => entry.presetName)), + entries: networkEntries, + }, + agentRender: plan.agentRender.filter(keepEntry), + buildSteps: plan.buildSteps.filter(keepEntry), + stateUpdates: plan.stateUpdates.filter(keepEntry), + healthChecks: plan.healthChecks.filter(keepEntry), + }); +} + +function isChannelPlanStartable(channel: SandboxMessagingChannelPlan): boolean { + if (!channel.configured) return false; + return channel.inputs.every((input) => { + if (!input.required) return true; + if (input.kind === "secret") return input.credentialAvailable === true; + if (input.value === undefined) return false; + return typeof input.value === "string" ? input.value.trim().length > 0 : true; + }); +} + +function mergePlanEntriesByChannel( + existing: readonly T[], + incoming: readonly T[], +): T[] { + const incomingChannelIds = new Set(incoming.map((entry) => entry.channelId)); + return [ + ...existing.filter((entry) => !incomingChannelIds.has(entry.channelId)), + ...incoming, + ]; +} + +function credentialAvailabilityFromPlan( + plan: SandboxMessagingPlan | null, +): MessagingCompilerCredentialAvailability | undefined { + if (!plan) return undefined; + const availability: Record = {}; + for (const channel of plan.channels) { + for (const input of channel.inputs) { + if (input.kind !== "secret" || input.credentialAvailable !== true) continue; + availability[input.inputId] = true; + availability[`${channel.channelId}.${input.inputId}`] = true; + if (input.sourceEnv) availability[input.sourceEnv] = true; + } + } + for (const credential of plan.credentialBindings) { + if (!credential.credentialAvailable) continue; + availability[credential.credentialId] = true; + availability[`${credential.channelId}.${credential.credentialId}`] = true; + availability[credential.sourceInput] = true; + availability[`${credential.channelId}.${credential.sourceInput}`] = true; + availability[credential.providerEnvKey] = true; + } + return Object.keys(availability).length > 0 ? availability : undefined; +} + +function mergeAvailability( + ...sources: Array +): MessagingCompilerCredentialAvailability | undefined { + const merged: Record = {}; + for (const source of sources) { + for (const [key, value] of Object.entries(source ?? {})) { + if (value === true) merged[key] = true; + } + } + return Object.keys(merged).length > 0 ? merged : undefined; +} + +function uniqueSortedStrings(values: readonly string[]): string[] { + return [...new Set(values)].filter(Boolean).sort(); +} diff --git a/test/e2e/test-channels-add-remove.sh b/test/e2e/test-channels-add-remove.sh index 59837349fad..fb17b987e06 100755 --- a/test/e2e/test-channels-add-remove.sh +++ b/test/e2e/test-channels-add-remove.sh @@ -84,7 +84,10 @@ fi SANDBOX_NAME="${NEMOCLAW_SANDBOX_NAME:-e2e-channels-add-remove}" INSTALL_LOG="/tmp/nemoclaw-e2e-install.log" +REGISTRY="$HOME/.nemoclaw/sandboxes.json" TELEGRAM_TOKEN="${TELEGRAM_BOT_TOKEN:-test-fake-telegram-token-add-remove-e2e}" +TELEGRAM_ALLOWED_IDS_VALUE="${TELEGRAM_ALLOWED_IDS:-123456789}" +TELEGRAM_REQUIRE_MENTION_VALUE="${TELEGRAM_REQUIRE_MENTION:-0}" is_fake_telegram_token() { case "${1:-}" in @@ -158,6 +161,105 @@ policy_list_has_preset() { | grep -E "^\s*●\s+${preset}\b" >/dev/null } +assert_host_telegram_config() { + local context="$1" + local output + if output="$(node -e ' +const fs = require("fs"); +const [registryPath, sandboxName, allowedIds, requireMention] = process.argv.slice(1); +const fail = (message) => { + console.error(message); + process.exit(1); +}; +if (!fs.existsSync(registryPath)) fail("registry file not found: " + registryPath); +const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")); +const entry = registry.sandboxes?.[sandboxName]; +if (!entry) fail("sandbox " + sandboxName + " missing from registry"); +const config = entry.messagingChannelConfig; +if (!config || typeof config !== "object" || Array.isArray(config)) { + fail("messagingChannelConfig missing or not an object"); +} +if (config.TELEGRAM_ALLOWED_IDS !== allowedIds) { + fail("TELEGRAM_ALLOWED_IDS expected " + allowedIds + ", got " + JSON.stringify(config.TELEGRAM_ALLOWED_IDS)); +} +if (config.TELEGRAM_REQUIRE_MENTION !== requireMention) { + fail("TELEGRAM_REQUIRE_MENTION expected " + requireMention + ", got " + JSON.stringify(config.TELEGRAM_REQUIRE_MENTION)); +} +' "$REGISTRY" "$SANDBOX_NAME" "$TELEGRAM_ALLOWED_IDS_VALUE" "$TELEGRAM_REQUIRE_MENTION_VALUE" 2>&1)"; then + pass "host registry messagingChannelConfig persists telegram config ${context}" + else + fail "host registry messagingChannelConfig missing telegram config ${context}: ${output}" + fi +} + +assert_host_telegram_plan() { + local expected="$1" + local context="$2" + local output + if output="$(node -e ' +const fs = require("fs"); +const [registryPath, sandboxName, expected] = process.argv.slice(1); +const fail = (message) => { + console.error(message); + process.exit(1); +}; +if (!fs.existsSync(registryPath)) fail("registry file not found: " + registryPath); +const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")); +const entry = registry.sandboxes?.[sandboxName]; +if (!entry) fail("sandbox " + sandboxName + " missing from registry"); +const state = entry.messaging; +if (!state || state.schemaVersion !== 1) fail("messaging state missing or schemaVersion != 1"); +const plan = state.plan; +if (!plan || plan.schemaVersion !== 1) fail("messaging.plan missing or schemaVersion != 1"); +if (plan.sandboxName !== sandboxName) { + fail("messaging.plan.sandboxName expected " + sandboxName + ", got " + JSON.stringify(plan.sandboxName)); +} +if (plan.agent !== "openclaw") fail("messaging.plan.agent expected openclaw, got " + JSON.stringify(plan.agent)); +const channels = Array.isArray(plan.channels) ? plan.channels : []; +const channel = channels.find((item) => item?.channelId === "telegram"); +const disabledChannels = Array.isArray(plan.disabledChannels) ? plan.disabledChannels : []; +const credentialBindings = Array.isArray(plan.credentialBindings) ? plan.credentialBindings : []; +const networkEntries = Array.isArray(plan.networkPolicy?.entries) ? plan.networkPolicy.entries : []; +const networkPresets = Array.isArray(plan.networkPolicy?.presets) ? plan.networkPolicy.presets : []; +const agentRender = Array.isArray(plan.agentRender) ? plan.agentRender : []; +if (expected === "active") { + if (!channel) fail("telegram channel missing from messaging.plan.channels"); + if (channel.active !== true) fail("telegram plan active expected true, got " + JSON.stringify(channel.active)); + if (channel.disabled === true) fail("telegram plan disabled unexpectedly true"); + if (!networkPresets.includes("telegram")) fail("telegram missing from messaging.plan.networkPolicy.presets"); + if (!networkEntries.some((entry) => entry?.channelId === "telegram")) { + fail("telegram missing from messaging.plan.networkPolicy.entries"); + } + if (!credentialBindings.some((entry) => entry?.channelId === "telegram" && entry?.providerEnvKey === "TELEGRAM_BOT_TOKEN")) { + fail("telegram TELEGRAM_BOT_TOKEN credential binding missing from messaging.plan"); + } + if (!agentRender.some((entry) => entry?.channelId === "telegram" && entry?.agent === "openclaw")) { + fail("telegram openclaw agent render entry missing from messaging.plan"); + } + if (disabledChannels.includes("telegram")) fail("telegram unexpectedly listed in messaging.plan.disabledChannels"); +} else if (expected === "removed") { + if (channel) fail("telegram still present in messaging.plan.channels"); + if (disabledChannels.includes("telegram")) fail("telegram still present in messaging.plan.disabledChannels"); + if (networkPresets.includes("telegram")) fail("telegram still present in messaging.plan.networkPolicy.presets"); + if (networkEntries.some((entry) => entry?.channelId === "telegram")) { + fail("telegram still present in messaging.plan.networkPolicy.entries"); + } + if (credentialBindings.some((entry) => entry?.channelId === "telegram")) { + fail("telegram credential binding still present in messaging.plan"); + } + if (agentRender.some((entry) => entry?.channelId === "telegram")) { + fail("telegram agent render entry still present in messaging.plan"); + } +} else { + fail("unknown expected plan state: " + expected); +} +' "$REGISTRY" "$SANDBOX_NAME" "$expected" 2>&1)"; then + pass "host registry messaging.plan has telegram ${expected} ${context}" + else + fail "host registry messaging.plan expected telegram ${expected} ${context}: ${output}" + fi +} + # Run rebuild with live tail of the rebuild log so the operator can see # progress. Mirrors the install.sh tail pattern in Phase 1. run_rebuild_with_live_log() { @@ -245,6 +347,8 @@ pass "C1a: Pre-cleanup complete" # messaging tokens and skip the messaging step entirely. This reproduces the # exact entry condition of the #3437 bug (onboard empty -> later channels add). unset TELEGRAM_BOT_TOKEN +unset TELEGRAM_ALLOWED_IDS +unset TELEGRAM_REQUIRE_MENTION export NEMOCLAW_SANDBOX_NAME="$SANDBOX_NAME" export NEMOCLAW_RECREATE_SANDBOX=1 @@ -338,6 +442,8 @@ section "Phase 3: channels add telegram + rebuild" # Now provide the token — this mirrors the real user flow: after onboard, # the operator decides to add a channel and exports the token first. export TELEGRAM_BOT_TOKEN="$TELEGRAM_TOKEN" +export TELEGRAM_ALLOWED_IDS="$TELEGRAM_ALLOWED_IDS_VALUE" +export TELEGRAM_REQUIRE_MENTION="$TELEGRAM_REQUIRE_MENTION_VALUE" maybe_skip_telegram_reachability_for_fake_token if nemoclaw "$SANDBOX_NAME" channels add telegram >/tmp/nc-add.log 2>&1; then @@ -352,6 +458,8 @@ else fail "C3a: channels add telegram did not register" tail -20 /tmp/nc-add.log 2>/dev/null || true fi +assert_host_telegram_config "after channels add" +assert_host_telegram_plan "active" "after channels add" info "Rebuilding sandbox to apply the add..." if run_rebuild_with_live_log /tmp/nc-rebuild-add.log; then @@ -394,6 +502,9 @@ else fail "C4c: telegram-bridge provider missing in gateway after add+rebuild" fi +assert_host_telegram_config "after add+rebuild" +assert_host_telegram_plan "active" "after add+rebuild" + # C4d: network reachability. With the preset applied, the bridge-style # probe (see telegram_egress_open) should reach Telegram and elicit a # response; without it, the proxy denies the CONNECT. User-facing symptom @@ -426,6 +537,8 @@ else fail "C5a: channels remove telegram did not unregister" tail -20 /tmp/nc-remove.log 2>/dev/null || true fi +assert_host_telegram_config "after channels remove" +assert_host_telegram_plan "removed" "after channels remove" info "Rebuilding sandbox to apply the remove..." if run_rebuild_with_live_log /tmp/nc-rebuild-remove.log; then @@ -471,4 +584,6 @@ else pass "C6c: 'telegram' preset removed from policy list after remove+rebuild" fi +assert_host_telegram_config "after remove+rebuild" + print_summary diff --git a/test/e2e/test-channels-stop-start.sh b/test/e2e/test-channels-stop-start.sh index ad082c81166..38b3f20d135 100755 --- a/test/e2e/test-channels-stop-start.sh +++ b/test/e2e/test-channels-stop-start.sh @@ -319,6 +319,113 @@ assert_disabled_channels() { done } +assert_host_messaging_config() { + local context="$1" + local output msg + if output="$(node -e ' +const fs = require("fs"); +const [registryPath, sandboxName, ...pairs] = process.argv.slice(1); +const fail = (message) => { + console.error(message); + process.exit(1); +}; +if (!fs.existsSync(registryPath)) fail("registry file not found: " + registryPath); +const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")); +const entry = registry.sandboxes?.[sandboxName]; +if (!entry) fail("sandbox " + sandboxName + " missing from registry"); +const config = entry.messagingChannelConfig; +if (!config || typeof config !== "object" || Array.isArray(config)) { + fail("messagingChannelConfig missing or not an object"); +} +for (let i = 0; i < pairs.length; i += 2) { + const key = pairs[i]; + const expected = pairs[i + 1]; + if (config[key] !== expected) { + fail(key + " expected " + expected + ", got " + JSON.stringify(config[key])); + } +} +' "$REGISTRY" "$ACTIVE_SANDBOX" \ + TELEGRAM_ALLOWED_IDS "$TELEGRAM_ALLOWED_IDS" \ + TELEGRAM_REQUIRE_MENTION "$TELEGRAM_REQUIRE_MENTION" \ + DISCORD_SERVER_ID "$DISCORD_SERVER_ID" \ + DISCORD_USER_ID "$DISCORD_USER_ID" \ + DISCORD_REQUIRE_MENTION "$DISCORD_REQUIRE_MENTION" \ + SLACK_ALLOWED_USERS "$SLACK_ALLOWED_USERS" \ + WECHAT_ALLOWED_IDS "$WECHAT_ALLOWED_IDS" 2>&1)"; then + msg="${ACTIVE_AGENT}: host registry messagingChannelConfig persists channel config ${context}" + pass_msg "$msg" + else + msg="${ACTIVE_AGENT}: host registry messagingChannelConfig missing channel config ${context}: ${output}" + fail_msg "$msg" + fi +} + +assert_host_messaging_plan_state() { + local expected="$1" + local context="$2" + local channel output msg + for channel in "${CHANNELS[@]}"; do + if output="$(node -e ' +const fs = require("fs"); +const [registryPath, sandboxName, agent, channelId, expected] = process.argv.slice(1); +const fail = (message) => { + console.error(message); + process.exit(1); +}; +if (!fs.existsSync(registryPath)) fail("registry file not found: " + registryPath); +const registry = JSON.parse(fs.readFileSync(registryPath, "utf8")); +const entry = registry.sandboxes?.[sandboxName]; +if (!entry) fail("sandbox " + sandboxName + " missing from registry"); +const state = entry.messaging; +if (!state || state.schemaVersion !== 1) fail("messaging state missing or schemaVersion != 1"); +const plan = state.plan; +if (!plan || plan.schemaVersion !== 1) fail("messaging.plan missing or schemaVersion != 1"); +if (plan.sandboxName !== sandboxName) { + fail("messaging.plan.sandboxName expected " + sandboxName + ", got " + JSON.stringify(plan.sandboxName)); +} +if (plan.agent !== agent) fail("messaging.plan.agent expected " + agent + ", got " + JSON.stringify(plan.agent)); +const channels = Array.isArray(plan.channels) ? plan.channels : []; +const channel = channels.find((item) => item?.channelId === channelId); +if (!channel) fail(channelId + " missing from messaging.plan.channels"); +if (channel.configured !== true) { + fail(channelId + " messaging.plan configured expected true, got " + JSON.stringify(channel.configured)); +} +const disabledChannels = Array.isArray(plan.disabledChannels) ? plan.disabledChannels : []; +if (expected === "active") { + if (channel.active !== true) fail(channelId + " messaging.plan active expected true, got " + JSON.stringify(channel.active)); + if (channel.disabled === true) fail(channelId + " messaging.plan disabled unexpectedly true"); + if (disabledChannels.includes(channelId)) fail(channelId + " unexpectedly listed in messaging.plan.disabledChannels"); +} else if (expected === "disabled") { + if (channel.disabled !== true) fail(channelId + " messaging.plan disabled expected true, got " + JSON.stringify(channel.disabled)); + if (channel.active === true) fail(channelId + " messaging.plan active unexpectedly true"); + if (!disabledChannels.includes(channelId)) fail(channelId + " missing from messaging.plan.disabledChannels"); +} else { + fail("unknown expected plan state: " + expected); +} +const networkEntries = Array.isArray(plan.networkPolicy?.entries) ? plan.networkPolicy.entries : []; +const networkPresets = Array.isArray(plan.networkPolicy?.presets) ? plan.networkPolicy.presets : []; +if (!networkPresets.includes(channelId)) fail(channelId + " missing from messaging.plan.networkPolicy.presets"); +if (!networkEntries.some((entry) => entry?.channelId === channelId)) { + fail(channelId + " missing from messaging.plan.networkPolicy.entries"); +} +const credentialBindings = Array.isArray(plan.credentialBindings) ? plan.credentialBindings : []; +if (channelId !== "whatsapp" && !credentialBindings.some((entry) => entry?.channelId === channelId)) { + fail(channelId + " credential binding missing from messaging.plan"); +} +const agentRender = Array.isArray(plan.agentRender) ? plan.agentRender : []; +if (!agentRender.some((entry) => entry?.channelId === channelId && entry?.agent === agent)) { + fail(channelId + " " + agent + " render entry missing from messaging.plan"); +} +' "$REGISTRY" "$ACTIVE_SANDBOX" "$ACTIVE_AGENT" "$channel" "$expected" 2>&1)"; then + msg="${ACTIVE_AGENT}/${channel}: host registry messaging.plan has channel ${expected} ${context}" + pass_msg "$msg" + else + msg="${ACTIVE_AGENT}/${channel}: host registry messaging.plan expected ${expected} ${context}: ${output}" + fail_msg "$msg" + fi + done +} + assert_provider_records_exist() { local context="$1" local channel provider msg @@ -624,12 +731,16 @@ run_agent_scenario() { assert_all_config_channels "present" "at baseline" assert_registry_channels "present" "at baseline" assert_disabled_channels "absent" "at baseline" + assert_host_messaging_config "at baseline" + assert_host_messaging_plan_state "active" "at baseline" for channel in "${CHANNELS[@]}"; do assert_policy_preset_active "$channel" "active" "at baseline" done section "${agent}: channels stop all + rebuild" stop_all_channels + assert_host_messaging_config "after channels stop" + assert_host_messaging_plan_state "disabled" "after channels stop" run_rebuild "stop-all" section "${agent}: verify stopped state" @@ -637,9 +748,13 @@ run_agent_scenario() { assert_registry_channels "present" "after stop" assert_disabled_channels "present" "after stop" assert_provider_records_exist "after stop" + assert_host_messaging_config "after stop+rebuild" + assert_host_messaging_plan_state "disabled" "after stop+rebuild" section "${agent}: channels start all + rebuild" start_all_channels + assert_host_messaging_config "after channels start" + assert_host_messaging_plan_state "active" "after channels start" run_rebuild "start-all" section "${agent}: verify restarted state" @@ -647,6 +762,8 @@ run_agent_scenario() { assert_registry_channels "present" "after start" assert_disabled_channels "absent" "after start" assert_provider_records_exist "after start" + assert_host_messaging_config "after start+rebuild" + assert_host_messaging_plan_state "active" "after start+rebuild" } section "Phase 0: Prerequisites"