Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(social): dispatch socialSend through the provider registry
trohitg97f35663bf00
diff --git a/server/nodes/social/_base.py b/server/nodes/social/_base.pyindex 7d872b2f..20b79a9e 100644--- a/server/nodes/social/_base.py+++ b/server/nodes/social/_base.py@@ -6,9 +6,14 @@ platform (WhatsApp, Telegram, Discord, Slack, Signal, SMS, Webchat,Email, Matrix, Teams).Imported by :class:`nodes.social.social_receive.SocialReceiveNode` and-:class:`nodes.social.social_send.SocialSendNode`. Calls into-``nodes.whatsapp._service`` for the WhatsApp bridge stay unchanged — moving-them out is a separate refactor.+:class:`nodes.social.social_send.SocialSendNode`.++This module names no platform on the send path. ``handle_social_send``+resolves the recipient from socialSend's own parameter shape and hands the+payload to whichever adapter the platform's plugin registered with+:mod:`services.plugin.social_provider_registry`. Each adapter owns the mapping+onto its own native parameter names, so adding a platform is one registration+in that plugin's ``__init__.py`` and zero edits here."""import time@@ -373,25 +378,26 @@ async def handle_social_receive(}-async def handle_social_send(node_id: str, node_type: str, parameters: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:+async def handle_social_send(ctx: Any, parameters: Dict[str, Any], node_type: str = "socialSend") -> Dict[str, Any]:"""Handle Social Send node - routes outbound messages to platform.- This node sends messages to the configured platform (WhatsApp, Telegram, etc.)- Also works as an AI Agent tool.-Args:- node_id: The node ID- node_type: The node type (socialSend)+ ctx: The node's NodeContext. Forwarded to the platform handler,+ which needs it to resolve credentials.parameters: Message parameters (channel, recipient, content)- context: Execution context+ node_type: The node type, for the result envelopeReturns:Send result with message_id and status"""start_time = time.time()+ node_id = ctx.node_idtry:- channel = parameters.get("channel", "whatsapp")+ # No default here: SocialSendParams.channel already declares one, and a+ # second copy would drift. An absent value falls through to the+ # unregistered-platform error below, which names what is available.+ channel = parameters.get("channel", "")recipient_type = parameters.get("recipient_type", "phone")message_type = parameters.get("message_type", "text")@@ -411,12 +417,39 @@ async def handle_social_send(node_id: str, node_type: str, parameters: Dict[str,if not recipient:raise ValueError(f"Recipient ({recipient_type}) is required")- # Route to platform-specific handler- if channel == "whatsapp":- result = await _send_via_whatsapp(parameters, recipient, recipient_type, message_type)- else:- # Stub for other platforms - will be implemented as they are integrated- result = {"success": False, "error": f"Platform '{channel}' is not yet implemented", "message_id": None}+ # Route to the platform's registered handler. This function names no+ # platform: each plugin self-registers an adapter from its own+ # __init__.py and owns the mapping onto its native param shape. See+ # services/plugin/social_provider_registry.py.+ #+ # Imported inside the function, not at module scope: tests patch+ # these at their canonical path, and a module-level binding would+ # capture whatever object happened to be installed the first time+ # this module was imported.+ from services.plugin.social_provider_registry import (+ get_social_send_handler,+ registered_platforms,+ )++ handler = get_social_send_handler(channel)+ if handler is None:+ available = ", ".join(sorted(registered_platforms())) or "none"+ raise ValueError(+ f"Platform '{channel}' has no registered send handler. "+ f"Available: {available}. A platform becomes available when its "+ f"plugin package calls register_social_send_handler() on import."+ )++ result = await handler(+ {+ **parameters,+ "channel": channel,+ "recipient": recipient,+ "recipient_type": recipient_type,+ "message_type": message_type,+ },+ ctx,+ )if not result.get("success"):raise Exception(result.get("error", "Send failed"))@@ -450,73 +483,4 @@ async def handle_social_send(node_id: str, node_type: str, parameters: Dict[str,}-async def _send_via_whatsapp(parameters: Dict[str, Any], recipient: str, recipient_type: str, message_type: str) -> Dict[str, Any]:- """Route message to WhatsApp via the social-provider registry.-- Maps socialSend parameters to whatsappSend parameters, then- dispatches through :func:`services.plugin.social_provider_registry.- get_social_send_handler`. The whatsapp plugin self-registers as the- ``"whatsapp"`` platform from its own ``__init__.py`` — no- cross-plugin import from this module.- """- from services.plugin.social_provider_registry import get_social_send_handler-- whatsapp_send_handler = get_social_send_handler("whatsapp")- if whatsapp_send_handler is None:- raise RuntimeError(- "social: 'whatsapp' platform not registered. "- "Check that nodes/whatsapp/__init__.py is imported at startup "- "and calls register_social_send_handler('whatsapp', ...). "- )-- # Map socialSend params to whatsappSend format- whatsapp_params = {- "recipient_type": recipient_type,- "message_type": message_type,- }-- # Set recipient- if recipient_type == "phone":- whatsapp_params["phone"] = recipient- else:- whatsapp_params["group_id"] = recipient-- # Map message content based on type- if message_type == "text":- whatsapp_params["message"] = parameters.get("message", "")-- elif message_type in ("image", "video", "audio", "document", "sticker"):- media_source = parameters.get("media_source", "url")- whatsapp_params["media_source"] = media_source-- if media_source == "url":- whatsapp_params["media_url"] = parameters.get("media_url", "")- elif media_source == "base64":- whatsapp_params["media_data"] = parameters.get("media_data", "")- elif media_source == "file":- whatsapp_params["file_path"] = parameters.get("file_path", "")-- if parameters.get("mime_type"):- whatsapp_params["mime_type"] = parameters["mime_type"]- if parameters.get("caption"):- whatsapp_params["caption"] = parameters["caption"]- if parameters.get("filename"):- whatsapp_params["filename"] = parameters["filename"]-- elif message_type == "location":- whatsapp_params["latitude"] = parameters.get("latitude", 0)- whatsapp_params["longitude"] = parameters.get("longitude", 0)- whatsapp_params["location_name"] = parameters.get("location_name", "")- whatsapp_params["address"] = parameters.get("address", "")-- elif message_type == "contact":- whatsapp_params["contact_name"] = parameters.get("contact_name", "")- whatsapp_params["vcard"] = parameters.get("vcard", "")-- # Reply options- if parameters.get("reply_to_message"):- whatsapp_params["is_reply"] = True- whatsapp_params["reply_message_id"] = parameters.get("reply_message_id", "")-- # Call WhatsApp handler- return await whatsapp_send_handler(whatsapp_params)+__all__ = ["handle_social_receive", "handle_social_send"]diff --git a/server/nodes/social/social_send/__init__.py b/server/nodes/social/social_send/__init__.pyindex bf994306..4cd9f0d2 100644--- a/server/nodes/social/social_send/__init__.py+++ b/server/nodes/social/social_send/__init__.py@@ -26,6 +26,7 @@ class SocialSendParams(BaseModel):# ===== CHANNEL / PLATFORM =====channel: Literal["whatsapp",+ "whatsapp_business","telegram","discord","slack",@@ -403,10 +404,9 @@ class SocialSendNode(ActionNode):from .._base import handle_social_sendresponse = await handle_social_send(- node_id=ctx.node_id,+ ctx,+ params.model_dump(),node_type=self.type,- parameters=params.model_dump(),- context=ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/whatsapp/__init__.py b/server/nodes/whatsapp/__init__.pyindex d80836aa..40be784e 100644--- a/server/nodes/whatsapp/__init__.py+++ b/server/nodes/whatsapp/__init__.py@@ -41,7 +41,7 @@ from ._handlers import WS_HANDLERSfrom ._option_loaders import load_channels, load_group_members, load_groupsfrom ._refresh import refresh_whatsapp_statusfrom ._runtime import WhatsAppRuntime, get_whatsapp_runtime-from ._service import handle_whatsapp_send+from ._social import social_send_adapter# Supervisor: ensures shutdown_all_supervisors() reaches us.# get_instance() constructs the singleton once (lazy in spawn, not here).@@ -81,7 +81,11 @@ register_canary_trigger_type("whatsappReceive", "com.opencompany.whatsapp.messag# registry so the social node dispatches by platform identifier# instead of cross-importing _service.handle_whatsapp_send. See# services/plugin/social_provider_registry.py.-register_social_send_handler("whatsapp", handle_whatsapp_send)+#+# The registered callable is the adapter, not handle_whatsapp_send itself:+# socialSend's payload shape is not whatsappSend's, and translating between+# them is this plugin's job rather than the social node's. See ._social.+register_social_send_handler("whatsapp", social_send_adapter)# Output schemas for the FE variable panel — self-registered so all# whatsapp code stays in this folder (same pattern as telegram).diff --git a/server/nodes/whatsapp/_social.py b/server/nodes/whatsapp/_social.pynew file mode 100644index 00000000..46ada2ca--- /dev/null+++ b/server/nodes/whatsapp/_social.py@@ -0,0 +1,100 @@+"""Adapter mapping ``socialSend``'s generic shape onto whatsapp params.++This body used to live in ``nodes/social/_base.py`` as ``_send_via_whatsapp``,+which meant the platform-neutral social node carried one platform's parameter+names — and would have grown a branch per platform. It lives here now, so the+knowledge of what whatsapp calls a caption stays inside the whatsapp plugin+and ``handle_social_send`` names no platform at all.++Registered as the ``"whatsapp"`` handler from this package's ``__init__.py``.+The registry contract is documented on+:func:`services.plugin.social_provider_registry.register_social_send_handler`:+the payload is ``socialSend``-shaped, and normalising it is the adapter's job.+"""++from __future__ import annotations++from typing import Any, Dict++from ._service import handle_whatsapp_send++# Message types that carry a media payload rather than a text body. Kept as a+# frozenset rather than an inline tuple so the membership test reads as a+# capability check, not a magic list.+_MEDIA_MESSAGE_TYPES = frozenset({"image", "video", "audio", "document", "sticker"})++# socialSend's media_source -> the whatsapp param that carries the payload for+# that source. A dict rather than an if/elif chain so an unknown source is a+# lookup miss (no key written) instead of a silently-skipped branch.+_MEDIA_SOURCE_FIELDS = {+ "url": ("media_url", "media_url"),+ "base64": ("media_data", "media_data"),+ "file": ("file_path", "file_path"),+}++# Optional passthroughs: copied only when truthy, because whatsappSend+# distinguishes "absent" from "empty string" for these.+_OPTIONAL_MEDIA_FIELDS = ("mime_type", "caption", "filename")+++async def social_send_adapter(payload: Dict[str, Any], ctx: Any) -> Dict[str, Any]:+ """Translate a ``socialSend`` payload into ``whatsappSend`` params.++ Args:+ payload: ``socialSend``'s own parameters, plus the resolved+ ``recipient`` and the normalised ``recipient_type`` /+ ``message_type`` that :func:`nodes.social._base.handle_social_send`+ guarantees are present.+ ctx: The node's NodeContext.++ Returns:+ whatsapp's native result dict, passed back to the social node+ untouched.+ """+ recipient = payload.get("recipient", "")+ recipient_type = payload.get("recipient_type", "phone")+ message_type = payload.get("message_type", "text")++ params: Dict[str, Any] = {+ "recipient_type": recipient_type,+ "message_type": message_type,+ }++ # whatsapp addresses individuals by phone and everything else by group jid.+ if recipient_type == "phone":+ params["phone"] = recipient+ else:+ params["group_id"] = recipient++ if message_type == "text":+ params["message"] = payload.get("message", "")++ elif message_type in _MEDIA_MESSAGE_TYPES:+ media_source = payload.get("media_source", "url")+ params["media_source"] = media_source+ source_field = _MEDIA_SOURCE_FIELDS.get(media_source)+ if source_field:+ target, source = source_field+ params[target] = payload.get(source, "")+ for field in _OPTIONAL_MEDIA_FIELDS:+ if payload.get(field):+ params[field] = payload[field]++ elif message_type == "location":+ params["latitude"] = payload.get("latitude", 0)+ params["longitude"] = payload.get("longitude", 0)+ params["location_name"] = payload.get("location_name", "")+ params["address"] = payload.get("address", "")++ elif message_type == "contact":+ params["contact_name"] = payload.get("contact_name", "")+ params["vcard"] = payload.get("vcard", "")++ if payload.get("reply_to_message"):+ params["is_reply"] = True+ params["reply_message_id"] = payload.get("reply_message_id", "")++ return await handle_whatsapp_send(params)+++__all__ = ["social_send_adapter"]diff --git a/server/nodes/whatsapp_business/__init__.py b/server/nodes/whatsapp_business/__init__.pyindex 3be0429e..432512ec 100644--- a/server/nodes/whatsapp_business/__init__.py+++ b/server/nodes/whatsapp_business/__init__.py@@ -14,12 +14,14 @@ from __future__ import annotationsfrom services.deployment.canary_registry import register_canary_trigger_typefrom services.events import register_webhook_sourcefrom services.node_output_schemas import register_output_schema+from services.plugin.social_provider_registry import register_social_send_handlerfrom services.ws_handler_registry import register_option_loaderfrom ._credentials import WhatsAppBusinessCredentialfrom ._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPEfrom ._option_loaders import load_templates+from ._social import social_send_adapterfrom ._source import get_webhook_sourcefrom .whatsapp_business_media import WhatsAppBusinessMediaNode, WhatsAppBusinessMediaOutputfrom .whatsapp_business_receive import (@@ -44,6 +46,11 @@ register_canary_trigger_type(WhatsAppBusinessStatusNode.type, STATUS_UPDATED_TYPregister_option_loader("whatsappBusinessTemplates", load_templates)+# socialSend routes by platform id. Registered under "whatsapp_business", not+# "whatsapp": nodes/whatsapp/ owns that key, and the two share no credential+# and no API.+register_social_send_handler("whatsapp_business", social_send_adapter)+register_output_schema(WhatsAppBusinessSendNode.type, WhatsAppBusinessSendOutput)register_output_schema(WhatsAppBusinessReceiveNode.type, WhatsAppBusinessReceiveOutput)register_output_schema(WhatsAppBusinessStatusNode.type, WhatsAppBusinessStatusOutput)diff --git a/server/nodes/whatsapp_business/_social.py b/server/nodes/whatsapp_business/_social.pynew file mode 100644index 00000000..b11c974e--- /dev/null+++ b/server/nodes/whatsapp_business/_social.py@@ -0,0 +1,83 @@+"""Adapter mapping ``socialSend``'s generic shape onto Cloud API params.++Registered as the ``"whatsapp_business"`` platform from this package's+``__init__.py``. Distinct from ``nodes/whatsapp/`` (the personal-account+bridge), which registers ``"whatsapp"`` — the two share no credential and no+API, so socialSend exposes them as separate channels.++The operations are called on the node itself rather than reimplemented here,+so the Cloud API request shaping, the per-type limits and the error mapping+all stay in one place.+"""++from __future__ import annotations++from typing import Any, Dict++from services.plugin import NodeUserError++# socialSend's media_source vocabulary -> the Cloud API's. socialSend has no+# notion of a pre-uploaded Meta media id, so "id" is unreachable from here;+# base64 arrives as an upload envelope that coerce_file_param understands, so+# it takes the same path as a workspace file.+_MEDIA_SOURCES = {"url": "link", "file": "file", "base64": "file"}+++async def social_send_adapter(payload: Dict[str, Any], ctx: Any) -> Dict[str, Any]:+ """Translate a ``socialSend`` payload into a ``whatsappBusinessSend`` call."""+ from .whatsapp_business_send import (+ WhatsAppBusinessSendNode,+ WhatsAppBusinessSendParams,+ )++ recipient = payload.get("recipient", "")+ message_type = payload.get("message_type", "text")+ node = WhatsAppBusinessSendNode()++ if message_type == "text":+ params = WhatsAppBusinessSendParams(+ operation="send_text",+ to=recipient,+ text=payload.get("message", ""),+ )+ result = await node.send_text(ctx, params)++ elif message_type in {"image", "video", "audio", "document", "sticker"}:+ source = payload.get("media_source", "url")+ params = WhatsAppBusinessSendParams(+ operation="send_media",+ to=recipient,+ media_type=message_type,+ media_source=_MEDIA_SOURCES.get(source, "link"),+ media_url=payload.get("media_url", ""),+ media=payload.get("media_data") or payload.get("file_path"),+ caption=payload.get("caption", ""),+ media_filename=payload.get("filename", ""),+ )+ result = await node.send_media(ctx, params)++ elif message_type == "location":+ params = WhatsAppBusinessSendParams(+ operation="send_location",+ to=recipient,+ latitude=payload.get("latitude", 0),+ longitude=payload.get("longitude", 0),+ location_name=payload.get("location_name", ""),+ location_address=payload.get("address", ""),+ )+ result = await node.send_location(ctx, params)++ else:+ raise NodeUserError(+ f"socialSend cannot send '{message_type}' through WhatsApp Business. "+ "Use text, image, video, audio, document, sticker or location, or "+ "use the whatsappBusinessSend node directly for templates and "+ "interactive messages."+ )++ # The operations raise NodeUserError on failure, so reaching here is+ # success. socialSend keys on this field.+ return {"success": True, **result.model_dump(mode="json", exclude_none=True)}+++__all__ = ["social_send_adapter"]diff --git a/server/services/plugin/social_provider_registry.py b/server/services/plugin/social_provider_registry.pyindex ecf53a83..fe02465c 100644--- a/server/services/plugin/social_provider_registry.py+++ b/server/services/plugin/social_provider_registry.py@@ -17,11 +17,22 @@ Handler signature::- handler(params: Dict[str, Any]) -> Awaitable[Dict[str, Any]]--The social node maps its own parameter shape onto the platform's-expected shape and calls the handler. The handler returns the-platform's native result dict; the social node passes that through.+ handler(payload: Dict[str, Any]) -> Awaitable[Dict[str, Any]]++``payload`` is **socialSend-shaped**, not platform-shaped: it is the node's+own parameters plus a resolved ``recipient`` and the normalised+``channel`` / ``recipient_type`` / ``message_type``. Translating that onto+the platform's native parameter names is the *handler's* job.++That direction is deliberate. The social node previously did the mapping+itself, which meant one platform's parameter names (``media_url``,+``vcard``, ``is_reply``) lived in the platform-neutral module and every new+platform would have added a branch there. Registering an adapter instead+keeps each platform's vocabulary inside its own plugin, so+``handle_social_send`` names no platform at all.++The handler returns the platform's native result dict; the social node+passes it through after checking ``success``."""from __future__ import annotations@@ -31,8 +42,8 @@ from typing import Any, Awaitable, Callable, Dict, Optionalfrom services.plugin.registry import IdempotentRegistry-# (params: Dict) -> Awaitable[Dict]-SocialSendHandler = Callable[[Dict[str, Any]], Awaitable[Dict[str, Any]]]+# (payload: Dict, ctx: NodeContext) -> Awaitable[Dict]+SocialSendHandler = Callable[[Dict[str, Any], Any], Awaitable[Dict[str, Any]]]_REGISTRY: IdempotentRegistry[str, SocialSendHandler] = IdempotentRegistry("social_send_handler")@@ -48,11 +59,12 @@ def register_social_send_handler(platform: str, handler: SocialSendHandler) -> NArgs:platform: Lower-case platform identifier (``"whatsapp"``,``"telegram"``, …). Matches the value the social node's- ``platform`` parameter holds at runtime.- handler: Async function accepting platform-specific- ``params: Dict`` and returning the platform's native- result dict. The social node builds the params dict by- mapping its generic shape onto the platform's keys.+ ``channel`` parameter holds at runtime.+ handler: Async function accepting a socialSend-shaped+ ``payload: Dict`` and the node's ``NodeContext``, returning+ the platform's native result dict. The handler maps the+ generic payload onto its own platform's keys — see the+ module docstring."""_REGISTRY.register(platform, handler)diff --git a/server/tests/test_social_provider_registry.py b/server/tests/test_social_provider_registry.pyindex d4954c39..ea511d23 100644--- a/server/tests/test_social_provider_registry.py+++ b/server/tests/test_social_provider_registry.py@@ -64,21 +64,23 @@ class TestRegistryContract:@pytest.mark.asyncioasync def test_register_then_get_returns_handler(self, fresh_registry):captured = []+ sentinel_ctx = object()- async def fake_handler(params: Dict[str, Any]):- captured.append(params)+ async def fake_handler(payload: Dict[str, Any], ctx: Any):+ captured.append((payload, ctx))return {"sent": True}fresh_registry.register_social_send_handler("whatsapp", fake_handler)handler = fresh_registry.get_social_send_handler("whatsapp")assert handler is fake_handler- result = await handler({"recipient": "+1234567890"})+ result = await handler({"recipient": "+1234567890"}, sentinel_ctx)assert result == {"sent": True}- assert captured == [{"recipient": "+1234567890"}]+ # ctx is forwarded verbatim: handlers resolve credentials through it.+ assert captured == [({"recipient": "+1234567890"}, sentinel_ctx)]def test_idempotent_register_same_callable(self, fresh_registry):- async def h(params):+ async def h(payload, ctx):return {}fresh_registry.register_social_send_handler("whatsapp", h)@@ -86,10 +88,10 @@ class TestRegistryContract:assert fresh_registry.registered_platforms() == frozenset({"whatsapp"})def test_conflicting_register_raises(self, fresh_registry):- async def h1(params):+ async def h1(payload, ctx):return {}- async def h2(params):+ async def h2(payload, ctx):return {}fresh_registry.register_social_send_handler("whatsapp", h1)@@ -97,7 +99,7 @@ class TestRegistryContract:fresh_registry.register_social_send_handler("whatsapp", h2)def test_multiple_platforms_coexist(self, fresh_registry):- async def h(params):+ async def h(payload, ctx):return {}for p in ("whatsapp", "telegram", "slack"):@@ -146,32 +148,97 @@ class TestNoCrossPluginReachInSocialBase:the cross-plugin import behind a runtime import."""from nodes.social import _base as social_base- src = inspect.getsource(social_base._send_via_whatsapp)+ src = inspect.getsource(social_base.handle_social_send)assert "get_social_send_handler" in src, (- "_send_via_whatsapp must call get_social_send_handler "+ "handle_social_send must call get_social_send_handler ""from services.plugin.social_provider_registry. Hardcoded ""fallback imports defeat the plugin-self-registration pattern.")+ def test_dispatcher_names_no_platform(self):+ """The send dispatcher must not branch on a platform name.++ It used to read ``if channel == "whatsapp"`` and stub everything+ else, so socialSend's channel enum advertised platforms that could+ never work. A platform name reappearing here means that branch is+ growing back.+ """+ from nodes.social import _base as social_base++ src = inspect.getsource(social_base.handle_social_send).lower()+ offenders = [p for p in ("whatsapp", "telegram", "discord", "slack") if p in src]+ assert not offenders, (+ f"handle_social_send mentions {offenders}. Platform-specific "+ "parameter mapping belongs in that plugin's registered adapter "+ "(see nodes/whatsapp/_social.py), not in the social node."+ )+class TestWhatsappPluginSelfRegistersAsSocialProvider:- """Importing the whatsapp plugin registers it as the 'whatsapp'- social send handler.+ """Importing a platform plugin registers its social send handler.++ The two WhatsApp plugins are separate platforms: ``nodes/whatsapp/``+ drives a personal account through the Go bridge, ``nodes/whatsapp_business/``+ the official Cloud API. They share no credential and no API, so they+ register under distinct keys and socialSend offers both."""- def test_whatsapp_plugin_import_populates_registry(self):+ @pytest.mark.parametrize(+ "module, platform",+ [+ ("nodes.whatsapp", "whatsapp"),+ ("nodes.whatsapp_business", "whatsapp_business"),+ ],+ )+ def test_plugin_import_populates_registry(self, module, platform):from services.plugin import social_provider_registry as regtry:- __import__("nodes.whatsapp")+ __import__(module)except ImportError as exc: # pragma: no cover- pytest.xfail(f"nodes.whatsapp not importable: {exc}")+ pytest.xfail(f"{module} not importable: {exc}")- handler = reg.get_social_send_handler("whatsapp")+ handler = reg.get_social_send_handler(platform)assert handler is not None, (- "Importing nodes.whatsapp should call "- "register_social_send_handler('whatsapp', handle_whatsapp_send). "+ f"Importing {module} should call "+ f"register_social_send_handler('{platform}', ...). ""Check the __init__.py bottom section.")- # And it should be callable (sanity).assert callable(handler)++ def test_both_whatsapp_platforms_are_distinct(self):+ """A shared key would make one plugin silently shadow the other —+ and, because registration raises on a conflicting callable, would+ break startup instead."""+ from services.plugin import social_provider_registry as reg++ for module in ("nodes.whatsapp", "nodes.whatsapp_business"):+ try:+ __import__(module)+ except ImportError as exc: # pragma: no cover+ pytest.xfail(f"{module} not importable: {exc}")++ personal = reg.get_social_send_handler("whatsapp")+ business = reg.get_social_send_handler("whatsapp_business")+ assert personal is not None and business is not None+ assert personal is not business++ def test_every_registered_platform_is_selectable(self):+ """A registered platform absent from socialSend's channel enum is+ unreachable; an enum entry with no handler is a promise the node+ cannot keep. This catches the first case."""+ from nodes.social.social_send import SocialSendParams+ from services.plugin import social_provider_registry as reg++ for module in ("nodes.whatsapp", "nodes.whatsapp_business"):+ try:+ __import__(module)+ except ImportError as exc: # pragma: no cover+ pytest.xfail(f"{module} not importable: {exc}")++ channels = set(SocialSendParams.model_fields["channel"].annotation.__args__)+ missing = sorted(reg.registered_platforms() - channels)+ assert not missing, (+ f"Registered social platforms {missing} are missing from "+ "SocialSendParams.channel, so socialSend can never dispatch to them."+ )