Skip to content

Self-improving AI Employees for everyone

refactor(telegram): self-contained plugin folder + 5 generic registries

trohitgf4f4e9884bce
diff --git a/server/nodes/telegram/__init__.py b/server/nodes/telegram/__init__.py
index 104187b6..8b31e4dc 100644
--- a/server/nodes/telegram/__init__.py
+++ b/server/nodes/telegram/__init__.py
@@ -1 +1,65 @@
-"""Plugins for the 'telegram' palette group. See ../__init__.py for the package layout."""
+"""Plugins for the 'telegram' palette group.
+
+This package owns the entire telegram surface area; nothing telegram-
+specific lives outside this folder. Cross-cutting concerns plug into
+generic registries that the consumers (router, broadcaster, event
+waiter, trigger handler) read at dispatch time:
+
+ _credentials.py TelegramCredential (api-key)
+ _service.py TelegramService (singleton bot lifecycle)
+ _handlers.py WebSocket handlers + WS_HANDLERS dispatch dict
+ _filters.py build_telegram_filter (event-waiter filter)
+ _refresh.py refresh_telegram_status (broadcaster hook)
+ precheck_telegram_trigger (trigger pre-check)
+ telegram_send.py workflow ActionNode + AI tool
+ telegram_receive.py workflow TriggerNode
+
+On import, this package self-registers four callbacks:
+
+ 1. WS handlers -> services.ws_handler_registry
+ 2. Event filter -> services.event_waiter.FILTER_BUILDERS
+ 3. Trigger precheck-> services.event_waiter._TRIGGER_PRECHECKS
+ 4. Status refresh -> services.status_broadcaster._SERVICE_REFRESH_CALLBACKS
+
+Adding a new plugin folder follows the same shape -- consumers do not
+need to learn its name.
+
+External callers should depend on the public re-exports below; the
+underscore-prefixed modules are implementation detail.
+"""
+
+from __future__ import annotations
+
+from services.event_waiter import register_filter_builder, register_trigger_precheck
+from services.node_output_schemas import register_output_schema
+from services.status_broadcaster import register_service_refresh
+from services.ws_handler_registry import register_ws_handlers
+
+from ._credentials import TelegramCredential
+from ._filters import build_telegram_filter
+from ._handlers import WS_HANDLERS
+from ._refresh import precheck_telegram_trigger, refresh_telegram_status
+from ._service import TelegramService, get_telegram_service
+
+# Telegram plugin classes -- importing them runs __init_subclass__ which
+# slots them into the plugin/node registries (handled by services.plugin).
+from .telegram_receive import TelegramReceiveNode, TelegramReceiveOutput
+from .telegram_send import TelegramSendNode, TelegramSendOutput
+
+# --- self-registration on import -------------------------------------------
+register_ws_handlers(WS_HANDLERS)
+register_filter_builder("telegramReceive", build_telegram_filter)
+register_trigger_precheck("telegramReceive", precheck_telegram_trigger)
+register_service_refresh(refresh_telegram_status)
+register_output_schema("telegramReceive", TelegramReceiveOutput)
+register_output_schema("telegramSend", TelegramSendOutput)
+
+__all__ = [
+ "TelegramCredential",
+ "TelegramService",
+ "WS_HANDLERS",
+ "build_telegram_filter",
+ "get_telegram_service",
+ "precheck_telegram_trigger",
+ "refresh_telegram_status",
+]
diff --git a/server/nodes/telegram/_filters.py b/server/nodes/telegram/_filters.py
new file mode 100644
index 00000000..1e6a61bc
--- /dev/null
+++ b/server/nodes/telegram/_filters.py
@@ -0,0 +1,122 @@
+"""Telegram event filter builder.
+
+Moved from ``services/event_waiter.build_telegram_filter`` so the
+generic ``event_waiter`` module no longer imports anything telegram-
+specific. The builder is published into
+``event_waiter.FILTER_BUILDERS`` via ``register_filter_builder()`` from
+this package's ``__init__.py``.
+
+Lazy ``owner_chat_id`` lookup goes through the local
+:class:`TelegramService` -- no import path leaks outside the plugin
+folder.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Callable, Dict
+
+logger = logging.getLogger(__name__)
+
+
+def build_telegram_filter(params: Dict) -> Callable[[Dict], bool]:
+ """Build a filter function for Telegram messages.
+
+ Sender filter values:
+ all, self, private, group, supergroup, channel,
+ specific_chat, specific_user, keywords
+
+ Legacy parameters (back-compat): chatTypeFilter, chat_id, from_user,
+ keywords, ignoreBots.
+
+ Event data fields originate from
+ :meth:`TelegramService._format_message`.
+ """
+ sender_filter = params.get("sender_filter", "")
+
+ # Legacy fallback
+ if not sender_filter:
+ chat_type_filter = params.get("chat_type_filter", "all")
+ old_chat_id = params.get("chat_id", "")
+ old_from_user = params.get("from_user", "")
+ old_keywords = params.get("keywords", "")
+
+ if old_chat_id:
+ sender_filter = "specific_chat"
+ elif old_from_user:
+ sender_filter = "specific_user"
+ elif old_keywords:
+ sender_filter = "keywords"
+ elif chat_type_filter != "all":
+ sender_filter = chat_type_filter
+ else:
+ sender_filter = "all"
+
+ content_type_filter = params.get("content_type_filter", "all")
+ chat_id_filter = params.get("chat_id", "")
+ from_user_filter = params.get("from_user", "")
+ keywords = [
+ k.strip().lower() for k in params.get("keywords", "").split(",") if k.strip()
+ ]
+ ignore_bots = params.get("ignore_bots", True)
+ owner_chat_id = params.get("_owner_chat_id")
+
+ logger.debug(
+ f"[TelegramFilter] Built: sender={sender_filter}, "
+ f"content_type={content_type_filter}, owner_chat_id={owner_chat_id}"
+ )
+
+ def _get_owner_chat_id() -> object:
+ """Lazy lookup from the local service -- handles owner detected
+ after the filter was built (first private message captures it)."""
+ if owner_chat_id:
+ return owner_chat_id
+ try:
+ from ._service import get_telegram_service
+
+ return get_telegram_service().owner_chat_id
+ except Exception:
+ return None
+
+ def matches(m: Dict) -> bool:
+ if content_type_filter != "all":
+ if m.get("content_type", "") != content_type_filter:
+ return False
+
+ if sender_filter == "self":
+ current_owner = _get_owner_chat_id()
+ if not current_owner:
+ logger.debug("[TelegramFilter] Rejecting: owner_chat_id not available")
+ return False
+ if str(m.get("from_id", "")) != str(current_owner):
+ return False
+
+ elif sender_filter in ("private", "group", "supergroup", "channel"):
+ if m.get("chat_type", "") != sender_filter:
+ return False
+
+ elif sender_filter == "specific_chat":
+ if chat_id_filter and str(m.get("chat_id", "")) != str(chat_id_filter):
+ return False
+
+ elif sender_filter == "specific_user":
+ if from_user_filter and str(m.get("from_id", "")) != str(from_user_filter):
+ return False
+
+ elif sender_filter == "keywords":
+ if keywords:
+ text = (m.get("text") or "").lower()
+ if not any(kw in text for kw in keywords):
+ return False
+
+ # Ignore bot messages (skip for 'self' filter)
+ if sender_filter != "self" and ignore_bots and m.get("is_bot", False):
+ return False
+
+ logger.debug(
+ f"[TelegramFilter] Matched message from "
+ f"{m.get('from_username', m.get('from_id'))}"
+ )
+ return True
+
+ return matches
diff --git a/server/nodes/telegram/_handlers.py b/server/nodes/telegram/_handlers.py
new file mode 100644
index 00000000..66622253
--- /dev/null
+++ b/server/nodes/telegram/_handlers.py
@@ -0,0 +1,193 @@
+"""Telegram WebSocket handlers — moved from routers/websocket.py.
+
+Owned by the plugin folder (same place the credential, service, and the
+two workflow nodes live). The router only registers the dict
+:data:`WS_HANDLERS` so a future plugin-discovery hook can pick this up
+without touching the core router.
+
+Wire format unchanged — frontend message ``type`` strings continue to
+match. Auth lookups previously used raw ``auth.get_api_key`` calls;
+those have been collapsed into a single :class:`TelegramCredential`
+``resolve()`` (the credential class already declares the keys it owns
+via ``id`` and ``extra_fields``).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Awaitable, Callable, Dict
+
+from fastapi import WebSocket
+
+from ._credentials import TelegramCredential
+from ._service import get_telegram_service
+
+logger = logging.getLogger(__name__)
+
+
+# ---------------------------------------------------------------------------
+# Send-method dispatch table -- replaces the long if/elif chain that was
+# previously inlined in handle_telegram_send.
+# ---------------------------------------------------------------------------
+
+
+def _send_text(svc, data, parse_mode):
+ text = data.get("text")
+ if not text:
+ return None, "text required for text message"
+ return svc.send_message(
+ chat_id=data["chat_id"], text=text, parse_mode=parse_mode,
+ ), None
+
+
+def _send_photo(svc, data, parse_mode):
+ photo_url = data.get("media_url")
+ if not photo_url:
+ return None, "media_url required for photo"
+ return svc.send_photo(
+ chat_id=data["chat_id"], photo=photo_url,
+ caption=data.get("caption"), parse_mode=parse_mode,
+ ), None
+
+
+def _send_document(svc, data, parse_mode):
+ doc_url = data.get("media_url")
+ if not doc_url:
+ return None, "media_url required for document"
+ return svc.send_document(
+ chat_id=data["chat_id"], document=doc_url,
+ caption=data.get("caption"), parse_mode=parse_mode,
+ ), None
+
+
+def _send_location(svc, data, parse_mode):
+ lat, lon = data.get("latitude"), data.get("longitude")
+ if lat is None or lon is None:
+ return None, "latitude and longitude required"
+ return svc.send_location(
+ chat_id=data["chat_id"], latitude=float(lat), longitude=float(lon),
+ ), None
+
+
+def _send_contact(svc, data, parse_mode):
+ phone, first_name = data.get("phone_number"), data.get("first_name")
+ if not phone or not first_name:
+ return None, "phone_number and first_name required"
+ return svc.send_contact(
+ chat_id=data["chat_id"], phone_number=phone, first_name=first_name,
+ last_name=data.get("last_name"),
+ ), None
+
+
+_SEND_DISPATCH: Dict[str, Callable] = {
+ "text": _send_text,
+ "photo": _send_photo,
+ "document": _send_document,
+ "location": _send_location,
+ "contact": _send_contact,
+}
+
+
+# ---------------------------------------------------------------------------
+# Handlers — one per `telegram_*` WebSocket message type.
+# ---------------------------------------------------------------------------
+
+
+async def handle_telegram_connect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Connect to Telegram. Service reads stored token from credentials
+ when payload omits it — DB is the source of truth, the frontend saves
+ via save_api_key first."""
+ return await get_telegram_service().connect(data.get("token"))
+
+
+async def handle_telegram_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Stop polling. Stored token stays in DB; explicit delete_api_key removes it."""
+ return await get_telegram_service().disconnect()
+
+
+async def handle_telegram_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ service = get_telegram_service()
+ status = service.get_status()
+ status["has_stored_token"] = await service.has_stored_token()
+ return {"success": True, "status": status}
+
+
+async def handle_telegram_send(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Direct send via WebSocket (not via workflow node)."""
+ service = get_telegram_service()
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+ if not data.get("chat_id"):
+ return {"success": False, "error": "chat_id required"}
+
+ message_type = data.get("message_type", "text")
+ dispatch = _SEND_DISPATCH.get(message_type)
+ if dispatch is None:
+ return {"success": False, "error": f"Unsupported message type: {message_type}"}
+
+ try:
+ coro_or_none, err = dispatch(service, data, data.get("parse_mode"))
+ if err:
+ return {"success": False, "error": err}
+ result = await coro_or_none
+ return {"success": True, "result": result}
+ except Exception as e:
+ logger.error(f"[Telegram] Send error: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def handle_telegram_reconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Reconnect using stored bot token from encrypted credentials.
+
+ The service's ``connect()`` already pulls the token from
+ :class:`TelegramCredential` when omitted, so this handler is now a
+ thin wrapper that surfaces a clearer "no stored token" error before
+ calling through. Owner restoration also happens inside ``connect()``.
+ """
+ try:
+ secrets = await TelegramCredential.resolve()
+ except PermissionError:
+ return {"success": False, "error": "No stored bot token found. Enter token to connect."}
+
+ if not secrets.get("api_key"):
+ return {"success": False, "error": "No stored bot token found. Enter token to connect."}
+
+ return await get_telegram_service().connect(secrets["api_key"])
+
+
+async def handle_telegram_get_me(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ service = get_telegram_service()
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+ try:
+ return {"success": True, "result": await service.get_me()}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
+async def handle_telegram_get_chat(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ service = get_telegram_service()
+ if not service.connected:
+ return {"success": False, "error": "Telegram bot not connected"}
+ if not data.get("chat_id"):
+ return {"success": False, "error": "chat_id required"}
+ try:
+ return {"success": True, "result": await service.get_chat(data["chat_id"])}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
+# ---------------------------------------------------------------------------
+# Registration — public surface consumed by routers/websocket.py.
+# ---------------------------------------------------------------------------
+
+
+WS_HANDLERS: Dict[str, Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]] = {
+ "telegram_connect": handle_telegram_connect,
+ "telegram_disconnect": handle_telegram_disconnect,
+ "telegram_reconnect": handle_telegram_reconnect,
+ "telegram_status": handle_telegram_status,
+ "telegram_send": handle_telegram_send,
+ "telegram_get_me": handle_telegram_get_me,
+ "telegram_get_chat": handle_telegram_get_chat,
+}
diff --git a/server/nodes/telegram/_refresh.py b/server/nodes/telegram/_refresh.py
new file mode 100644
index 00000000..7b39b10a
--- /dev/null
+++ b/server/nodes/telegram/_refresh.py
@@ -0,0 +1,106 @@
+"""Telegram service-status refresh callback.
+
+Moved from ``services/status_broadcaster._refresh_telegram_status``.
+The broadcaster no longer hardcodes a per-service refresh — instead
+plugin packages register their own callback via
+``status_broadcaster.register_service_refresh``.
+
+The callback runs once per WebSocket client connect (inside the
+``_refresh_all_services`` TaskGroup). Auth reads + owner restore
+happen inside :class:`TelegramService`; this function just decides
+whether to attempt an auto-reconnect and mirrors the resulting status
+into the broadcaster cache.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Dict, TYPE_CHECKING
+
+from opentelemetry import trace
+
+if TYPE_CHECKING:
+ from services.status_broadcaster import StatusBroadcaster
+
+logger = logging.getLogger(__name__)
+tracer = trace.get_tracer(__name__)
+
+
+async def refresh_telegram_status(broadcaster: "StatusBroadcaster") -> None:
+ """Refresh Telegram cache on the broadcaster and auto-reconnect if needed.
+
+ Called once per ``_refresh_all_services`` cycle. OTel span emitted
+ so cold-start ``getMe`` time is observable -- the historical
+ bottleneck on local DNS for the first WebSocket connect.
+ """
+ with tracer.start_as_current_span("broadcaster.refresh_telegram") as span:
+ try:
+ from ._service import get_telegram_service
+
+ service = get_telegram_service()
+
+ def _snapshot(connected: bool, has_token: bool) -> Dict[str, Any]:
+ s = service.get_status()
+ return {
+ "connected": connected,
+ "bot_id": s.get("bot_id") if connected else None,
+ "bot_username": s.get("bot_username") if connected else None,
+ "bot_name": s.get("bot_name") if connected else None,
+ "owner_chat_id": s.get("owner_chat_id") if connected else None,
+ "has_stored_token": has_token,
+ }
+
+ if service.connected:
+ broadcaster._status["telegram"] = _snapshot(True, True)
+ span.set_attribute("path", "already_connected")
+ elif not await service.has_stored_token():
+ broadcaster._status["telegram"] = _snapshot(False, False)
+ span.set_attribute("path", "no_token")
+ else:
+ span.set_attribute("path", "auto_reconnect")
+ logger.info("[StatusBroadcaster] Auto-reconnecting Telegram bot...")
+ result = await service.connect()
+ ok = bool(result.get("success"))
+ broadcaster._status["telegram"] = _snapshot(ok, True)
+ span.set_attribute("reconnect_ok", ok)
+ if ok:
+ bot_username = broadcaster._status["telegram"].get("bot_username")
+ logger.info(
+ f"[StatusBroadcaster] Telegram auto-reconnected: @{bot_username}"
+ )
+ else:
+ logger.warning(
+ f"[StatusBroadcaster] Telegram auto-reconnect failed: "
+ f"{result.get('error')}"
+ )
+
+ await broadcaster.broadcast({
+ "type": "telegram_status",
+ "data": broadcaster._status["telegram"],
+ })
+ span.set_attribute(
+ "connected", bool(broadcaster._status["telegram"]["connected"])
+ )
+ except Exception as e:
+ span.record_exception(e)
+ logger.debug(f"[StatusBroadcaster] Could not refresh Telegram status: {e}")
+
+
+async def precheck_telegram_trigger(parameters: Dict) -> str | None:
+ """Trigger-precheck: ensure the Telegram bot is connected before
+ entering the event-wait loop.
+
+ Returns an error string to short-circuit, or None to proceed.
+ """
+ from ._service import get_telegram_service
+
+ service = get_telegram_service()
+ if not service.connected:
+ return "Telegram bot not connected. Add bot token in Credentials."
+ sender_filter = parameters.get("sender_filter", "all")
+ logger.info(
+ "[TelegramTrigger] starting "
+ f"sender_filter={sender_filter} "
+ f"owner_detected={service.owner_chat_id is not None}"
+ )
+ return None
diff --git a/server/services/telegram_service.py b/server/nodes/telegram/_service.py
similarity index 60%
rename from server/services/telegram_service.py
rename to server/nodes/telegram/_service.py
index bcdbbd09..d7994fd1 100644
--- a/server/services/telegram_service.py
+++ b/server/nodes/telegram/_service.py
@@ -1,21 +1,56 @@
+"""Telegram bot service — moved from services/ to nodes/ as the
+plugin-first home for all telegram business logic.
+
+Public surface (consumed by `_handlers.py`, `telegram_send.py`,
+`telegram_receive.py`, and the global `status_broadcaster`):
+
+ get_telegram_service() -> TelegramService module-level singleton
+
+ service.connect(token=None) -> dict idempotent connect; reads
+ token from TelegramCredential
+ when omitted
+ service.disconnect() -> dict
+ service.connected: bool
+ service.owner_chat_id: int | None
+ service.has_stored_token() -> bool
+ service.set_owner(chat_id) -> None
+ service.get_status() -> dict
+
+ service.send_message / send_photo / send_document /
+ service.send_location / send_contact send helpers; the
+ parse-mode fallback on
+ `BadRequest("can't parse
+ entities")` is folded into
+ a single helper instead of
+ being copy-pasted four
+ times.
+
+ service.get_me() / service.get_chat(id) direct API helpers used by
+ the non-workflow WebSocket
+ handlers.
+
+Auth lookups go through :class:`TelegramCredential.resolve` (lifted from
+the per-key ``auth.get_api_key("telegram_bot_token")`` / ``..._owner_chat_id``
+calls scattered across the previous handler/router code). The credential
+class stays declarative — :class:`ApiKeyCredential` does the heavy lifting,
+this service just consumes the resolved dict.
"""
-Telegram Bot Integration Service
-Uses python-telegram-bot v22.6 for Bot API communication.
-Singleton service with background polling for receiving updates.
-"""
+from __future__ import annotations
import asyncio
import logging
import os
from datetime import datetime
-from typing import Any, Dict, Optional
+from typing import Any, Awaitable, Callable, Dict, Optional
from telegram import Bot, Update
from telegram.error import BadRequest, NetworkError
from telegram.ext import Application, ContextTypes, MessageHandler, filters
from telegram.helpers import escape_markdown
+from ._credentials import TelegramCredential
+
logger = logging.getLogger(__name__)
@@ -36,30 +71,26 @@ class TelegramService:
@classmethod
def get_instance(cls) -> "TelegramService":
- """Get singleton instance."""
if cls._instance is None:
cls._instance = cls()
return cls._instance
@classmethod
async def reset_instance(cls):
- """Reset singleton (for testing)."""
if cls._instance:
await cls._instance.disconnect()
cls._instance = None
@property
def connected(self) -> bool:
- """Check if bot is connected and polling."""
return self._connected and self._application is not None
@property
def owner_chat_id(self) -> Optional[int]:
- """Get the bot owner's chat ID (auto-captured from first private message).
- Falls back to TELEGRAM_OWNER_CHAT_ID env var if not auto-detected."""
+ """Bot owner's chat ID (auto-captured on first private message).
+ Falls back to TELEGRAM_OWNER_CHAT_ID env var."""
if self._owner_chat_id:
return self._owner_chat_id
- # Fallback: TELEGRAM_OWNER_CHAT_ID env var
env_owner = os.environ.get("TELEGRAM_OWNER_CHAT_ID")
if env_owner:
try:
@@ -70,12 +101,10 @@ class TelegramService:
return None
async def set_owner(self, chat_id: int):
- """Set owner chat_id (used to restore from credentials on reconnect)."""
self._owner_chat_id = chat_id
logger.info(f"[Telegram] Owner chat_id restored: {chat_id}")
def get_status(self) -> Dict[str, Any]:
- """Get current connection status."""
return {
"connected": self._connected,
"bot_id": self._bot_info.get("id"),
@@ -85,11 +114,17 @@ class TelegramService:
"owner_chat_id": self._owner_chat_id,
}
+ # =========================================================================
+ # Connection lifecycle
+ # =========================================================================
+
async def has_stored_token(self) -> bool:
- """Whether a ``telegram_bot_token`` is persisted in auth credentials."""
- from core.container import container
- auth = container.auth_service()
- return bool(await auth.get_api_key("telegram_bot_token"))
+ """Whether `telegram_bot_token` is persisted in auth credentials."""
+ try:
+ secrets = await TelegramCredential.resolve()
+ return bool(secrets.get("api_key"))
+ except PermissionError:
+ return False
async def connect(self, token: Optional[str] = None) -> Dict[str, Any]:
"""Connect to Telegram with bot token and start polling.
@@ -97,38 +132,33 @@ class TelegramService:
When ``token`` is omitted, falls back to the stored
``telegram_bot_token`` credential — matches the Twitter/Google
OAuth pattern where the frontend saves credentials first and then
- calls connect. On success the token is persisted (idempotent) and
- any previously captured owner chat id is restored.
-
- Args:
- token: Bot token from @BotFather. Optional when a token has
- already been saved via ``auth_service.store_api_key``.
+ calls connect.
- Returns:
- Connection result with bot info
+ Idempotent: if already connected, returns success without tearing
+ down the working bot. See the in-line comment block for the race
+ this guards against.
"""
- from core.container import container
- auth = container.auth_service()
-
+ # Resolve credentials via the declarative class instead of raw
+ # ``auth.get_api_key("telegram_bot_token")`` / ``..._owner_chat_id``
+ # lookups. Keeps the credential id in one place.
+ secrets: Dict[str, Any] = {}
if not token:
- token = await auth.get_api_key("telegram_bot_token")
+ try:
+ secrets = await TelegramCredential.resolve()
+ token = secrets.get("api_key")
+ except PermissionError:
+ pass
if not token:
return {"success": False, "error": "Bot token required"}
+
async with self._lock:
- # Idempotent: if already connected, return success without
- # tearing down. The previous disconnect-then-rebuild logic
- # caused a race when multiple WebSocket clients triggered
- # _refresh_telegram_status concurrently — the first one
- # connected the bot, the second saw _connected=True inside
- # the lock and tore down the working bot, leaving a 1-2s
- # window where in-flight send_message calls hung on a closed
- # httpx transport until the 10s read_timeout fired.
- #
- # Genuine reconnect (e.g. new token) should call disconnect()
- # explicitly first, then connect().
+ # Idempotent: avoid the disconnect-then-rebuild race that
+ # caused intermittent ``send_message`` hangs against a closed
+ # httpx transport when concurrent _refresh_telegram_status
+ # tasks fired on overlapping WebSocket connects.
if self._connected:
logger.debug(
- f"[Telegram] connect() called while already connected to "
+ "[Telegram] connect() called while already connected to "
f"@{self._bot_info.get('username')}, returning success",
)
return {
@@ -142,21 +172,13 @@ class TelegramService:
try:
logger.info("[Telegram] Connecting with bot token...")
- # Create bot and validate token
- bot = Bot(token=token)
- me = await bot.get_me()
-
- self._bot_info = {
- "id": me.id,
- "username": me.username,
- "first_name": me.first_name,
- "can_join_groups": me.can_join_groups,
- "can_read_all_group_messages": me.can_read_all_group_messages,
- }
-
- logger.info(f"[Telegram] Bot validated: @{me.username} (ID: {me.id})")
-
- # Build application
+ # Build application. Bot info is populated by
+ # ``application.initialize()`` below (it calls getMe once
+ # and caches on the bot instance) — the previous code
+ # also called ``bot.get_me()`` on a separate throwaway
+ # Bot before building the Application, paying for a
+ # second redundant network round-trip on every cold
+ # start. Drop that — single round-trip now.
self._application = (
Application.builder()
.token(token)
@@ -173,25 +195,36 @@ class TelegramService:
)
self._bot = self._application.bot
self._token = token
-
- # Register message handler for all messages
self._application.add_handler(
MessageHandler(filters.ALL, self._on_message_received)
)
- # Initialize application
await self._application.initialize()
- # Start polling in background task
+ me = self._bot
+ self._bot_info = {
+ "id": me.id,
+ "username": me.username,
+ "first_name": me.first_name,
+ "can_join_groups": me.can_join_groups,
+ "can_read_all_group_messages": me.can_read_all_group_messages,
+ }
+ logger.info(f"[Telegram] Bot validated: @{me.username} (ID: {me.id})")
+
self._polling_task = asyncio.create_task(self._run_polling())
self._connected = True
- # Broadcast status update
await self._broadcast_status()
# Hydrate runtime owner_chat_id from stored credential.
- # The DB is the source of truth; connect only reads.
- saved_owner = await auth.get_api_key("telegram_owner_chat_id")
+ saved_owner = secrets.get("telegram_owner_chat_id")
+ if saved_owner is None:
+ try:
+ saved_owner = (await TelegramCredential.resolve()).get(
+ "telegram_owner_chat_id"
+ )
+ except PermissionError:
+ saved_owner = None
if saved_owner:
try:
self._owner_chat_id = int(saved_owner)
@@ -199,7 +232,6 @@ class TelegramService:
pass
logger.info(f"[Telegram] Connected and polling started for @{me.username}")
-
return {
"success": True,
"bot": self._bot_info,
@@ -211,30 +243,21 @@ class TelegramService:
self._connected = False
self._application = None
self._bot = None
- return {
- "success": False,
- "error": str(e),
- }
+ return {"success": False, "error": str(e)}
async def disconnect(self) -> Dict[str, Any]:
- """Disconnect bot and stop polling."""
async with self._lock:
return await self._disconnect_internal()
async def _disconnect_internal(self) -> Dict[str, Any]:
- """Internal disconnect (must be called with lock held)."""
try:
logger.info("[Telegram] Disconnecting...")
-
- # Cancel polling task
if self._polling_task and not self._polling_task.done():
self._polling_task.cancel()
try:
await self._polling_task
except asyncio.CancelledError:
pass
-
- # Stop and shutdown application
if self._application:
try:
await self._application.stop()
@@ -250,25 +273,24 @@ class TelegramService:
self._owner_chat_id = None
self._bot_info = {}
- # Broadcast disconnected status
await self._broadcast_status()
-
logger.info("[Telegram] Disconnected")
return {"success": True, "message": "Disconnected"}
-
except Exception as e:
logger.error(f"[Telegram] Disconnect error: {e}")
return {"success": False, "error": str(e)}
+ # =========================================================================
+ # Polling loop
+ # =========================================================================
+
def _on_polling_error(self, error) -> None:
- """Handle polling errors (called by PTB's internal retry loop)."""
if isinstance(error, NetworkError):
logger.debug(f"[Telegram] Network error during polling (auto-retrying): {error}")
else:
logger.error(f"[Telegram] Polling error: {error}")
async def _run_polling(self):
- """Run polling loop in background."""
try:
logger.info("[Telegram] Starting polling loop...")
await self._application.start()
@@ -277,11 +299,8 @@ class TelegramService:
allowed_updates=Update.ALL_TYPES,
error_callback=self._on_polling_error,
)
-
- # Keep running until cancelled
while True:
await asyncio.sleep(1)
-
except asyncio.CancelledError:
logger.info("[Telegram] Polling cancelled")
raise
@@ -291,41 +310,51 @@ class TelegramService:
await self._broadcast_status()
async def _on_message_received(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
- """Handle incoming messages and dispatch to event_waiter."""
try:
if not update.message:
return
-
msg = update.message
# Auto-capture bot owner from first private message
- if self._owner_chat_id is None and msg.chat.type == "private" and msg.from_user:
+ if (
+ self._owner_chat_id is None
+ and msg.chat.type == "private"
+ and msg.from_user
+ ):
self._owner_chat_id = msg.from_user.id
- logger.info(f"[Telegram] Owner detected: @{msg.from_user.username} (ID: {msg.from_user.id})")
- # Persist to credentials DB so it survives reconnects
+ logger.info(
+ f"[Telegram] Owner detected: @{msg.from_user.username} "
+ f"(ID: {msg.from_user.id})"
+ )
try:
from core.container import container
auth = container.auth_service()
- await auth.store_api_key("telegram_owner_chat_id", str(msg.from_user.id), models=[])
+ await auth.store_api_key(
+ "telegram_owner_chat_id",
+ str(msg.from_user.id),
+ models=[],
+ )
except Exception as persist_err:
- logger.warning(f"[Telegram] Failed to persist owner chat_id: {persist_err}")
+ logger.warning(
+ f"[Telegram] Failed to persist owner chat_id: {persist_err}"
+ )
await self._broadcast_status()
event_data = self._format_message(msg)
+ logger.info(
+ f"[Telegram] Message received: {event_data.get('content_type')} from "
+ f"{event_data.get('from_username', event_data.get('from_id'))}, "
+ f"chat_type={event_data.get('chat_type')}"
+ )
- logger.info(f"[Telegram] Message received: {event_data.get('content_type')} from {event_data.get('from_username', event_data.get('from_id'))}, chat_type={event_data.get('chat_type')}")
-
- # Dispatch to event_waiter for trigger nodes
from services import event_waiter
resolved = event_waiter.dispatch("telegram_message_received", event_data)
logger.info(f"[Telegram] Dispatched to {resolved} waiter(s)")
-
except Exception as e:
logger.error(f"[Telegram] Message handler error: {e}")
def _format_message(self, msg) -> Dict[str, Any]:
"""Format Telegram message to unified event data."""
- # Determine content type
content_type = "text"
if msg.photo:
content_type = "photo"
@@ -346,11 +375,10 @@ class TelegramService:
elif msg.poll:
content_type = "poll"
- # Build event data
data = {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
- "chat_type": msg.chat.type, # private, group, supergroup, channel
+ "chat_type": msg.chat.type,
"chat_title": msg.chat.title,
"from_id": msg.from_user.id if msg.from_user else None,
"from_username": msg.from_user.username if msg.from_user else None,
@@ -363,9 +391,7 @@ class TelegramService:
"reply_to_message_id": msg.reply_to_message.message_id if msg.reply_to_message else None,
}
- # Add media info if present
if msg.photo:
- # Get largest photo
photo = msg.photo[-1]
data["photo"] = {
"file_id": photo.file_id,
@@ -393,11 +419,9 @@ class TelegramService:
"last_name": msg.contact.last_name,
"user_id": msg.contact.user_id,
}
-
return data
async def _broadcast_status(self):
- """Broadcast connection status to all WebSocket clients."""
try:
from services.status_broadcaster import get_status_broadcaster
broadcaster = get_status_broadcaster()
@@ -412,17 +436,11 @@ class TelegramService:
logger.warning(f"[Telegram] Status broadcast failed: {e}")
# =========================================================================
- # Send Methods
+ # Send helpers — parse-mode preprocessing + BadRequest fallback in one place
# =========================================================================
@staticmethod
- def _escape_text(text: str, parse_mode: Optional[str]) -> str:
- """Escape reserved characters for the given parse mode.
-
- MarkdownV2 reserves: _ * [ ] ( ) ~ ` > # + - = | { } . !
- Markdown (v1) reserves: _ * ` [
- HTML: no escaping needed (Telegram handles it).
- """
+ def _escape_text(text: Optional[str], parse_mode: Optional[str]) -> Optional[str]:
if not text or not parse_mode:
return text
if parse_mode == "MarkdownV2":
@@ -432,66 +450,79 @@ class TelegramService:
return text
@staticmethod
- def _format_auto(text: str) -> tuple[str, str]:
- """Convert GFM markdown to Telegram HTML using markdown-it-py.
-
- Returns (formatted_text, parse_mode) tuple.
- """
+ def _format_auto(text: Optional[str]) -> tuple[Optional[str], str]:
if not text:
return text, "HTML"
from services.markdown_formatter import to_telegram_html
return to_telegram_html(text), "HTML"
- async def send_message(
- self,
- chat_id: str | int,
- text: str,
- parse_mode: Optional[str] = None,
- disable_notification: bool = False,
- reply_to_message_id: Optional[int] = None,
- ) -> Dict[str, Any]:
- """Send a text message.
-
- Args:
- chat_id: Chat ID or @username
- text: Message text
- parse_mode: 'HTML', 'Markdown', 'MarkdownV2', or 'Auto'
- disable_notification: Send silently
- reply_to_message_id: Reply to this message
-
- Returns:
- Sent message info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
+ @classmethod
+ def _resolve_body(
+ cls, body: Optional[str], parse_mode: Optional[str]
+ ) -> tuple[Optional[str], Optional[str]]:
+ """Apply parse-mode preprocessing to a text/caption. Returns
+ ``(body, effective_parse_mode)``."""
if parse_mode == "Auto":
- safe_text, effective_pm = self._format_auto(text)
- else:
- effective_pm = parse_mode if parse_mode else None
- safe_text = self._escape_text(text, effective_pm)
+ return cls._format_auto(body)
+ return cls._escape_text(body, parse_mode), parse_mode or None
+ async def _send_with_parse_fallback(
+ self,
+ method: Callable[..., Awaitable[Any]],
+ *,
+ body_kw: str,
+ body: Optional[str],
+ parse_mode: Optional[str],
+ **kwargs: Any,
+ ) -> Any:
+ """Call ``method(**{body_kw: processed_body, parse_mode: pm}, **kwargs)``;
+ on Telegram ``BadRequest("can't parse entities")`` retry once with the
+ raw body and ``parse_mode=None``. Folds 4 copies of the same try/except
+ into a single helper.
+ """
+ processed, effective_pm = self._resolve_body(body, parse_mode)
try:
- msg = await self._bot.send_message(
- chat_id=chat_id,
- text=safe_text,
+ return await method(
+ **{body_kw: processed},
parse_mode=effective_pm,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
+ **kwargs,
)
except BadRequest as e:
if "can't parse entities" in str(e).lower() and effective_pm:
- logger.warning(f"[Telegram] Parse mode {effective_pm} failed, sending as plain text")
- msg = await self._bot.send_message(
- chat_id=chat_id,
- text=text,
+ logger.warning(
+ f"[Telegram] Parse mode {effective_pm} failed for "
+ f"{method.__name__}, sending as plain text"
+ )
+ return await method(
+ **{body_kw: body},
parse_mode=None,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
+ **kwargs,
)
- else:
- raise
+ raise
+ def _require_bot(self) -> Bot:
+ if not self._bot:
+ raise ValueError("Telegram bot not connected")
+ return self._bot
+
+ async def send_message(
+ self,
+ chat_id: str | int,
+ text: str,
+ parse_mode: Optional[str] = None,
+ disable_notification: bool = False,
+ reply_to_message_id: Optional[int] = None,
+ ) -> Dict[str, Any]:
+ bot = self._require_bot()
+ msg = await self._send_with_parse_fallback(
+ bot.send_message,
+ body_kw="text",
+ body=text,
+ parse_mode=parse_mode,
+ chat_id=chat_id,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
return {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
@@ -508,51 +539,17 @@ class TelegramService:
disable_notification: bool = False,
reply_to_message_id: Optional[int] = None,
) -> Dict[str, Any]:
- """Send a photo.
-
- Args:
- chat_id: Chat ID or @username
- photo: URL or file_id
- caption: Photo caption
- parse_mode: Caption parse mode
- disable_notification: Send silently
- reply_to_message_id: Reply to this message
-
- Returns:
- Sent message info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
- if parse_mode == "Auto" and caption:
- safe_caption, effective_pm = self._format_auto(caption)
- else:
- effective_pm = parse_mode if parse_mode else None
- safe_caption = self._escape_text(caption, effective_pm) if caption else caption
-
- try:
- msg = await self._bot.send_photo(
- chat_id=chat_id,
- photo=photo,
- caption=safe_caption,
- parse_mode=effective_pm,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
- )
- except BadRequest as e:
- if "can't parse entities" in str(e).lower() and effective_pm:
- logger.warning(f"[Telegram] Parse mode {effective_pm} failed for photo caption, sending as plain text")
- msg = await self._bot.send_photo(
- chat_id=chat_id,
- photo=photo,
- caption=caption,
- parse_mode=None,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
- )
- else:
- raise
-
+ bot = self._require_bot()
+ msg = await self._send_with_parse_fallback(
+ bot.send_photo,
+ body_kw="caption",
+ body=caption,
+ parse_mode=parse_mode,
+ chat_id=chat_id,
+ photo=photo,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
return {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
@@ -568,51 +565,17 @@ class TelegramService:
disable_notification: bool = False,
reply_to_message_id: Optional[int] = None,
) -> Dict[str, Any]:
- """Send a document.
-
- Args:
- chat_id: Chat ID or @username
- document: URL or file_id
- caption: Document caption
- parse_mode: Caption parse mode
- disable_notification: Send silently
- reply_to_message_id: Reply to this message
-
- Returns:
- Sent message info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
- if parse_mode == "Auto" and caption:
- safe_caption, effective_pm = self._format_auto(caption)
- else:
- effective_pm = parse_mode if parse_mode else None
- safe_caption = self._escape_text(caption, effective_pm) if caption else caption
-
- try:
- msg = await self._bot.send_document(
- chat_id=chat_id,
- document=document,
- caption=safe_caption,
- parse_mode=effective_pm,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
- )
- except BadRequest as e:
- if "can't parse entities" in str(e).lower() and effective_pm:
- logger.warning(f"[Telegram] Parse mode {effective_pm} failed for document caption, sending as plain text")
- msg = await self._bot.send_document(
- chat_id=chat_id,
- document=document,
- caption=caption,
- parse_mode=None,
- disable_notification=disable_notification,
- reply_to_message_id=reply_to_message_id,
- )
- else:
- raise
-
+ bot = self._require_bot()
+ msg = await self._send_with_parse_fallback(
+ bot.send_document,
+ body_kw="caption",
+ body=caption,
+ parse_mode=parse_mode,
+ chat_id=chat_id,
+ document=document,
+ disable_notification=disable_notification,
+ reply_to_message_id=reply_to_message_id,
+ )
return {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
@@ -627,29 +590,14 @@ class TelegramService:
disable_notification: bool = False,
reply_to_message_id: Optional[int] = None,
) -> Dict[str, Any]:
- """Send a location.
-
- Args:
- chat_id: Chat ID or @username
- latitude: Latitude
- longitude: Longitude
- disable_notification: Send silently
- reply_to_message_id: Reply to this message
-
- Returns:
- Sent message info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
- msg = await self._bot.send_location(
+ bot = self._require_bot()
+ msg = await bot.send_location(
chat_id=chat_id,
latitude=latitude,
longitude=longitude,
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
)
-
return {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
@@ -665,23 +613,8 @@ class TelegramService:
disable_notification: bool = False,
reply_to_message_id: Optional[int] = None,
) -> Dict[str, Any]:
- """Send a contact.
-
- Args:
- chat_id: Chat ID or @username
- phone_number: Contact phone number
- first_name: Contact first name
- last_name: Contact last name
- disable_notification: Send silently
- reply_to_message_id: Reply to this message
-
- Returns:
- Sent message info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
- msg = await self._bot.send_contact(
+ bot = self._require_bot()
+ msg = await bot.send_contact(
chat_id=chat_id,
phone_number=phone_number,
first_name=first_name,
@@ -689,19 +622,19 @@ class TelegramService:
disable_notification=disable_notification,
reply_to_message_id=reply_to_message_id,
)
-
return {
"message_id": msg.message_id,
"chat_id": msg.chat.id,
"date": msg.date.isoformat(),
}
- async def get_me(self) -> Dict[str, Any]:
- """Get bot info."""
- if not self._bot:
- raise ValueError("Telegram bot not connected")
+ # =========================================================================
+ # Misc API helpers (used by the credentials-modal WS handlers)
+ # =========================================================================
- me = await self._bot.get_me()
+ async def get_me(self) -> Dict[str, Any]:
+ bot = self._require_bot()
+ me = await bot.get_me()
return {
"id": me.id,
"username": me.username,
@@ -710,18 +643,8 @@ class TelegramService:
}
async def get_chat(self, chat_id: str | int) -> Dict[str, Any]:
- """Get chat info.
-
- Args:
- chat_id: Chat ID or @username
-
- Returns:
- Chat info
- """
- if not self._bot:
- raise ValueError("Telegram bot not connected")
-
- chat = await self._bot.get_chat(chat_id)
+ bot = self._require_bot()
+ chat = await bot.get_chat(chat_id)
return {
"id": chat.id,
"type": chat.type,
diff --git a/server/nodes/telegram/telegram_receive.py b/server/nodes/telegram/telegram_receive.py
index 0ef0a5e1..face27a4 100644
--- a/server/nodes/telegram/telegram_receive.py
+++ b/server/nodes/telegram/telegram_receive.py
@@ -130,7 +130,7 @@ class TelegramReceiveNode(TriggerNode):
# and returns an error envelope.
import time
- from services.telegram_service import get_telegram_service
+ from ._service import get_telegram_service
svc = get_telegram_service()
if not getattr(svc, "connected", False):
diff --git a/server/nodes/telegram/telegram_send.py b/server/nodes/telegram/telegram_send.py
index 2ca7928d..7fb73653 100644
--- a/server/nodes/telegram/telegram_send.py
+++ b/server/nodes/telegram/telegram_send.py
@@ -169,7 +169,8 @@ class TelegramSendNode(ActionNode):
async def send(self, ctx: NodeContext, params: TelegramSendParams) -> Any:
"""Inlined from handlers/telegram.py:handle_telegram_send (Wave 11.D.1)."""
from core.logging import get_logger
- from services.telegram_service import get_telegram_service
+
+ from ._service import get_telegram_service
log = get_logger(__name__)
service = get_telegram_service()
diff --git a/server/routers/websocket.py b/server/routers/websocket.py
index 1febf261..925588b1 100644
--- a/server/routers/websocket.py
+++ b/server/routers/websocket.py
@@ -2121,161 +2121,13 @@ async def handle_whatsapp_diagnostics(data: Dict[str, Any], websocket: WebSocket
# ============================================================================
-# Telegram Handlers - Connect/disconnect/status for Telegram bot
+# Plugin-owned WS handlers (telegram, future plugins, ...) live in their
+# own ``nodes/<group>/`` package and self-register via
+# ``register_ws_handlers`` at import time. The dispatch table below
+# merges them in via ``get_ws_handlers()`` -- no plugin names hardcoded
+# in this file.
# ============================================================================
-from services.telegram_service import get_telegram_service
-
-
-async def handle_telegram_connect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Connect to Telegram. Service reads stored token from DB when the
- payload omits it — DB is the source of truth, the frontend saves the
- token via save_api_key before calling this handler."""
- return await get_telegram_service().connect(data.get("token"))
-
-
-async def handle_telegram_disconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Stop the polling session. The stored token stays in DB; explicit
- delete_api_key removes it."""
- return await get_telegram_service().disconnect()
-
-
-async def handle_telegram_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get Telegram bot connection status."""
- service = get_telegram_service()
- status = service.get_status()
- status["has_stored_token"] = await service.has_stored_token()
- return {"success": True, "status": status}
-
-
-async def handle_telegram_send(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Send message via Telegram bot (direct WebSocket call, not via workflow node)."""
- service = get_telegram_service()
-
- if not service.connected:
- return {"success": False, "error": "Telegram bot not connected"}
-
- chat_id = data.get("chat_id")
- message_type = data.get("message_type", "text")
- text = data.get("text")
- parse_mode = data.get("parse_mode")
-
- if not chat_id:
- return {"success": False, "error": "chat_id required"}
-
- try:
- if message_type == "text":
- if not text:
- return {"success": False, "error": "text required for text message"}
- result = await service.send_message(
- chat_id=chat_id,
- text=text,
- parse_mode=parse_mode,
- )
- elif message_type == "photo":
- photo_url = data.get("media_url")
- if not photo_url:
- return {"success": False, "error": "media_url required for photo"}
- result = await service.send_photo(
- chat_id=chat_id,
- photo=photo_url,
- caption=data.get("caption"),
- parse_mode=parse_mode,
- )
- elif message_type == "document":
- doc_url = data.get("media_url")
- if not doc_url:
- return {"success": False, "error": "media_url required for document"}
- result = await service.send_document(
- chat_id=chat_id,
- document=doc_url,
- caption=data.get("caption"),
- parse_mode=parse_mode,
- )
- elif message_type == "location":
- lat = data.get("latitude")
- lon = data.get("longitude")
- if lat is None or lon is None:
- return {"success": False, "error": "latitude and longitude required"}
- result = await service.send_location(
- chat_id=chat_id,
- latitude=float(lat),
- longitude=float(lon),
- )
- elif message_type == "contact":
- phone = data.get("phone_number")
- first_name = data.get("first_name")
- if not phone or not first_name:
- return {"success": False, "error": "phone_number and first_name required"}
- result = await service.send_contact(
- chat_id=chat_id,
- phone_number=phone,
- first_name=first_name,
- last_name=data.get("last_name"),
- )
- else:
- return {"success": False, "error": f"Unsupported message type: {message_type}"}
-
- return {"success": True, "result": result}
- except Exception as e:
- logger.error(f"[Telegram] Send error: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def handle_telegram_reconnect(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Reconnect Telegram using stored bot token from encrypted credentials."""
- try:
- auth_service = get_auth_service()
- token = await auth_service.get_api_key("telegram_bot_token")
- if not token:
- return {"success": False, "error": "No stored bot token found. Enter token to connect."}
-
- service = get_telegram_service()
- result = await service.connect(token)
-
- # Restore owner_chat_id from credentials if previously captured
- if result.get("success"):
- try:
- saved_owner = await auth_service.get_api_key("telegram_owner_chat_id")
- if saved_owner:
- await service.set_owner(int(saved_owner))
- except Exception as e:
- logger.warning(f"[Telegram] Failed to restore owner_chat_id: {e}")
-
- return result
- except Exception as e:
- logger.error(f"[Telegram] Reconnect failed: {e}")
- return {"success": False, "error": str(e)}
-
-
-async def handle_telegram_get_me(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get bot info."""
- service = get_telegram_service()
- if not service.connected:
- return {"success": False, "error": "Telegram bot not connected"}
- try:
- result = await service.get_me()
- return {"success": True, "result": result}
- except Exception as e:
- return {"success": False, "error": str(e)}
-
-
-async def handle_telegram_get_chat(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Get chat info."""
- service = get_telegram_service()
- if not service.connected:
- return {"success": False, "error": "Telegram bot not connected"}
-
- chat_id = data.get("chat_id")
- if not chat_id:
- return {"success": False, "error": "chat_id required"}
-
- try:
- result = await service.get_chat(chat_id)
- return {"success": True, "result": result}
- except Exception as e:
- return {"success": False, "error": str(e)}
-
# ============================================================================
# Workflow Storage Operations
@@ -3350,6 +3202,27 @@ async def handle_refresh_model_registry(data: Dict[str, Any], websocket: WebSock
# Message Router
# ============================================================================
+# Plugin packages (nodes/<group>/__init__.py) self-register their WS
+# handlers into ``services.ws_handler_registry`` at import time. This
+# router doesn't know any plugin's message-type names — it consults the
+# registry at dispatch time via :func:`_resolve_handler`.
+from services.ws_handler_registry import get_ws_handlers
+
+
+def _resolve_handler(msg_type: str):
+ """Resolve a WS message_type to its handler.
+
+ Looks first in the legacy core ``MESSAGE_HANDLERS`` table, then
+ falls back to the plugin-owned registry. Plugin handlers are
+ discovered at import time (via the side-effect ``import nodes`` in
+ ``main.lifespan``), so by the time messages flow they're registered.
+ """
+ handler = MESSAGE_HANDLERS.get(msg_type)
+ if handler is None:
+ handler = get_ws_handlers().get(msg_type)
+ return handler
+
+
MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
# Status/ping
"ping": handle_ping,
@@ -3470,14 +3343,9 @@ MESSAGE_HANDLERS: Dict[str, MessageHandler] = {
"whatsapp_stop": handle_whatsapp_stop,
"whatsapp_diagnostics": handle_whatsapp_diagnostics,
- # Telegram operations
- "telegram_connect": handle_telegram_connect,
- "telegram_disconnect": handle_telegram_disconnect,
- "telegram_reconnect": handle_telegram_reconnect,
- "telegram_status": handle_telegram_status,
- "telegram_send": handle_telegram_send,
- "telegram_get_me": handle_telegram_get_me,
- "telegram_get_chat": handle_telegram_get_chat,
+ # Telegram operations live in nodes/telegram/_handlers.py and
+ # self-register via services.ws_handler_registry. Dispatch hits them
+ # via _resolve_handler() defined above.
# Workflow storage operations
"save_workflow": handle_save_workflow,
@@ -3679,7 +3547,7 @@ async def websocket_status_endpoint(websocket: WebSocket):
logger.debug("WebSocket message received", msg_type=msg_type, has_request_id=bool(request_id))
- handler = MESSAGE_HANDLERS.get(msg_type)
+ handler = _resolve_handler(msg_type)
if handler:
# Run handler as task so it doesn't block queue processing
@@ -3777,7 +3645,7 @@ async def websocket_internal_endpoint(websocket: WebSocket):
msg_type = data.get("type", "")
request_id = data.get("request_id")
- handler = MESSAGE_HANDLERS.get(msg_type)
+ handler = _resolve_handler(msg_type)
if handler:
task = asyncio.create_task(
@@ -3827,5 +3695,7 @@ async def websocket_info():
"endpoint": "/ws/status",
"connected_clients": broadcaster.connection_count,
"current_status": broadcaster.get_status(),
- "supported_message_types": list(MESSAGE_HANDLERS.keys())
+ "supported_message_types": sorted(
+ set(MESSAGE_HANDLERS.keys()) | set(get_ws_handlers().keys())
+ ),
}
diff --git a/server/services/event_waiter.py b/server/services/event_waiter.py
index 6c9a6d8c..bb2d9bb8 100644
--- a/server/services/event_waiter.py
+++ b/server/services/event_waiter.py
@@ -120,11 +120,9 @@ TRIGGER_REGISTRY: Dict[str, TriggerConfig] = {
event_type='gmail_email_received',
display_name='Gmail Email'
),
- 'telegramReceive': TriggerConfig(
- node_type='telegramReceive',
- event_type='telegram_message_received',
- display_name='Telegram Message'
- ),
+ # 'telegramReceive' moved to nodes/telegram/ — backfilled here from
+ # the plugin's ``event_type`` class attribute via
+ # ``_auto_populate_from_plugins`` on first access.
'emailReceive': TriggerConfig(
node_type='emailReceive',
event_type='email_received',
@@ -487,125 +485,6 @@ def build_gmail_filter(params: Dict) -> Callable[[Dict], bool]:
return matches
-def build_telegram_filter(params: Dict) -> Callable[[Dict], bool]:
- """Build filter function for Telegram messages.
-
- Supports new senderFilter-based params and legacy chatTypeFilter/chat_id/from_user params.
-
- New parameter: senderFilter
- - 'all': Accept all messages
- - 'self': Only messages from the bot owner (uses injected _owner_chat_id)
- - 'private': Only private (DM) chats
- - 'group': Only group chats
- - 'supergroup': Only supergroup chats
- - 'channel': Only channel posts
- - 'specific_chat': Only from specific chat_id
- - 'specific_user': Only from specific from_user
- - 'keywords': Messages containing specific keywords
-
- Legacy parameters (backward compat):
- - chatTypeFilter: 'all', 'private', 'group', 'supergroup', 'channel'
- - chat_id, from_user, keywords, ignoreBots
-
- Event data fields (from TelegramService._format_message):
- message_id, chat_id, chat_type, chat_title, from_id, from_username,
- from_first_name, from_last_name, is_bot, text, content_type, date,
- reply_to_message_id, photo/document/location/contact dicts
-
- Args:
- params: Node parameters (may include injected _owner_chat_id)
-
- Returns:
- Filter function that checks if event matches criteria
- """
- # New-style sender_filter (takes precedence)
- sender_filter = params.get('sender_filter', '')
-
- # Legacy fallback: reconstruct from old params if sender_filter absent.
- # `chat_type_filter` was the pre-Wave-11 schema field name (already
- # snake_case in the DB), so the read here matches.
- if not sender_filter:
- chat_type_filter = params.get('chat_type_filter', 'all')
- old_chat_id = params.get('chat_id', '')
- old_from_user = params.get('from_user', '')
- old_keywords = params.get('keywords', '')
-
- if old_chat_id:
- sender_filter = 'specific_chat'
- elif old_from_user:
- sender_filter = 'specific_user'
- elif old_keywords:
- sender_filter = 'keywords'
- elif chat_type_filter != 'all':
- sender_filter = chat_type_filter
- else:
- sender_filter = 'all'
-
- content_type_filter = params.get('content_type_filter', 'all')
- chat_id_filter = params.get('chat_id', '')
- from_user_filter = params.get('from_user', '')
- keywords = [k.strip().lower() for k in params.get('keywords', '').split(',') if k.strip()]
- ignore_bots = params.get('ignore_bots', True)
- owner_chat_id = params.get('_owner_chat_id')
-
- logger.debug(f"[TelegramFilter] Built: sender={sender_filter}, content_type={content_type_filter}, owner_chat_id={owner_chat_id}")
-
- def _get_owner_chat_id() -> object:
- """Get owner_chat_id dynamically - handles case where owner is detected
- after the filter was built (first message to bot captures the owner)."""
- if owner_chat_id:
- return owner_chat_id
- # Lazy lookup from service at match time
- try:
- from services.telegram_service import get_telegram_service
- service = get_telegram_service()
- return service.owner_chat_id
- except Exception:
- return None
-
- def matches(m: Dict) -> bool:
- # Content type filter (always applies)
- if content_type_filter != 'all':
- if m.get('content_type', '') != content_type_filter:
- return False
-
- # Sender filter
- if sender_filter == 'self':
- current_owner = _get_owner_chat_id()
- if not current_owner:
- logger.debug("[TelegramFilter] Rejecting: owner_chat_id not available")
- return False
- if str(m.get('from_id', '')) != str(current_owner):
- return False
-
- elif sender_filter in ('private', 'group', 'supergroup', 'channel'):
- if m.get('chat_type', '') != sender_filter:
- return False
-
- elif sender_filter == 'specific_chat':
- if chat_id_filter and str(m.get('chat_id', '')) != str(chat_id_filter):
- return False
-
- elif sender_filter == 'specific_user':
- if from_user_filter and str(m.get('from_id', '')) != str(from_user_filter):
- return False
-
- elif sender_filter == 'keywords':
- if keywords:
- text = (m.get('text') or '').lower()
- if not any(kw in text for kw in keywords):
- return False
-
- # Ignore bot messages (skip for 'self' filter)
- if sender_filter != 'self' and ignore_bots and m.get('is_bot', False):
- return False
-
- logger.debug(f"[TelegramFilter] Matched message from {m.get('from_username', m.get('from_id'))}")
- return True
-
- return matches
-
-
def build_email_filter(params: Dict) -> Callable[[Dict], bool]:
"""Build filter for email events (Himalaya IMAP polling)."""
folder_filter = params.get('folder', 'INBOX')
@@ -620,7 +499,12 @@ def build_email_filter(params: Dict) -> Callable[[Dict], bool]:
return matches
-# Registry of filter builders per trigger type
+# Registry of filter builders per trigger type. Plugin packages
+# (nodes/<group>/) call :func:`register_filter_builder` from their
+# package ``__init__.py`` to publish per-trigger filters without this
+# module needing to import them. The hardcoded entries below are core
+# triggers that don't yet live in their own plugin folder; once they
+# do, this dict shrinks to ``{}`` and everything is registry-driven.
FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'whatsappReceive': build_whatsapp_filter,
'webhookTrigger': build_webhook_filter,
@@ -628,11 +512,29 @@ FILTER_BUILDERS: Dict[str, Callable[[Dict], Callable[[Dict], bool]]] = {
'taskTrigger': build_task_completed_filter,
'twitterReceive': build_twitter_filter,
'gmailReceive': build_gmail_filter,
- 'telegramReceive': build_telegram_filter,
'emailReceive': build_email_filter,
}
+def register_filter_builder(
+ node_type: str,
+ builder: Callable[[Dict], Callable[[Dict], bool]],
+) -> None:
+ """Publish a filter builder for a trigger node type.
+
+ Idempotent on re-import (same callable for same key is a no-op).
+ Used by plugin packages to keep all per-node-type knowledge inside
+ the plugin folder instead of hardcoding it here.
+ """
+ existing = FILTER_BUILDERS.get(node_type)
+ if existing is not None and existing is not builder:
+ raise ValueError(
+ f"Filter builder for '{node_type}' is already registered by "
+ f"{existing.__module__}.{existing.__qualname__}"
+ )
+ FILTER_BUILDERS[node_type] = builder
+
+
def build_filter(node_type: str, params: Dict) -> Callable[[Dict], bool]:
"""Build a filter function for the given trigger type and parameters.
@@ -648,6 +550,56 @@ def build_filter(node_type: str, params: Dict) -> Callable[[Dict], bool]:
return lambda x: True
+# =============================================================================
+# TRIGGER PRE-CHECKS (plugin-registered)
+# =============================================================================
+#
+# Some trigger nodes need to short-circuit with a friendly error before
+# entering the wait loop -- e.g. "Telegram bot not connected, add token
+# in Credentials". The pre-check used to be a hardcoded ``if node_type
+# == 'telegramReceive'`` branch in handlers/triggers.py; it now lives in
+# the plugin folder and registers itself here.
+#
+# Signature: ``async def precheck(parameters: Dict) -> Optional[str]``
+# - return None -> proceed normally
+# - return str -> short-circuit with that error message
+
+import inspect as _inspect
+
+_TriggerPrecheck = Callable[[Dict[str, Any]], Any]
+_TRIGGER_PRECHECKS: Dict[str, _TriggerPrecheck] = {}
+
+
+def register_trigger_precheck(node_type: str, fn: _TriggerPrecheck) -> None:
+ """Register a pre-execution check for a trigger node type.
+
+ Idempotent on re-import. The callback may be sync or async; ``run_trigger_precheck``
+ awaits the coroutine when needed.
+ """
+ existing = _TRIGGER_PRECHECKS.get(node_type)
+ if existing is not None and existing is not fn:
+ raise ValueError(
+ f"Trigger precheck for '{node_type}' is already registered by "
+ f"{existing.__module__}.{existing.__qualname__}"
+ )
+ _TRIGGER_PRECHECKS[node_type] = fn
+
+
+async def run_trigger_precheck(node_type: str, parameters: Dict) -> Any:
+ """Run the registered precheck for ``node_type`` (if any).
+
+ Returns the precheck's return value (typically ``None`` or an
+ error-message string).
+ """
+ fn = _TRIGGER_PRECHECKS.get(node_type)
+ if fn is None:
+ return None
+ result = fn(parameters)
+ if _inspect.isawaitable(result):
+ result = await result
+ return result
+
+
# =============================================================================
# WAITER DATA STRUCTURES
# =============================================================================
diff --git a/server/services/handlers/triggers.py b/server/services/handlers/triggers.py
index 6d178db1..93e2e8fe 100644
--- a/server/services/handlers/triggers.py
+++ b/server/services/handlers/triggers.py
@@ -48,24 +48,20 @@ async def handle_trigger_node(
}
try:
- # Telegram pre-check: verify bot is connected before waiting
- if node_type == 'telegramReceive':
- from services.telegram_service import get_telegram_service
- service = get_telegram_service()
- if not service.connected:
- return {
- "success": False,
- "node_id": node_id,
- "node_type": node_type,
- "error": "Telegram bot not connected. Add bot token in Credentials.",
- "execution_time": time.time() - start_time,
- "timestamp": datetime.now().isoformat()
- }
- sender_filter = parameters.get('sender_filter', 'all')
- logger.info("Telegram trigger starting",
- node_id=node_id, sender_filter=sender_filter,
- owner_detected=service.owner_chat_id is not None,
- execution_id=execution_id)
+ # Plugin-registered pre-check (e.g. "Telegram bot not connected").
+ # Plugins call ``event_waiter.register_trigger_precheck(node_type, fn)``
+ # from their package __init__. ``fn(parameters) -> Optional[str]``
+ # returns an error message to short-circuit, or None to proceed.
+ precheck_error = await event_waiter.run_trigger_precheck(node_type, parameters)
+ if precheck_error:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": node_type,
+ "error": precheck_error,
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
# Register waiter for this trigger (async to pre-fetch LID cache)
waiter = await event_waiter.register(node_type, node_id, parameters)
diff --git a/server/services/node_output_schemas.py b/server/services/node_output_schemas.py
index 6daee2b2..b8d1b1a3 100644
--- a/server/services/node_output_schemas.py
+++ b/server/services/node_output_schemas.py
@@ -376,30 +376,12 @@ class ContactsOutput(_OutputBase):
# ---------------------------------------------------------------------------
-# Messaging: Telegram, WhatsApp DB, Social
+# Messaging: WhatsApp DB, Social
+# (Telegram schemas moved to nodes/telegram/, registered via
+# ``register_output_schema``.)
# ---------------------------------------------------------------------------
-class TelegramReceiveOutput(_OutputBase):
- message_id: Optional[int] = None
- chat_id: Optional[int] = None
- chat_type: Optional[str] = None
- chat_title: Optional[str] = None
- from_id: Optional[int] = None
- from_username: Optional[str] = None
- from_first_name: Optional[str] = None
- from_last_name: Optional[str] = None
- is_bot: Optional[bool] = None
- text: Optional[str] = None
- content_type: Optional[str] = None
- date: Optional[str] = None
- reply_to_message_id: Optional[int] = None
- photo: Optional[dict] = None
- document: Optional[dict] = None
- location: Optional[dict] = None
- contact: Optional[dict] = None
-
-
class WhatsAppDbOutput(_OutputBase):
"""Composite — different operations surface different subsets of these
fields. We keep them all optional so the variable panel shows the union."""
@@ -789,8 +771,9 @@ NODE_OUTPUT_SCHEMAS: dict[str, type[BaseModel]] = {
"whatsappReceive": WhatsAppReceiveOutput,
"whatsappSend": WhatsAppSendOutput,
"whatsappDb": WhatsAppDbOutput,
- # telegram / twitter
- "telegramReceive": TelegramReceiveOutput,
+ # telegram entries are registered by nodes/telegram/__init__.py via
+ # register_output_schema() to keep all telegram code self-contained.
+ # twitter
"twitterSend": TwitterSendOutput,
"twitterSearch": TwitterSearchOutput,
"twitterUser": TwitterUserOutput,
@@ -881,3 +864,26 @@ def list_node_types_with_schema() -> list[str]:
client cache key."""
return sorted(NODE_OUTPUT_SCHEMAS.keys())
+
+
+def register_output_schema(node_type: str, model_class: type[BaseModel]) -> None:
+ """Publish an output schema for a node type from a plugin package.
+
+ Plugin folders (``nodes/<group>/__init__.py``) use this to register
+ their own ``Output`` Pydantic class so the central registry above
+ doesn't need to import or duplicate it. Idempotent on re-import;
+ registering a different class for an existing type raises
+ ``ValueError``.
+
+ See e.g. ``nodes/telegram/__init__.py``.
+ """
+ existing = NODE_OUTPUT_SCHEMAS.get(node_type)
+ if existing is not None and existing is not model_class:
+ raise ValueError(
+ f"Output schema for '{node_type}' is already registered as "
+ f"{existing.__module__}.{existing.__qualname__}; refusing to "
+ f"overwrite with {model_class.__module__}.{model_class.__qualname__}"
+ )
+ NODE_OUTPUT_SCHEMAS[node_type] = model_class
+ # Bust the JSON-schema cache so the next call re-serialises.
+ _schema_cache.pop(node_type, None)
diff --git a/server/services/status_broadcaster.py b/server/services/status_broadcaster.py
index f802cf12..1db73a00 100644
--- a/server/services/status_broadcaster.py
+++ b/server/services/status_broadcaster.py
@@ -129,17 +129,18 @@ class StatusBroadcaster:
Uses ``asyncio.TaskGroup`` (Python 3.11+) for structured
concurrency: every refresh runs as an independent task and
publishes its own ``<service>_status`` message the moment its
- cache slot is populated. The slowest service (e.g. Telegram's
- 10 s ``getMe`` cold-DNS path) no longer gates the others — the
- credentials/status UI hydrates incrementally.
-
- Each ``_refresh_*`` already swallows its own exceptions, so
- TaskGroup never sees one. Kept inside try/except* defensively
- in case a future refactor lets one escape.
-
- Wrapped in an OTel span so the cycle's wall-clock duration is
- emitted via the configured span exporter (ConsoleSpanExporter
- in dev for benchmarking, OTLP in prod).
+ cache slot is populated. The slowest service no longer gates
+ the others — the credentials/status UI hydrates incrementally.
+
+ Plugin packages register their own refresh callbacks via
+ :func:`register_service_refresh` (see
+ ``nodes/<group>/__init__.py``). The hardcoded core refreshes
+ below predate the registry; they'll move into their own plugin
+ folders in subsequent waves.
+
+ Each callback swallows its own exceptions, so TaskGroup never
+ sees one. Kept inside try/except* defensively in case a future
+ refactor lets one escape.
"""
with tracer.start_as_current_span("broadcaster.refresh_all_services"):
try:
@@ -147,8 +148,10 @@ class StatusBroadcaster:
tg.create_task(self._refresh_whatsapp_status())
tg.create_task(self._refresh_twitter_status())
tg.create_task(self._refresh_google_status())
- tg.create_task(self._refresh_telegram_status())
tg.create_task(self._auto_reconnect_android_relay())
+ # Plugin-registered refreshes (telegram, future ones)
+ for callback in list(_SERVICE_REFRESH_CALLBACKS):
+ tg.create_task(callback(self))
except* Exception as eg:
for exc in eg.exceptions:
logger.warning("[StatusBroadcaster] Service refresh task failed: %s", exc)
@@ -379,62 +382,6 @@ class StatusBroadcaster:
span.record_exception(e)
logger.debug(f"[StatusBroadcaster] Could not refresh Google status: {e}")
- async def _refresh_telegram_status(self):
- """Refresh Telegram status from stored credentials and auto-reconnect.
-
- Called on client connect. Auth reads + owner restore are handled
- inside TelegramService; this function just decides whether to
- attempt an auto-reconnect and mirrors the resulting status into
- the broadcaster cache.
-
- Span emitted via OTel for cold-start benchmarking. This is the
- canonical "is the broadcaster fast?" metric — Telegram's getMe
- on cold DNS is the historical bottleneck (10s read_timeout).
- """
- with tracer.start_as_current_span("broadcaster.refresh_telegram") as span:
- try:
- from services.telegram_service import get_telegram_service
- service = get_telegram_service()
-
- def _snapshot(connected: bool, has_token: bool) -> Dict[str, Any]:
- s = service.get_status()
- return {
- "connected": connected,
- "bot_id": s.get("bot_id") if connected else None,
- "bot_username": s.get("bot_username") if connected else None,
- "bot_name": s.get("bot_name") if connected else None,
- "owner_chat_id": s.get("owner_chat_id") if connected else None,
- "has_stored_token": has_token,
- }
-
- if service.connected:
- self._status["telegram"] = _snapshot(True, True)
- span.set_attribute("path", "already_connected")
- elif not await service.has_stored_token():
- self._status["telegram"] = _snapshot(False, False)
- span.set_attribute("path", "no_token")
- else:
- span.set_attribute("path", "auto_reconnect")
- logger.info("[StatusBroadcaster] Auto-reconnecting Telegram bot...")
- result = await service.connect() # service reads token from DB
- ok = bool(result.get("success"))
- self._status["telegram"] = _snapshot(ok, True)
- span.set_attribute("reconnect_ok", ok)
- if ok:
- bot_username = self._status["telegram"].get("bot_username")
- logger.info(f"[StatusBroadcaster] Telegram auto-reconnected: @{bot_username}")
- else:
- logger.warning(f"[StatusBroadcaster] Telegram auto-reconnect failed: {result.get('error')}")
-
- await self.broadcast({
- "type": "telegram_status",
- "data": self._status["telegram"],
- })
- span.set_attribute("connected", bool(self._status["telegram"]["connected"]))
- except Exception as e:
- span.record_exception(e)
- logger.debug(f"[StatusBroadcaster] Could not refresh Telegram status: {e}")
-
async def _auto_reconnect_android_relay(self):
"""Auto-reconnect to Android relay if there's a stored pairing session.
@@ -1244,6 +1191,34 @@ class StatusBroadcaster:
return len(self._connections)
+# ---------------------------------------------------------------------------
+# Plugin-registered service-refresh callbacks.
+#
+# The legacy ``_refresh_*`` instance methods (whatsapp/twitter/google/
+# android) hardcode service-specific lookups inside the broadcaster.
+# New plugin packages instead register an ``async def refresh(broadcaster)``
+# callback here -- the broadcaster has zero per-plugin knowledge.
+# ---------------------------------------------------------------------------
+
+import typing as _typing # local alias to avoid shadowing module-level name
+
+_ServiceRefreshCallback = _typing.Callable[
+ ["StatusBroadcaster"], _typing.Awaitable[None]
+]
+_SERVICE_REFRESH_CALLBACKS: _typing.List[_ServiceRefreshCallback] = []
+
+
+def register_service_refresh(callback: _ServiceRefreshCallback) -> None:
+ """Register a per-service refresh callback.
+
+ Idempotent on re-import (same callable is a no-op). Each registered
+ callback runs once per ``_refresh_all_services()`` cycle (i.e. on
+ every WebSocket client connect).
+ """
+ if callback not in _SERVICE_REFRESH_CALLBACKS:
+ _SERVICE_REFRESH_CALLBACKS.append(callback)
+
+
# Global singleton instance
_broadcaster: Optional[StatusBroadcaster] = None
diff --git a/server/services/todo_service.py b/server/services/todo_service.py
index 1d2a04bb..ba7f120e 100644
--- a/server/services/todo_service.py
+++ b/server/services/todo_service.py
@@ -4,7 +4,8 @@ Provides the write_todos tool capability for AI agents to create and manage
structured task lists during complex multi-step operations.
State is persisted as JSON strings, keyed by session identifier.
-Follows the singleton pattern used by browser_service.py and telegram_service.py.
+Follows the singleton pattern used by browser_service.py and the
+TelegramService inside ``nodes/telegram/_service.py``.
"""
import json
diff --git a/server/services/ws_handler_registry.py b/server/services/ws_handler_registry.py
new file mode 100644
index 00000000..c314ea4b
--- /dev/null
+++ b/server/services/ws_handler_registry.py
@@ -0,0 +1,61 @@
+"""WebSocket handler registry for plugin-owned messages.
+
+Mirrors the pattern used by :data:`services.node_registry._HANDLER_REGISTRY`
+(plugin nodes self-register via ``BaseNode.__init_subclass__``) but for
+side-channel WebSocket commands like ``telegram_connect``,
+``whatsapp_status``, etc.
+
+Each ``nodes/<group>/__init__.py`` calls :func:`register_ws_handlers`
+with a dict of ``message_type -> async handler``; the central WebSocket
+router reads :func:`get_ws_handlers` at dispatch time and merges the
+result into its own legacy ``MESSAGE_HANDLERS`` table.
+
+No hardcoded plugin names anywhere in the router. Adding a new
+plugin's WS surface is a one-line registration call inside that
+plugin's package.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Awaitable, Callable, Dict
+
+from fastapi import WebSocket
+
+logger = logging.getLogger(__name__)
+
+WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]
+
+_REGISTRY: Dict[str, WSHandler] = {}
+
+
+def register_ws_handlers(handlers: Dict[str, WSHandler]) -> None:
+ """Publish a batch of ``message_type -> handler`` mappings.
+
+ Idempotent on re-import (same callable for the same key is a no-op).
+ Registering a different callable for an existing key raises
+ ``ValueError`` to surface plugin namespace collisions early.
+ """
+ for msg_type, handler in handlers.items():
+ existing = _REGISTRY.get(msg_type)
+ if existing is not None and existing is not handler:
+ raise ValueError(
+ f"WS handler for message_type '{msg_type}' is already registered "
+ f"by {existing.__module__}.{existing.__qualname__}; refusing to "
+ f"overwrite with {handler.__module__}.{handler.__qualname__}"
+ )
+ _REGISTRY[msg_type] = handler
+
+
+def get_ws_handlers() -> Dict[str, WSHandler]:
+ """Snapshot of all plugin-registered WS handlers.
+
+ Returns a fresh dict so callers can mutate without affecting the
+ registry (e.g. ``MESSAGE_HANDLERS = {**core, **get_ws_handlers()}``).
+ """
+ return dict(_REGISTRY)
+
+
+def list_registered_types() -> list[str]:
+ """For diagnostics / startup logging."""
+ return sorted(_REGISTRY.keys())
diff --git a/server/tests/nodes/test_telegram_social.py b/server/tests/nodes/test_telegram_social.py
index 5190ffe7..1304fcbc 100644
--- a/server/tests/nodes/test_telegram_social.py
+++ b/server/tests/nodes/test_telegram_social.py
@@ -20,10 +20,10 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-# Force import so unittest.mock.patch("services.telegram_service.X") can
-# resolve the attribute path. Without this the module is never loaded at
-# test-collection time and patch raises AttributeError.
-import services.telegram_service # noqa: F401
+# Force import so unittest.mock.patch("nodes.telegram._service.X") can
+# resolve the attribute path. The TelegramService now lives inside the
+# plugin folder; nothing telegram-specific remains under ``services/``.
+import nodes.telegram._service # noqa: F401
from tests.nodes._mocks import patched_broadcaster, patched_container
@@ -66,9 +66,9 @@ def _make_telegram_service(*, connected: bool = True, owner_chat_id=None):
def _patch_telegram_service(svc):
- """Patch the get_telegram_service accessor everywhere it is imported."""
+ """Patch the get_telegram_service accessor at its canonical path."""
return patch(
- "services.telegram_service.get_telegram_service", return_value=svc
+ "nodes.telegram._service.get_telegram_service", return_value=svc
)
@@ -267,6 +267,7 @@ def _make_waiter_stub(*, canned_event=None, is_trigger=True, wait_side_effect=No
stub.wait_for_event = AsyncMock(side_effect=wait_side_effect)
else:
stub.wait_for_event = AsyncMock(return_value=canned_event or {})
+ stub.run_trigger_precheck = AsyncMock(return_value=None)
stub.get_backend_mode = MagicMock(return_value="asyncio.Future")
stub.cancel = MagicMock(return_value=True)
stub.dispatch = MagicMock(return_value=1)
diff --git a/server/tests/nodes/test_twitter.py b/server/tests/nodes/test_twitter.py
index 1bc4c036..68aadc50 100644
--- a/server/tests/nodes/test_twitter.py
+++ b/server/tests/nodes/test_twitter.py
@@ -577,6 +577,7 @@ def _make_waiter_stub(*, canned_event=None):
)
stub.register = AsyncMock(return_value=waiter_obj)
stub.wait_for_event = AsyncMock(return_value=canned_event or {})
+ stub.run_trigger_precheck = AsyncMock(return_value=None)
stub.get_backend_mode = MagicMock(return_value="asyncio.Future")
stub.cancel = MagicMock(return_value=True)
stub.dispatch = MagicMock(return_value=1)