Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(telegram): stop dropping inbound media, spill over-long captions
trohitg1753efe0489d
diff --git a/server/nodes/telegram/_filters.py b/server/nodes/telegram/_filters.pyindex ac2b3a1d..e306f528 100644--- a/server/nodes/telegram/_filters.py+++ b/server/nodes/telegram/_filters.py@@ -74,7 +74,13 @@ def build_telegram_filter(params: Dict) -> Callable[[Dict], bool]:return Nonedef matches(m: Dict) -> bool:- if content_type_filter != "all":+ if content_type_filter == "media":+ # Any message carrying a downloadable file, regardless of kind.+ from ._service import _MEDIA_CONTENT_TYPES++ if m.get("content_type", "") not in _MEDIA_CONTENT_TYPES:+ return False+ elif content_type_filter != "all":if m.get("content_type", "") != content_type_filter:return Falsediff --git a/server/nodes/telegram/_handlers.py b/server/nodes/telegram/_handlers.pyindex 589dd797..b73b2aa1 100644--- a/server/nodes/telegram/_handlers.py+++ b/server/nodes/telegram/_handlers.py@@ -27,79 +27,6 @@ from ._service import get_telegram_servicelogger = 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.# ---------------------------------------------------------------------------@@ -133,21 +60,26 @@ async def handle_telegram_send(data: Dict[str, Any], websocket: WebSocket) -> Di``{success: False, error: str(e)}`` automatically. Early-returnvalidation stays since those are deterministic input checks."""+ from pydantic import ValidationError++ from ._send import perform_send+ from .telegram_send import TelegramSendParams+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}"}+ # Validate through the node's own Params model so this path enforces the+ # same contract as the workflow node — and honours ``silent`` /+ # ``reply_to_message_id``, which the previous hand-rolled dispatch dropped.+ try:+ params = TelegramSendParams.model_validate(data)+ except ValidationError as exc:+ return {"success": False, "error": f"Invalid parameters: {exc}"}- coro_or_none, err = dispatch(service, data, data.get("parse_mode"))- if err:- return {"success": False, "error": err}- result = await coro_or_none+ result = await perform_send(service, data["chat_id"], params)return {"success": True, "result": result}diff --git a/server/nodes/telegram/_send.py b/server/nodes/telegram/_send.pynew file mode 100644index 00000000..845f28a2--- /dev/null+++ b/server/nodes/telegram/_send.py@@ -0,0 +1,149 @@+"""Single source of truth for what ``telegramSend`` can send.++Both entry points — the workflow node (``telegram_send.py``) and the direct+WebSocket command (``_handlers.py:handle_telegram_send``) — route through+``perform_send`` here. They used to carry two independent copies of the+message-type dispatch, which had already drifted: the WebSocket copy silently+ignored ``silent`` and ``reply_to_message_id``, and validated nothing, so a+``location`` command with a null latitude reached python-telegram-bot and+raised a TypeError instead of a legible error.++Dispatch is a table keyed by message type, so adding a type is one entry plus+one ``Literal`` member rather than a new branch in two files.+"""++from __future__ import annotations++from typing import Any, Awaitable, Callable, Dict, Optional++from services.plugin import NodeUserError++from .telegram_send import TelegramSendParams+++async def resolve_chat_id(service: Any, params: TelegramSendParams) -> str | int:+ """Resolve the destination chat, restoring a stored owner if needed.++ ``recipient_type="self"`` targets the bot owner, who is normally captured+ on the first private message. After a process restart the in-memory value+ is gone but the credential row survives, so fall back to it before giving+ up.+ """+ from core.logging import get_logger++ log = get_logger(__name__)++ if params.recipient_type != "self":+ if not params.chat_id:+ raise NodeUserError("chat_id is required")+ return params.chat_id++ chat_id = service.owner_chat_id+ if chat_id:+ return chat_id++ try:+ from services.plugin.deps import get_auth_service++ saved = await get_auth_service().get_api_key("telegram_owner_chat_id")+ if saved:+ owner_id = int(saved)+ await service.set_owner(owner_id)+ log.info(f"[Telegram] Owner restored from credentials: {owner_id}")+ return owner_id+ except Exception as exc: # noqa: BLE001+ log.warning(f"[Telegram] Failed to restore owner: {exc}")++ raise NodeUserError(+ "Bot owner not detected. Send any private message to your bot "+ "on Telegram to auto-detect, or set TELEGRAM_OWNER_CHAT_ID in .env",+ )+++async def _send_text(service: Any, params: TelegramSendParams, common: Dict[str, Any]) -> Dict[str, Any]:+ if not params.text:+ raise NodeUserError("text is required for text message")+ return await service.send_message(+ text=params.text,+ parse_mode=params.parse_mode or None,+ **common,+ )+++async def _send_photo(service: Any, params: TelegramSendParams, common: Dict[str, Any]) -> Dict[str, Any]:+ if not params.media_url:+ raise NodeUserError("media_url is required for photo message")+ return await service.send_photo(+ photo=params.media_url,+ caption=params.caption or None,+ parse_mode=params.parse_mode or None,+ **common,+ )+++async def _send_document(service: Any, params: TelegramSendParams, common: Dict[str, Any]) -> Dict[str, Any]:+ if not params.media_url:+ raise NodeUserError("media_url is required for document message")+ return await service.send_document(+ document=params.media_url,+ caption=params.caption or None,+ parse_mode=params.parse_mode or None,+ **common,+ )+++async def _send_location(service: Any, params: TelegramSendParams, common: Dict[str, Any]) -> Dict[str, Any]:+ if params.latitude is None or params.longitude is None:+ raise NodeUserError("latitude and longitude are required for location message")+ return await service.send_location(+ latitude=float(params.latitude),+ longitude=float(params.longitude),+ **common,+ )+++async def _send_contact(service: Any, params: TelegramSendParams, common: Dict[str, Any]) -> Dict[str, Any]:+ if not params.phone_number or not params.first_name:+ raise NodeUserError("phone_number and first_name are required for contact message")+ return await service.send_contact(+ phone_number=params.phone_number,+ first_name=params.first_name,+ last_name=params.last_name or None,+ **common,+ )+++_DISPATCH: Dict[str, Callable[[Any, TelegramSendParams, Dict[str, Any]], Awaitable[Dict[str, Any]]]] = {+ "text": _send_text,+ "photo": _send_photo,+ "document": _send_document,+ "location": _send_location,+ "contact": _send_contact,+}+++async def perform_send(+ service: Any,+ chat_id: str | int,+ params: TelegramSendParams,+) -> Dict[str, Any]:+ """Validate the type-specific params and dispatch to the service.++ Returns the raw service result; callers shape their own envelope.+ """+ handler = _DISPATCH.get(params.message_type)+ if handler is None:+ raise NodeUserError(f"Unsupported message type: {params.message_type}")++ reply_to: Optional[int] = (+ int(params.reply_to_message_id) if params.reply_to_message_id else None+ )+ common = dict(+ chat_id=chat_id,+ disable_notification=params.silent,+ reply_to_message_id=reply_to,+ )+ return await handler(service, params, common)+++__all__ = ["perform_send", "resolve_chat_id"]diff --git a/server/nodes/telegram/_service.py b/server/nodes/telegram/_service.pyindex 2218322f..dc7eb72d 100644--- a/server/nodes/telegram/_service.py+++ b/server/nodes/telegram/_service.py@@ -40,6 +40,7 @@ from __future__ import annotationsimport asyncioimport logging+import mimetypesimport osfrom datetime import datetimefrom typing import Any, Awaitable, Callable, Dict, Optional@@ -68,39 +69,291 @@ _TG_TEXT_LIMIT = 4096_TG_CAPTION_LIMIT = 1024+def _tg_len(text: str) -> int:+ """Length as Telegram counts it: UTF-16 code units, not code points.++ The Bot API measures its 4096 / 1024 caps in UTF-16 units, so an emoji+ costs 2 and Python's ``len()`` under-counts. A 1024-code-point caption of+ emoji is rejected as "caption is too long" even though ``len()`` says it+ fits. See https://core.telegram.org/api/entities.+ """+ return len(text.encode("utf-16-le")) // 2+++def _split_head(text: str, limit: int) -> tuple[str, str]:+ """Split off the first <=``limit`` chunk at the cleanest boundary.++ Returns ``(head, tail)``; ``tail`` is ``""`` when the whole text fits.+ Prefers paragraph -> line -> sentence -> space breaks found past the+ halfway mark so we don't leave tiny tail chunks, else cuts hard.+ """+ if _tg_len(text) <= limit:+ return text, ""++ # Start from a code-point slice, then shrink until it fits in UTF-16+ # units too (an all-emoji window is twice as long as it looks).+ window = text[:limit]+ while window and _tg_len(window) > limit:+ window = window[: len(window) - (_tg_len(window) - limit)]++ cut = -1+ for sep in ("\n\n", "\n", ". ", "! ", "? ", " "):+ idx = window.rfind(sep)+ if idx > limit // 2:+ cut = idx + len(sep)+ break+ if cut <= 0:+ # No clean break -- hard cut at the end of the fitted window.+ cut = len(window)+ return text[:cut].rstrip(), text[cut:].lstrip()++def _split_text(text: str, limit: int) -> list[str]:- """Split ``text`` into chunks no longer than ``limit`` characters,+ """Split ``text`` into chunks no longer than ``limit`` UTF-16 units,preferring paragraph -> line -> sentence -> space boundaries beforefalling back to a hard cut. Used for Telegram's 4096 / 1024 caps.Pure stdlib, no regex outside ``str`` ops -- the splitting heuristicshould stay legible."""- if len(text) <= limit:+ if _tg_len(text) <= limit:return [text]chunks: list[str] = []remaining = text- while len(remaining) > limit:- # Search for a clean break point in the last ~25% of the window- # so we don't end up with tiny tail chunks.- window = remaining[:limit]- cut = -1- for sep in ("\n\n", "\n", ". ", "! ", "? ", " "):- idx = window.rfind(sep)- if idx > limit // 2:- cut = idx + len(sep)- break- if cut <= 0:- # No clean break -- hard cut at the limit.- cut = limit- chunks.append(remaining[:cut].rstrip())- remaining = remaining[cut:].lstrip()+ while _tg_len(remaining) > limit:+ head, remaining = _split_head(remaining, limit)+ chunks.append(head)if remaining:chunks.append(remaining)return chunks+# Inbound content-type probes, in priority order.+#+# ORDER IS LOAD-BEARING: Telegram sets ``message.document`` on animation+# messages (an animation *is* a document carrying an extra ``animation``+# field), so probing ``document`` first misclassifies every GIF. Same for+# video_note vs video. Probe the most specific object first.+_CONTENT_PROBES: tuple[tuple[str, Callable[[Any], Any]], ...] = (+ ("photo", lambda m: m.photo),+ ("animation", lambda m: getattr(m, "animation", None)),+ ("video_note", lambda m: getattr(m, "video_note", None)),+ ("video", lambda m: m.video),+ ("voice", lambda m: m.voice),+ ("audio", lambda m: m.audio),+ ("sticker", lambda m: m.sticker),+ ("document", lambda m: m.document),+ ("location", lambda m: m.location),+ ("contact", lambda m: m.contact),+ ("poll", lambda m: m.poll),+)++# Media kinds — the subset of content types that carry a downloadable file.+_MEDIA_CONTENT_TYPES = frozenset(+ {"photo", "animation", "video_note", "video", "voice", "audio", "sticker", "document"}+)+++def _detect_content_type(msg: Any) -> str:+ for name, probe in _CONTENT_PROBES:+ try:+ if probe(msg):+ return name+ except AttributeError:+ continue+ return "text"+++# Per-type detail extraction. Deliberately scalar-only: no thumbnails, no+# PhotoSize arrays, no vcard blobs. Node results are amplified ~5x (Temporal+# payload -> WS broadcast -> 3 DB keys -> LLM conversation, replayed every+# turn), so each dict stays 5-10 scalars, a few hundred bytes.+_DETAIL_EXTRACTORS: Dict[str, Callable[[Any], Dict[str, Any]]] = {+ "photo": lambda m: {+ "file_id": m.photo[-1].file_id,+ "file_unique_id": m.photo[-1].file_unique_id,+ "width": m.photo[-1].width,+ "height": m.photo[-1].height,+ "file_size": m.photo[-1].file_size,+ },+ "video": lambda m: {+ "file_id": m.video.file_id,+ "file_unique_id": m.video.file_unique_id,+ "width": m.video.width,+ "height": m.video.height,+ "duration": m.video.duration,+ "file_name": m.video.file_name,+ "mime_type": m.video.mime_type,+ "file_size": m.video.file_size,+ },+ "animation": lambda m: {+ "file_id": m.animation.file_id,+ "file_unique_id": m.animation.file_unique_id,+ "width": m.animation.width,+ "height": m.animation.height,+ "duration": m.animation.duration,+ "file_name": m.animation.file_name,+ "mime_type": m.animation.mime_type,+ "file_size": m.animation.file_size,+ },+ "video_note": lambda m: {+ "file_id": m.video_note.file_id,+ "file_unique_id": m.video_note.file_unique_id,+ "length": m.video_note.length,+ "duration": m.video_note.duration,+ "file_size": m.video_note.file_size,+ },+ "audio": lambda m: {+ "file_id": m.audio.file_id,+ "file_unique_id": m.audio.file_unique_id,+ "duration": m.audio.duration,+ "performer": m.audio.performer,+ "title": m.audio.title,+ "file_name": m.audio.file_name,+ "mime_type": m.audio.mime_type,+ "file_size": m.audio.file_size,+ },+ "voice": lambda m: {+ "file_id": m.voice.file_id,+ "file_unique_id": m.voice.file_unique_id,+ "duration": m.voice.duration,+ "mime_type": m.voice.mime_type,+ "file_size": m.voice.file_size,+ },+ "sticker": lambda m: {+ "file_id": m.sticker.file_id,+ "file_unique_id": m.sticker.file_unique_id,+ "width": m.sticker.width,+ "height": m.sticker.height,+ "emoji": m.sticker.emoji,+ "set_name": m.sticker.set_name,+ "is_animated": m.sticker.is_animated,+ "is_video": m.sticker.is_video,+ "file_size": m.sticker.file_size,+ },+ "document": lambda m: {+ "file_id": m.document.file_id,+ "file_unique_id": m.document.file_unique_id,+ "file_name": m.document.file_name,+ "mime_type": m.document.mime_type,+ "file_size": m.document.file_size,+ },+ "location": lambda m: {+ "latitude": m.location.latitude,+ "longitude": m.location.longitude,+ "horizontal_accuracy": getattr(m.location, "horizontal_accuracy", None),+ "live_period": getattr(m.location, "live_period", None),+ },+ "contact": lambda m: {+ "phone_number": m.contact.phone_number,+ "first_name": m.contact.first_name,+ "last_name": m.contact.last_name,+ "user_id": m.contact.user_id,+ },+ "poll": lambda m: {+ "id": m.poll.id,+ "question": m.poll.question,+ "options": [o.text for o in (m.poll.options or [])[:12]],+ "type": m.poll.type,+ "is_anonymous": m.poll.is_anonymous,+ "allows_multiple_answers": m.poll.allows_multiple_answers,+ "is_closed": m.poll.is_closed,+ "total_voter_count": m.poll.total_voter_count,+ },+}++# Telegram omits mime_type on several kinds; synthesise it so downstream+# nodes get a usable content type without per-kind branching.+_SYNTHETIC_MIME: Dict[str, str] = {+ "photo": "image/jpeg",+ "voice": "audio/ogg",+ "video_note": "video/mp4",+ "animation": "video/mp4",+ "sticker": "image/webp",+}+_SYNTHETIC_EXT: Dict[str, str] = {+ "image/jpeg": ".jpg",+ "image/png": ".png",+ "image/webp": ".webp",+ "audio/ogg": ".ogg",+ "video/mp4": ".mp4",+ "application/x-tgsticker": ".tgs",+ "video/webm": ".webm",+}+++def _normalize_media(+ content_type: str,+ detail: Optional[Dict[str, Any]],+ caption: Optional[str],+) -> Optional[Dict[str, Any]]:+ """Collapse any media kind into one type-agnostic block.++ Downstream nodes and agents should never branch on content_type to find+ a file_id — this is the single shape they read.+ """+ if content_type not in _MEDIA_CONTENT_TYPES or not detail:+ return None++ mime = detail.get("mime_type") or _SYNTHETIC_MIME.get(content_type)+ if content_type == "sticker":+ if detail.get("is_animated"):+ mime = "application/x-tgsticker"+ elif detail.get("is_video"):+ mime = "video/webm"++ file_name = detail.get("file_name")+ if not file_name:+ ext = _SYNTHETIC_EXT.get(mime or "") or mimetypes.guess_extension(mime or "") or ".bin"+ file_name = f"{detail.get('file_unique_id') or content_type}{ext}"++ return {+ "kind": content_type,+ "file_id": detail.get("file_id"),+ "file_unique_id": detail.get("file_unique_id"),+ "mime_type": mime,+ "file_name": file_name,+ "file_size": detail.get("file_size"),+ "duration": detail.get("duration"),+ "width": detail.get("width"),+ "height": detail.get("height"),+ "caption": caption or "",+ # Populated only by an explicit download; the trigger never fetches+ # bytes and never carries base64.+ "file_path": None,+ "downloaded": False,+ }+++def _summarize_reply_to(replied: Any) -> Optional[Dict[str, Any]]:+ """Bounded summary of the message being replied to.++ Without this an agent sees a bare ``reply_to_message_id`` it cannot act+ on — "transcribe this" / "summarise this" needs the quoted media.+ """+ if replied is None:+ return None+ content_type = _detect_content_type(replied)+ summary: Dict[str, Any] = {+ "message_id": replied.message_id,+ "content_type": content_type,+ "text": ((replied.text or replied.caption or "")[:500]),+ }+ extractor = _DETAIL_EXTRACTORS.get(content_type)+ if extractor is not None and content_type in _MEDIA_CONTENT_TYPES:+ try:+ detail = extractor(replied)+ summary["media"] = {+ "kind": content_type,+ "file_id": detail.get("file_id"),+ "mime_type": detail.get("mime_type") or _SYNTHETIC_MIME.get(content_type),+ }+ except Exception: # noqa: BLE001+ pass+ return summary++class TelegramService(ServiceSingleton):"""Singleton service for Telegram bot operations.@@ -488,25 +741,7 @@ class TelegramService(ServiceSingleton):def _format_message(self, msg) -> Dict[str, Any]:"""Format Telegram message to unified event data."""- content_type = "text"- if msg.photo:- content_type = "photo"- elif msg.video:- content_type = "video"- elif msg.audio:- content_type = "audio"- elif msg.voice:- content_type = "voice"- elif msg.document:- content_type = "document"- elif msg.sticker:- content_type = "sticker"- elif msg.location:- content_type = "location"- elif msg.contact:- content_type = "contact"- elif msg.poll:- content_type = "poll"+ content_type = _detect_content_type(msg)data = {"message_id": msg.message_id,@@ -518,40 +753,36 @@ class TelegramService(ServiceSingleton):"from_first_name": msg.from_user.first_name if msg.from_user else None,"from_last_name": msg.from_user.last_name if msg.from_user else None,"is_bot": msg.from_user.is_bot if msg.from_user else False,+ # ``text`` keeps its historical caption fallback: workflows read it+ # on photo messages. ``caption`` below is additive, never a swap."text": msg.text or msg.caption or "",+ "caption": msg.caption or "","content_type": content_type,"date": msg.date.isoformat() if msg.date else datetime.now().isoformat(),"reply_to_message_id": msg.reply_to_message.message_id if msg.reply_to_message else None,+ # Album correlation: several media messages sharing this id were+ # sent as one album.+ "media_group_id": getattr(msg, "media_group_id", None),}- if msg.photo:- photo = msg.photo[-1]- data["photo"] = {- "file_id": photo.file_id,- "file_unique_id": photo.file_unique_id,- "width": photo.width,- "height": photo.height,- "file_size": photo.file_size,- }- elif msg.document:- data["document"] = {- "file_id": msg.document.file_id,- "file_name": msg.document.file_name,- "mime_type": msg.document.mime_type,- "file_size": msg.document.file_size,- }- elif msg.location:- data["location"] = {- "latitude": msg.location.latitude,- "longitude": msg.location.longitude,- }- elif msg.contact:- data["contact"] = {- "phone_number": msg.contact.phone_number,- "first_name": msg.contact.first_name,- "last_name": msg.contact.last_name,- "user_id": msg.contact.user_id,- }+ extractor = _DETAIL_EXTRACTORS.get(content_type)+ if extractor is not None:+ try:+ data[content_type] = extractor(msg)+ except Exception as exc: # noqa: BLE001+ # A malformed/partial payload from one message must never stop+ # the event reaching its workflow.+ logger.warning(+ "[Telegram] Could not extract %s details: %s", content_type, exc+ )++ media = _normalize_media(content_type, data.get(content_type), msg.caption)+ data["media"] = media+ data["has_media"] = media is not None++ reply_to = _summarize_reply_to(getattr(msg, "reply_to_message", None))+ if reply_to is not None:+ data["reply_to"] = reply_toreturn dataasync def _broadcast_status(self):@@ -685,32 +916,96 @@ class TelegramService(ServiceSingleton):"message_ids": message_ids,}- async def send_photo(+ async def _send_captioned_media(self,+ method: Callable[..., Awaitable[Any]],+ *,+ media_kw: str,+ media: Any,+ caption: Optional[str],+ parse_mode: Optional[str],chat_id: str | int,- photo: str,- caption: Optional[str] = None,- parse_mode: Optional[str] = None,disable_notification: bool = False,reply_to_message_id: Optional[int] = None,+ **extras: Any,) -> Dict[str, Any]:- bot = self._require_bot()+ """Send one media message, spilling an over-long caption.++ Telegram caps captions at 1024 UTF-16 units and rejects the whole+ send with BadRequest("Message caption is too long") past that. We+ truncate at the cap and thread the remainder underneath as a reply,+ so the content is never silently lost — the behaviour the limit+ constants above have documented since they were introduced.++ Ordering matters: the caption is split while still **raw**, before+ ``_resolve_body`` converts markdown to HTML. Splitting after+ conversion could cut a ``<b>`` from its closing tag and produce+ BadRequest("can't find end of the entity"). Telegram measures the+ cap against entity-parsed text, so truncating the raw markdown is+ conservative and can never come out over-long.+ """+ head, tail = _split_head(caption, _TG_CAPTION_LIMIT) if caption else ("", "")+ if tail:+ logger.info(+ "[Telegram] Caption is %d units (cap %d) — remainder threaded as a follow-up",+ _tg_len(caption or ""),+ _TG_CAPTION_LIMIT,+ )+msg = await self._send_with_parse_fallback(- bot.send_photo,+ method,body_kw="caption",- body=caption,+ body=head or None,parse_mode=parse_mode,chat_id=chat_id,- photo=photo,+ **{media_kw: media},disable_notification=disable_notification,reply_to_message_id=reply_to_message_id,+ **extras,)++ follow_up_ids: list[int] = []+ if tail:+ # send_message already chunks at 4096 and chains replies, so a+ # very long remainder threads under itself correctly.+ spill = await self.send_message(+ chat_id=chat_id,+ text=tail,+ parse_mode=parse_mode,+ disable_notification=True, # one notification per logical message+ reply_to_message_id=msg.message_id,+ )+ follow_up_ids = list(spill.get("message_ids") or [])+return {"message_id": msg.message_id,"chat_id": msg.chat.id,"date": msg.date.isoformat(),+ "caption_truncated": bool(tail),+ "follow_up_message_ids": follow_up_ids,}+ async def send_photo(+ self,+ chat_id: str | int,+ photo: str,+ caption: Optional[str] = None,+ parse_mode: Optional[str] = None,+ disable_notification: bool = False,+ reply_to_message_id: Optional[int] = None,+ ) -> Dict[str, Any]:+ bot = self._require_bot()+ return await self._send_captioned_media(+ bot.send_photo,+ media_kw="photo",+ media=photo,+ caption=caption,+ parse_mode=parse_mode,+ chat_id=chat_id,+ disable_notification=disable_notification,+ reply_to_message_id=reply_to_message_id,+ )+async def send_document(self,chat_id: str | int,@@ -721,21 +1016,16 @@ class TelegramService(ServiceSingleton):reply_to_message_id: Optional[int] = None,) -> Dict[str, Any]:bot = self._require_bot()- msg = await self._send_with_parse_fallback(+ return await self._send_captioned_media(bot.send_document,- body_kw="caption",- body=caption,+ media_kw="document",+ media=document,+ caption=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,- "date": msg.date.isoformat(),- }async def send_location(self,diff --git a/server/nodes/telegram/telegram_receive.py b/server/nodes/telegram/telegram_receive.pyindex 6aaffe73..56be6e5f 100644--- a/server/nodes/telegram/telegram_receive.py+++ b/server/nodes/telegram/telegram_receive.py@@ -24,11 +24,14 @@ class TelegramReceiveParams(BaseModel):content_type_filter: Literal["all",+ "media","text","photo","video","audio","voice",+ "animation",+ "video_note","document","sticker","location",@@ -36,7 +39,11 @@ class TelegramReceiveParams(BaseModel):"poll",] = Field(default="all",- description="Filter by message content type",+ description=(+ "Filter by message content type. 'media' matches any message "+ "carrying a file (photo, video, audio, voice, animation, video "+ "note, sticker or document)."+ ),)sender_filter: Literal["all",@@ -97,6 +104,35 @@ class TelegramReceiveParams(BaseModel):model_config = ConfigDict(extra="ignore")+class TelegramMedia(BaseModel):+ """Type-agnostic view of whatever file the message carried.++ ``None`` for text / location / contact / poll messages. This is the field+ downstream nodes and agents should read — the per-type blocks below are+ Telegram's own shapes and require per-kind branching, this one does not.++ It never carries bytes or base64: node outputs are persisted, broadcast,+ and serialized into LLM conversations, so media travels as an id plus (once+ downloaded) a workspace-relative path.+ """++ kind: Optional[str] = None # photo|video|audio|voice|animation|video_note|sticker|document+ file_id: Optional[str] = None # re-send via telegramSend without re-uploading+ file_unique_id: Optional[str] = None # stable across bots — use as a dedup key+ mime_type: Optional[str] = None # synthesised when Telegram omits it+ file_name: Optional[str] = None # synthesised from kind + extension when absent+ file_size: Optional[int] = None+ duration: Optional[int] = None+ width: Optional[int] = None+ height: Optional[int] = None+ caption: Optional[str] = None+ file_path: Optional[str] = None # set once downloaded; never bytes+ downloaded: Optional[bool] = None+ download_error: Optional[str] = None++ model_config = ConfigDict(extra="allow")++class TelegramReceiveOutput(BaseModel):message_id: Optional[int] = Nonechat_id: Optional[int] = None@@ -108,13 +144,27 @@ class TelegramReceiveOutput(BaseModel):from_last_name: Optional[str] = Noneis_bot: Optional[bool] = Nonetext: Optional[str] = None+ caption: Optional[str] = Nonecontent_type: Optional[str] = Nonedate: Optional[str] = Nonereply_to_message_id: Optional[int] = None+ # Normalized media view — read this instead of the per-type blocks.+ media: Optional[TelegramMedia] = None+ has_media: Optional[bool] = None+ media_group_id: Optional[str] = None # shared by messages sent as one album+ reply_to: Optional[dict] = None # bounded summary of the quoted message+ # Telegram-native per-type detail blocks.photo: Optional[dict] = None+ video: Optional[dict] = None+ audio: Optional[dict] = None+ voice: Optional[dict] = None+ animation: Optional[dict] = None+ video_note: Optional[dict] = None+ sticker: Optional[dict] = Nonedocument: Optional[dict] = Nonelocation: Optional[dict] = Nonecontact: Optional[dict] = None+ poll: Optional[dict] = Nonemodel_config = ConfigDict(extra="allow")@@ -136,9 +186,12 @@ class TelegramReceiveNode(TriggerNode):Output = TelegramReceiveOutputdef build_filter(self, params: TelegramReceiveParams) -> Callable[[Dict[str, Any]], bool]:- # Delegate to legacy filter builder for full feature parity —- # 11.F ports the body and removes the legacy registry entry.- from services.event_waiter import build_telegram_filter+ # The filter body lives in this plugin folder (Wave 11.F moved it out+ # of services/event_waiter.py). This path is normally unreachable —+ # __init__.py pre-registers the builder and event_waiter only binds+ # ``build_filter`` for types absent from FILTER_BUILDERS — but it must+ # still import from the real location.+ from ._filters import build_telegram_filterreturn build_telegram_filter(params.model_dump())diff --git a/server/nodes/telegram/telegram_send.py b/server/nodes/telegram/telegram_send.pyindex 87bf2321..b69d02ae 100644--- a/server/nodes/telegram/telegram_send.py+++ b/server/nodes/telegram/telegram_send.py@@ -9,7 +9,7 @@ converts to a declarative ``TelegramCredential``.from __future__ import annotations-from typing import Any, Literal, Optional+from typing import Any, List, Literal, Optionalfrom pydantic import BaseModel, ConfigDict, Field@@ -147,6 +147,18 @@ class TelegramSendOutput(BaseModel):message_id: Optional[int] = Nonechat_id: Optional[int] = Nonesent: Optional[bool] = None+ # ``message_type`` and ``date`` were always returned but never declared,+ # surviving only via ``extra="allow"``. Declaring them makes them visible+ # in the frontend data picker; the runtime payload is unchanged.+ message_type: Optional[str] = None+ date: Optional[str] = None+ # Populated when one logical send became several Telegram messages:+ # text over the 4096 cap, or a caption over 1024 whose remainder was+ # threaded underneath as a follow-up.+ parts: Optional[int] = None+ message_ids: Optional[List[int]] = None+ caption_truncated: Optional[bool] = None+ follow_up_message_ids: Optional[List[int]] = Nonemodel_config = ConfigDict(extra="allow")@@ -183,97 +195,31 @@ class TelegramSendNode(ActionNode):"Telegram bot not connected. Add bot token in Credentials.",)- if params.recipient_type == "self":- chat_id = service.owner_chat_id- if not chat_id:- try:- from services.plugin.deps import get_auth_service+ # Validation + dispatch live in _send.py so the WebSocket command path+ # cannot drift from this one.+ from ._send import perform_send, resolve_chat_id- saved = await get_auth_service().get_api_key("telegram_owner_chat_id")- if saved:- owner_id = int(saved)- await service.set_owner(owner_id)- chat_id = owner_id- log.info(f"[Telegram] Owner restored from credentials: {owner_id}")- except Exception as e:- log.warning(f"[Telegram] Failed to restore owner: {e}")- if not chat_id:- raise RuntimeError(- "Bot owner not detected. Send any private message to your bot "- "on Telegram to auto-detect, or set TELEGRAM_OWNER_CHAT_ID in .env",- )- else:- chat_id = params.chat_id- if not chat_id:- raise RuntimeError("chat_id is required")-- # Empty string = no parse mode (Python None); other values pass through- # so the TelegramService can handle "Auto" and the formal parse modes.- parse_mode = params.parse_mode or None- reply_to = int(params.reply_to_message_id) if params.reply_to_message_id else None-- common = dict(- chat_id=chat_id,- disable_notification=params.silent,- reply_to_message_id=reply_to,- )+ chat_id = await resolve_chat_id(service, params)mt = params.message_type- if mt == "text":- if not params.text:- raise RuntimeError("text is required for text message")- result = await service.send_message(- text=params.text,- parse_mode=parse_mode,- **common,- )- elif mt == "photo":- if not params.media_url:- raise RuntimeError("media_url is required for photo message")- result = await service.send_photo(- photo=params.media_url,- caption=params.caption or None,- parse_mode=parse_mode,- **common,- )- elif mt == "document":- if not params.media_url:- raise RuntimeError("media_url is required for document message")- result = await service.send_document(- document=params.media_url,- caption=params.caption or None,- parse_mode=parse_mode,- **common,- )- elif mt == "location":- if params.latitude is None or params.longitude is None:- raise RuntimeError(- "latitude and longitude are required for location message",- )- result = await service.send_location(- latitude=float(params.latitude),- longitude=float(params.longitude),- **common,- )- elif mt == "contact":- if not params.phone_number or not params.first_name:- raise RuntimeError(- "phone_number and first_name are required for contact message",- )- result = await service.send_contact(- phone_number=params.phone_number,- first_name=params.first_name,- last_name=params.last_name or None,- **common,- )- else:- raise RuntimeError(f"Unsupported message type: {mt}")+ result = await perform_send(service, chat_id, params)log.info(f"[Telegram] Message sent: type={mt}, chat={chat_id}, " f"msg_id={result.get('message_id')}",)- return {+ # ``sent`` has been declared on TelegramSendOutput since the node was+ # written but was never populated, and ``_serialize_result`` dumps with+ # ``exclude_unset=True`` — so the data picker advertised a field that+ # never materialised. Emit it.+ payload = {"message_id": result.get("message_id"),"chat_id": result.get("chat_id"),"message_type": mt,"date": result.get("date"),+ "sent": True,}+ # Multi-part sends (text over 4096, or a caption that spilled into a+ # threaded follow-up) report the whole chain, not just the first id.+ for key in ("parts", "message_ids", "caption_truncated", "follow_up_message_ids"):+ if key in result:+ payload[key] = result[key]+ return payloaddiff --git a/server/tests/nodes/test_telegram_service.py b/server/tests/nodes/test_telegram_service.pynew file mode 100644index 00000000..f4b09020--- /dev/null+++ b/server/tests/nodes/test_telegram_service.py@@ -0,0 +1,437 @@+"""TelegramService unit tests — split/caption/format logic.++Pure service tests: a ``TelegramService`` is instantiated directly and its+``_bot`` replaced with an ``AsyncMock``. No node harness, no event waiter.+This covers the text-splitting, caption-spill and inbound-formatting logic,+none of which had coverage before.++Companion to ``test_telegram_social.py``, which drives the nodes end to end+through ``NodeTestHarness``.+"""++from __future__ import annotations++from datetime import datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from nodes.telegram._service import (+ _MEDIA_CONTENT_TYPES,+ _detect_content_type,+ _split_head,+ _split_text,+ _tg_len,+ TelegramService,+ _TG_CAPTION_LIMIT,+)++pytestmark = pytest.mark.node_contract+++# ---------------------------------------------------------------------------+# helpers+# ---------------------------------------------------------------------------+++def _message(**overrides):+ """A Bot API message with every media slot empty unless overridden."""+ base = dict(+ message_id=1,+ chat=SimpleNamespace(id=555, type="private", title=None),+ from_user=SimpleNamespace(+ id=77, username="user", first_name="First", last_name=None, is_bot=False+ ),+ date=datetime(2026, 7, 25, 12, 0, 0),+ text=None,+ caption=None,+ media_group_id=None,+ reply_to_message=None,+ photo=None,+ video=None,+ audio=None,+ voice=None,+ document=None,+ sticker=None,+ animation=None,+ video_note=None,+ location=None,+ contact=None,+ poll=None,+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++def _sent(message_id: int = 100):+ msg = MagicMock()+ msg.message_id = message_id+ msg.chat.id = 555+ msg.date.isoformat.return_value = "2026-07-25T12:00:00"+ msg.text = "sent"+ return msg+++def _service_with_bot() -> tuple[TelegramService, MagicMock]:+ service = TelegramService()+ bot = MagicMock()+ bot.send_message = AsyncMock(side_effect=lambda **kw: _sent(200))+ bot.send_photo = AsyncMock(side_effect=lambda **kw: _sent(100))+ bot.send_document = AsyncMock(side_effect=lambda **kw: _sent(101))+ service._bot = bot+ return service, bot+++# ---------------------------------------------------------------------------+# length accounting + splitting+# ---------------------------------------------------------------------------+++def test_tg_len_counts_utf16_units_not_code_points():+ # Telegram measures its caps in UTF-16 units, so an emoji costs 2.+ # len() says 1, which is why over-long messages used to slip through+ # and get rejected by the API.+ assert _tg_len("a") == 1+ assert _tg_len("\U0001f44d") == 2+ assert _tg_len("ab\U0001f44d") == 4+++def test_split_text_returns_short_text_untouched():+ # The fits-in-one path must not rstrip or otherwise rewrite the text.+ assert _split_text(" padded ", 100) == [" padded "]+++def test_split_head_prefers_paragraph_then_line_then_sentence():+ head, tail = _split_head("para one.\n\npara two is longer", 15)+ assert head == "para one."+ assert tail == "para two is longer"++ head, tail = _split_head("line one\nline two is longer", 14)+ assert head == "line one"++ head, tail = _split_head("Sentence one. Sentence two is longer", 20)+ assert head == "Sentence one."+++def test_split_head_hard_cuts_when_no_boundary_exists():+ head, tail = _split_head("x" * 50, 10)+ assert len(head) == 10+ assert len(tail) == 40+++def test_split_text_splits_emoji_by_utf16_budget():+ # 600 emoji = 1200 UTF-16 units, so it must split at a 1024 cap even+ # though len() reports only 600 characters.+ text = "\U0001f44d" * 600+ chunks = _split_text(text, 1024)+ assert len(chunks) > 1+ assert all(_tg_len(chunk) <= 1024 for chunk in chunks)+++# ---------------------------------------------------------------------------+# caption spill+# ---------------------------------------------------------------------------+++async def test_caption_under_the_limit_sends_no_follow_up():+ service, bot = _service_with_bot()+ result = await service.send_photo(chat_id=555, photo="https://x/a.jpg", caption="short")++ assert bot.send_photo.await_count == 1+ assert bot.send_message.await_count == 0+ assert result["caption_truncated"] is False+ assert result["follow_up_message_ids"] == []+++async def test_caption_over_the_limit_truncates_and_threads_the_remainder():+ service, bot = _service_with_bot()+ caption = "A" * (_TG_CAPTION_LIMIT + 500)++ result = await service.send_photo(chat_id=555, photo="https://x/a.jpg", caption=caption)++ # The media send carries a caption within the cap...+ sent_caption = bot.send_photo.await_args.kwargs["caption"]+ assert _tg_len(sent_caption) <= _TG_CAPTION_LIMIT+ # ...and the remainder is threaded underneath it as a reply.+ assert bot.send_message.await_count == 1+ spill = bot.send_message.await_args.kwargs+ assert spill["reply_to_message_id"] == 100+ assert spill["disable_notification"] is True+ assert result["caption_truncated"] is True+ assert result["follow_up_message_ids"] == [200]+++async def test_caption_is_split_before_markdown_conversion():+ """Truncating after markdown->HTML could orphan a <b> from its closer.++ Splitting the raw body keeps every emitted part well-formed.+ """+ service, bot = _service_with_bot()+ # Sized so the split point falls *inside* the bold span: 1000 chars of+ # filler puts the cut in the middle of "**bold spanning the cut**".+ caption = ("word " * 200) + "**bold spanning the cut**"++ await service.send_photo(+ chat_id=555, photo="https://x/a.jpg", caption=caption, parse_mode="Auto"+ )++ head = bot.send_photo.await_args.kwargs["caption"] or ""+ tail = bot.send_message.await_args.kwargs["text"] or ""++ # The marker really is straddled — otherwise this test proves nothing.+ assert "bold" in head and "cut" in tail+ # Neither part may carry a dangling tag. Converting first and splitting+ # after would leave "<b>" open in the head and "</b>" orphaned in the tail,+ # which Telegram rejects with "can't find end of the entity".+ for part in (head, tail):+ assert part.count("<b>") == part.count("</b>")+++async def test_document_caption_spills_through_the_same_path():+ service, bot = _service_with_bot()+ result = await service.send_document(+ chat_id=555, document="https://x/a.pdf", caption="B" * (_TG_CAPTION_LIMIT + 10)+ )++ assert bot.send_document.await_count == 1+ assert bot.send_message.await_count == 1+ assert result["caption_truncated"] is True+++# ---------------------------------------------------------------------------+# inbound formatting+# ---------------------------------------------------------------------------+++def test_animation_is_not_classified_as_document():+ """Telegram sets .document on animation messages too.++ Probing document first made every GIF arrive as a document, dropping the+ animation metadata.+ """+ msg = _message(+ animation=SimpleNamespace(+ file_id="ANIM",+ file_unique_id="uniq",+ width=320,+ height=240,+ duration=3,+ file_name="cat.gif",+ mime_type="video/mp4",+ file_size=1024,+ ),+ document=SimpleNamespace(+ file_id="DOC",+ file_unique_id="uniq",+ file_name="cat.gif",+ mime_type="image/gif",+ file_size=1024,+ ),+ )+ assert _detect_content_type(msg) == "animation"++ data = TelegramService()._format_message(msg)+ assert data["content_type"] == "animation"+ assert data["media"]["file_id"] == "ANIM"+++ "field,obj,kind",+ [+ (+ "voice",+ SimpleNamespace(+ file_id="V", file_unique_id="uv", duration=5, mime_type=None, file_size=99+ ),+ "voice",+ ),+ (+ "video",+ SimpleNamespace(+ file_id="VD",+ file_unique_id="uvd",+ width=1,+ height=2,+ duration=4,+ file_name="v.mp4",+ mime_type="video/mp4",+ file_size=10,+ ),+ "video",+ ),+ (+ "sticker",+ SimpleNamespace(+ file_id="S",+ file_unique_id="us",+ width=1,+ height=1,+ emoji="\U0001f600",+ set_name="pack",+ is_animated=False,+ is_video=False,+ file_size=7,+ ),+ "sticker",+ ),+ (+ "video_note",+ SimpleNamespace(+ file_id="VN", file_unique_id="uvn", length=240, duration=6, file_size=11+ ),+ "video_note",+ ),+ (+ "audio",+ SimpleNamespace(+ file_id="A",+ file_unique_id="ua",+ duration=8,+ performer="p",+ title="t",+ file_name="a.mp3",+ mime_type="audio/mpeg",+ file_size=12,+ ),+ "audio",+ ),+ ],+)+def test_every_media_kind_is_extracted_and_normalized(field, obj, kind):+ """Before this, only photo/document/location/contact survived —+ video, audio, voice, sticker and poll file_ids were dropped."""+ data = TelegramService()._format_message(_message(**{field: obj}))++ assert data["content_type"] == kind+ assert data[kind]["file_id"] == obj.file_id+ assert data["has_media"] is True++ media = data["media"]+ assert media["kind"] == kind+ assert media["file_id"] == obj.file_id+ assert media["mime_type"], "mime_type must be synthesised when Telegram omits it"+ assert media["file_name"], "file_name must be synthesised when Telegram omits it"+ # The trigger never downloads; media travels as an id, not bytes.+ assert media["file_path"] is None+ assert media["downloaded"] is False+ assert "data" not in media and "base64" not in media+++def test_voice_gets_a_synthesised_ogg_mime_and_name():+ voice = SimpleNamespace(+ file_id="V", file_unique_id="uv", duration=5, mime_type=None, file_size=99+ )+ media = TelegramService()._format_message(_message(voice=voice))["media"]+ assert media["mime_type"] == "audio/ogg"+ assert media["file_name"].endswith(".ogg")+++def test_animated_and_video_stickers_get_distinct_mimes():+ def sticker(**kw):+ return SimpleNamespace(+ file_id="S",+ file_unique_id="us",+ width=1,+ height=1,+ emoji=None,+ set_name=None,+ is_animated=False,+ is_video=False,+ file_size=1,+ **kw,+ )++ plain = TelegramService()._format_message(_message(sticker=sticker()))["media"]+ assert plain["mime_type"] == "image/webp"++ animated = sticker()+ animated.is_animated = True+ assert (+ TelegramService()._format_message(_message(sticker=animated))["media"]["mime_type"]+ == "application/x-tgsticker"+ )+++def test_poll_and_location_details_are_captured():+ poll = SimpleNamespace(+ id="p1",+ question="Which?",+ options=[SimpleNamespace(text="a"), SimpleNamespace(text="b")],+ type="regular",+ is_anonymous=True,+ allows_multiple_answers=False,+ is_closed=False,+ total_voter_count=3,+ )+ data = TelegramService()._format_message(_message(poll=poll))+ assert data["content_type"] == "poll"+ assert data["poll"]["options"] == ["a", "b"]+ # A poll is not a downloadable file.+ assert data["has_media"] is False+ assert data["media"] is None++ location = SimpleNamespace(+ latitude=1.5, longitude=2.5, horizontal_accuracy=None, live_period=None+ )+ loc = TelegramService()._format_message(_message(location=location))+ assert loc["location"]["latitude"] == 1.5+++def test_text_still_falls_back_to_caption():+ """Back-compat lock: workflows read `text` on photo messages."""+ photo = SimpleNamespace(+ file_id="P", file_unique_id="up", width=1, height=1, file_size=5+ )+ data = TelegramService()._format_message(_message(photo=[photo], caption="a caption"))++ assert data["text"] == "a caption" # unchanged historical behaviour+ assert data["caption"] == "a caption" # new, additive+ assert data["media"]["caption"] == "a caption"+++def test_reply_to_carries_quoted_media():+ quoted = _message(+ message_id=42,+ voice=SimpleNamespace(+ file_id="QV", file_unique_id="uqv", duration=2, mime_type=None, file_size=3+ ),+ )+ data = TelegramService()._format_message(_message(text="transcribe this", reply_to_message=quoted))++ assert data["reply_to_message_id"] == 42+ assert data["reply_to"]["content_type"] == "voice"+ assert data["reply_to"]["media"]["file_id"] == "QV"+++def test_media_group_id_is_exposed_for_album_correlation():+ photo = SimpleNamespace(file_id="P", file_unique_id="up", width=1, height=1, file_size=5)+ data = TelegramService()._format_message(_message(photo=[photo], media_group_id="alb-1"))+ assert data["media_group_id"] == "alb-1"+++def test_detail_extraction_failure_does_not_drop_the_message():+ """A partial provider payload must not stop the event reaching the workflow."""+ broken = SimpleNamespace(file_id="V") # missing every other attribute+ data = TelegramService()._format_message(_message(voice=broken))++ assert data["content_type"] == "voice"+ assert data["message_id"] == 1 # the message still came through+ assert data.get("voice") is None+++def test_media_content_types_covers_every_downloadable_kind():+ assert _MEDIA_CONTENT_TYPES == {+ "photo",+ "video",+ "audio",+ "voice",+ "animation",+ "video_note",+ "sticker",+ "document",+ }diff --git a/server/tests/nodes/test_telegram_social.py b/server/tests/nodes/test_telegram_social.pyindex bef95f84..9ae38b9b 100644--- a/server/tests/nodes/test_telegram_social.py+++ b/server/tests/nodes/test_telegram_social.py@@ -213,6 +213,73 @@ class TestTelegramSend:harness.assert_envelope(result, success=False)assert "invalid parameters" in result["error"].lower()+ async def test_sent_flag_is_emitted_on_success(self, harness):+ """``sent`` was declared on the Output model but never populated, so+ ``exclude_unset=True`` meant the data picker advertised a phantom+ field. It must now appear in the payload."""+ svc = _make_telegram_service(connected=True, owner_chat_id=9999)++ with _patch_telegram_service(svc):+ result = await harness.execute(+ "telegramSend",+ {"recipient_type": "self", "message_type": "text", "text": "hello"},+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["sent"] is True++ async def test_multipart_send_reports_the_whole_chain(self, harness):+ """A text over 4096 becomes several Telegram messages; the caller+ needs every id, not just the first."""+ svc = _make_telegram_service(connected=True, owner_chat_id=1)+ svc.send_message = AsyncMock(+ return_value={+ "message_id": 42,+ "chat_id": 111,+ "date": "2026-04-15T00:00:00",+ "text": "hi",+ "parts": 3,+ "message_ids": [42, 43, 44],+ }+ )++ with _patch_telegram_service(svc):+ result = await harness.execute(+ "telegramSend",+ {"recipient_type": "self", "message_type": "text", "text": "x" * 9000},+ )++ payload = result["result"]+ assert payload["parts"] == 3+ assert payload["message_ids"] == [42, 43, 44]++ async def test_caption_spill_surfaces_on_the_output(self, harness):+ svc = _make_telegram_service(connected=True, owner_chat_id=1)+ svc.send_photo = AsyncMock(+ return_value={+ "message_id": 43,+ "chat_id": 111,+ "date": "2026-04-15T00:00:00",+ "caption_truncated": True,+ "follow_up_message_ids": [44],+ }+ )++ with _patch_telegram_service(svc):+ result = await harness.execute(+ "telegramSend",+ {+ "recipient_type": "self",+ "message_type": "photo",+ "media_url": "https://example.com/a.jpg",+ "caption": "A" * 2000,+ },+ )++ payload = result["result"]+ assert payload["caption_truncated"] is True+ assert payload["follow_up_message_ids"] == [44]+# ============================================================================# telegramReceive (trigger via generic handle_trigger_node + event_waiter)@@ -295,6 +362,45 @@ class TestTelegramReceive:# Plugin trigger calls register synchronously and awaits waiter.future.waiter.register.assert_called_once()+ async def test_media_event_survives_the_trigger_envelope(self, harness):+ """A voice message must reach the workflow with its normalized media+ block intact — before this, video/audio/voice/sticker file_ids were+ dropped entirely."""+ svc = _make_telegram_service(connected=True, owner_chat_id=42)+ event = {+ **self.CANNED,+ "text": "",+ "content_type": "voice",+ "has_media": True,+ "voice": {"file_id": "VOICE-1", "duration": 4, "mime_type": "audio/ogg"},+ "media": {+ "kind": "voice",+ "file_id": "VOICE-1",+ "mime_type": "audio/ogg",+ "file_name": "uv.ogg",+ "duration": 4,+ "file_path": None,+ "downloaded": False,+ },+ }+ waiter = _make_waiter_stub(canned_event=event)++ with _patch_telegram_service(svc), patched_broadcaster(), patch("services.event_waiter", waiter):+ result = await harness.execute(+ "telegramReceive",+ {"sender_filter": "all", "content_type_filter": "media"},+ )++ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["content_type"] == "voice"+ assert payload["media"]["file_id"] == "VOICE-1"+ assert payload["media"]["kind"] == "voice"+ assert payload["has_media"] is True+ # The trigger never carries bytes.+ assert payload["media"]["file_path"] is None+ assert payload["media"]["downloaded"] is False+async def test_bot_not_connected_returns_error(self, harness):svc = _make_telegram_service(connected=False)waiter = _make_waiter_stub(canned_event=self.CANNED)