From f07a9cabe1caccaa32e42f93d1908aa0c73db065 Mon Sep 17 00:00:00 2001 From: patrick-chinchill Date: Thu, 1 Oct 2026 03:16:25 -0700 Subject: [PATCH 1/3] feat(telegram): send 2-10 files or attachments as one sendMediaGroup (#278) Ports vercel/chat 8d7ccdb1 (#605, chat@4.34.0) and the media-group half of d5ebec12 (#833, reply_parameters). post_message drops the single-file and single-attachment errors: one upload keeps send_document / send_attachment, 2+ go through _send_document_media_group / _send_attachment_media_group. Every returned message is cached and the last is returned. Part of #184. --- CHANGELOG.md | 4 + docs/UPSTREAM_SYNC.md | 35 ++- src/chat_sdk/adapters/telegram/adapter.py | 339 +++++++++++++++++++--- tests/test_telegram_api.py | 316 ++++++++++++++++++-- 4 files changed, 621 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f9046b7..217a3023 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ Sync wave from `chat@4.31.0` to `chat@4.41.1` (tracking #184). `UPSTREAM_PARITY` stays `4.31.0` until #203. +- **Telegram: multiple files or attachments go out as one media group** (#278; ports vercel/chat `8d7ccdb1` #605, chat@4.34.0). + - **Consumer-visible (Telegram):** `post_message` / `thread.post` with 2–10 `files` or 2–10 `attachments` now sends one `sendMediaGroup` album instead of raising `ValidationError("Telegram adapter supports a single file/attachment upload per message")`. Every sent message is cached and the last one is returned. The caption (with `parse_mode`) goes on the first item only, with the same MarkdownV2 → plain-text retry as single uploads. `thread.reply` threads the album to its target (`reply_parameters`). One file or attachment still uses `sendDocument` / `sendPhoto` / `sendVideo` / `sendAudio`. + - New `ValidationError`s: more than 10 items ("Telegram media groups support 2-10 files"); a card with buttons ("Telegram media groups do not support inline keyboards"); documents or audio mixed with another type (photos and videos may mix). Mixing `files` and `attachments` still raises. + - **Slack Agent Sessions lifecycle and native stop** (#215; Slack half of vercel/chat `2ce2be00` #862, chat@4.39.0, plus `8b6d7f3a` #882 and `2cc8cc3f` #897, chat@4.40.0). Only with `agent_view=True`; without it nothing changes (no `agents.sessions.*` call, byte-identical stream stop payloads). A live check in an `agent_view` workspace is still pending. - **Consumer-visible (agent_view typing):** `start_typing()` without a status (and `thread.start_typing()`) now moves the agent session to `processing` through `agents.sessions.setStatus` (with `initiator_user_id`) instead of calling `assistant.threads.setStatus` with "Typing..."; `start_typing(thread_id, "")` moves it to `active`. A custom status still goes through `assistant.threads.setStatus`. A failed `agents.sessions.setStatus` is logged, with no legacy fallback. The adapter now has `end_typing`, so a reply posted after `thread.start_typing()` (a post, or a post+edit stream) moves the session back to `active` (or the `StreamingPlanOptions.session_status`). - **Consumer-visible (agent_view status and titles):** `set_assistant_status(channel, ts, "")` (or whitespace) sets the session `active` instead of sending an empty status; a custom status without `loading_messages` (explicit or configured) now sends `loading_messages=[status]`. `set_assistant_title` calls `agents.sessions.rename` instead of `assistant.threads.setTitle`. diff --git a/docs/UPSTREAM_SYNC.md b/docs/UPSTREAM_SYNC.md index a5419579..c48346f7 100644 --- a/docs/UPSTREAM_SYNC.md +++ b/docs/UPSTREAM_SYNC.md @@ -1575,8 +1575,8 @@ Ports `aaeede70` (vercel/chat#899, chat@4.40.0) and the Teams handler half of Ports `629e6555` (vercel/chat#760, chat@4.37.0) and `91683e52` (vercel/chat#942, chat@4.41.0) in `adapters/telegram/adapter.py`. The core half of #942 (`WebhookOptions.deduplicate`, task-returning `process_*`) -landed in #191. Outbound multi-file `sendMediaGroup` (`8d7ccdb1`, #605) is -split out to #278. +landed in #191. Outbound multi-file `sendMediaGroup` (`8d7ccdb1`, #605) was +split out to #278 (see "Telegram outbound media groups" below). - `process_update` returns the list of dispatched handler tasks (message, album, slash command, action, reactions). The webhook path ignores it. @@ -1643,6 +1643,34 @@ split out to #278. acknowledgement never reached Telegram (a crash before the next `getUpdates`) is delivered again, as upstream. +### Telegram outbound media groups (chat@4.34, #278) + +Parity with `8d7ccdb1` (vercel/chat#605, chat@4.34.0) in +`adapters/telegram/adapter.py`, plus the media-group half of `d5ebec12` +(#833, `reply_parameters`). + +- `post_message` sends one file / attachment with `send_document` / + `send_attachment` as before, and 2+ with `_send_document_media_group` / + `_send_attachment_media_group` (one `sendMediaGroup`). Every returned + message is parsed and cached; the last one is returned. +- Checks, in upstream order and before any `fetch_data` download: 2–10 items + (`TELEGRAM_MEDIA_GROUP_MIN` / `_MAX`), attachment categories (`file` → + document, `audio` → audio, `image`/`video` → visual; more than one + category raises), then no `reply_markup`. +- Multipart body (`aiohttp.FormData`, rebuilt per attempt for the + MarkdownV2 → plain retry): `chat_id`, `message_thread_id`, + `reply_parameters` (JSON string), `media` (a JSON string of `InputMedia` + items, types from `ATTACHMENT_MEDIA_GROUP_TYPES`) and a `media{i}` file + part per binary payload, referenced as `attach://media{i}`. A URL-only + attachment puts its URL in `media` and has no part. Caption and + `parse_mode` go on item 0 only. Video `width` / `height` are included when + JS `Number.isInteger` would accept them (`_integral_update_id`: an + integral float counts, `bool` does not). +- Tests: the four upstream media-group tests and "threads a media group to + its target" in `tests/test_telegram_api.py` (the adapter test file is not + fidelity-mapped, #78), plus Python-only tests for the inline-keyboard + rejection, the caption retry, and the 10-item audio album. + ### Telegram replies (chat@4.38–4.39, #228) Parity with the Telegram halves of `0f24cc30` (vercel/chat#802, chat@4.38.0), @@ -1671,8 +1699,7 @@ Parity with the Telegram halves of `0f24cc30` (vercel/chat#802, chat@4.38.0), `send_attachment` URL/upload paths: a dict in JSON bodies (omitted when there is no target), a JSON string in multipart bodies. A rich-endpoint `ValidationError` mentioning `reply_parameters` falls back to a regular - send. Outbound media groups (#278) are not ported yet, so they get - `reply_parameters` when #278 lands. + send. Outbound media groups (#278) carry it in their multipart body too. - **Message-id parsing.** Bare ids must fully match `[0-9]+` and composite ids `([^:]+):([0-9]+)` (`re.fullmatch`), the ASCII-digit, end-anchored meaning of upstream's `/^\d+$/` and `/^([^:]+):(\d+)$/`. Python's `\d` and `$` would diff --git a/src/chat_sdk/adapters/telegram/adapter.py b/src/chat_sdk/adapters/telegram/adapter.py index 46e78f1d..cf4f1b87 100644 --- a/src/chat_sdk/adapters/telegram/adapter.py +++ b/src/chat_sdk/adapters/telegram/adapter.py @@ -89,6 +89,7 @@ EmojiValue, FetchOptions, FetchResult, + FileUpload, FormattedContent, LockScope, Message, @@ -141,6 +142,15 @@ "image": {"field": "photo", "method": "sendPhoto"}, "video": {"field": "video", "method": "sendVideo"}, } +# Map a normalized Attachment.type to its ``InputMedia`` type inside a +# ``sendMediaGroup`` album. Port of upstream ATTACHMENT_MEDIA_GROUP_TYPES +# (vercel/chat#605). +ATTACHMENT_MEDIA_GROUP_TYPES: dict[str, str] = { + "audio": "audio", + "file": "document", + "image": "photo", + "video": "video", +} LEADING_AT_PATTERN = re.compile(r"^@+") EMOJI_PLACEHOLDER_PATTERN = re.compile(r"^\{\{emoji:([a-z0-9_]+)\}\}$", re.IGNORECASE) EMOJI_NAME_PATTERN = re.compile(r"^[a-z0-9_+-]+$", re.IGNORECASE) @@ -164,7 +174,9 @@ TELEGRAM_INCOMING_MEDIA_GROUP_LOCK_TTL_MS = 5_000 TELEGRAM_INCOMING_MEDIA_GROUP_RETRY_MS = 50 TELEGRAM_INCOMING_MEDIA_GROUP_SETTLE_MS = 1_000 -# Albums hold at most 10 items; the incoming buffer keeps the newest 10. +# Albums hold 2-10 items: ``sendMediaGroup`` accepts that range and the +# incoming buffer keeps the newest 10 parts. +TELEGRAM_MEDIA_GROUP_MIN = 2 TELEGRAM_MEDIA_GROUP_MAX = 10 # Upper bound for both the request-failure backoff and the per-update retry # backoff of the polling loop (vercel/chat#942). @@ -571,6 +583,19 @@ def _integral_update_id(value: Any) -> int | None: return None +@dataclass +class _TelegramMediaGroupPart: + """One ``InputMedia`` item of an outbound ``sendMediaGroup`` album.""" + + media: str + type: str + data: bytes | None = None + filename: str | None = None + mime_type: str | None = None + width: int | None = None + height: int | None = None + + def _js_number_str(value: Any) -> str: """Render a JSON number the way JavaScript's ``String(number)`` does. @@ -2299,18 +2324,7 @@ async def post_message( ) files = extract_files(message) - if len(files) > 1: - raise ValidationError( - "telegram", - "Telegram adapter supports a single file upload per message", - ) - attachments = extract_postable_attachments(message) - if len(attachments) > 1: - raise ValidationError( - "telegram", - "Telegram adapter supports a single attachment upload per message", - ) if files and attachments: raise ValidationError( @@ -2319,27 +2333,50 @@ async def post_message( ) rich = self.resolve_rich_message(message, card, len(files), len(attachments)) - raw_message: TelegramMessage + raw_messages: list[TelegramMessage] - if len(files) == 1: + if files: file = files[0] if not file: raise ValidationError("telegram", "File upload payload is empty") - raw_message = await self.send_document( - parsed_thread, file, text, plain_text, reply_markup, parse_mode, reply_parameters + # 2+ files go out as one album (vercel/chat#605). + raw_messages = ( + [ + await self.send_document( + parsed_thread, file, text, plain_text, reply_markup, parse_mode, reply_parameters + ) + ] + if len(files) == 1 + else await self._send_document_media_group( + parsed_thread, files, text, plain_text, reply_markup, parse_mode, reply_parameters + ) ) - elif len(attachments) == 1: + elif attachments: attachment = attachments[0] if not attachment: raise ValidationError("telegram", "Attachment upload payload is empty") - raw_message = await self.send_attachment( - parsed_thread, - attachment, - text, - plain_text, - reply_markup, - parse_mode, - reply_parameters, + raw_messages = ( + [ + await self.send_attachment( + parsed_thread, + attachment, + text, + plain_text, + reply_markup, + parse_mode, + reply_parameters, + ) + ] + if len(attachments) == 1 + else await self._send_attachment_media_group( + parsed_thread, + attachments, + text, + plain_text, + reply_markup, + parse_mode, + reply_parameters, + ) ) else: if not text.strip(): @@ -2370,37 +2407,48 @@ async def _send_rich() -> TelegramMessage: rich_body["reply_parameters"] = reply_parameters return await self.telegram_fetch("sendRichMessage", rich_body) - raw_message = await self.with_telegram_rich_fallback( - _send_rich, - _send_regular, - method="sendRichMessage", - thread_id=thread_id, - ) + raw_messages = [ + await self.with_telegram_rich_fallback( + _send_rich, + _send_regular, + method="sendRichMessage", + thread_id=thread_id, + ) + ] else: - raw_message = await _send_regular() - - resulting_thread_id = self.encode_thread_id( - TelegramThreadId( - chat_id=str(raw_message["chat"]["id"]), - message_thread_id=( - raw_message.get("message_thread_id") - if raw_message.get("message_thread_id") is not None - else parsed_thread.message_thread_id - ), - ) - ) + raw_messages = [await _send_regular()] # Reuse the locally pre-rendered AST/text when the rich path produced # the message, so Telegram's echo isn't re-parsed (upstream passes # ``{ formatted, text }`` into ``parseTelegramMessage``). parsed_content = TelegramParsedContent(formatted=rich.formatted, text=rich.text) if rich is not None else None - parsed_message = self.parse_telegram_message(raw_message, resulting_thread_id, parsed_content) - self.cache_message(parsed_message) + # A media group returns every sent message: all are cached and the + # last one is returned, as upstream. + parsed_messages: list[Message] = [] + for raw_message in raw_messages: + resulting_thread_id = self.encode_thread_id( + TelegramThreadId( + chat_id=str(raw_message["chat"]["id"]), + message_thread_id=( + raw_message.get("message_thread_id") + if raw_message.get("message_thread_id") is not None + else parsed_thread.message_thread_id + ), + ) + ) + parsed_messages.append(self.parse_telegram_message(raw_message, resulting_thread_id, parsed_content)) + + for parsed_message in parsed_messages: + self.cache_message(parsed_message) + + if not parsed_messages: + raise NetworkError("telegram", "Telegram postMessage did not return any sent messages") + sent_message = parsed_messages[-1] return RawMessage( - id=parsed_message.id, - thread_id=parsed_message.thread_id, - raw=raw_message, + id=sent_message.id, + thread_id=sent_message.thread_id, + raw=sent_message.raw, ) async def post_channel_message( @@ -3835,6 +3883,201 @@ async def _send(resolved_parse_mode: str | None, resolved_text: str) -> Telegram thread_id=self.encode_thread_id(thread), ) + async def _send_document_media_group( + self, + thread: TelegramThreadId, + files: list[FileUpload], + text: str, + plain_text: str, + reply_markup: TelegramInlineKeyboardMarkup | None = None, + parse_mode: str | None = None, + reply_parameters: TelegramReplyParameters | None = None, + ) -> list[TelegramMessage]: + """Send 2-10 file uploads as one ``sendMediaGroup`` album of documents. + + Port of upstream ``sendDocumentMediaGroup`` (vercel/chat#605). + """ + self._validate_media_group_length(len(files)) + + if reply_markup: + raise ValidationError("telegram", "Telegram media groups do not support inline keyboards") + + parts: list[_TelegramMediaGroupPart] = [] + for index, file in enumerate(files): + data: Any = file.data + if isinstance(data, memoryview) or not isinstance(data, bytes): + data = bytes(data) + parts.append( + _TelegramMediaGroupPart( + data=data, + filename=file.filename, + media=f"attach://media{index}", + mime_type=file.mime_type, + type="document", + ) + ) + + return await self._send_media_group(thread, parts, text, plain_text, parse_mode, reply_parameters) + + async def _send_attachment_media_group( + self, + thread: TelegramThreadId, + attachments: list[Attachment], + text: str, + plain_text: str, + reply_markup: TelegramInlineKeyboardMarkup | None = None, + parse_mode: str | None = None, + reply_parameters: TelegramReplyParameters | None = None, + ) -> list[TelegramMessage]: + """Send 2-10 typed attachments as one ``sendMediaGroup`` album. + + Port of upstream ``sendAttachmentMediaGroup`` (vercel/chat#605). + Binary payloads (``data`` or ``fetch_data``) become ``media{i}`` + multipart parts referenced as ``attach://media{i}``; URL-only + attachments pass their URL as ``media``. + """ + self._validate_media_group_length(len(attachments)) + self._validate_attachment_media_group_types(attachments) + + if reply_markup: + raise ValidationError("telegram", "Telegram media groups do not support inline keyboards") + + parts: list[_TelegramMediaGroupPart] = [] + for index, attachment in enumerate(attachments): + data: Any = attachment.data + if data is None and attachment.fetch_data is not None: + data = await attachment.fetch_data() + + if data is None and not attachment.url: + raise ValidationError( + "telegram", + f"Attachment data or URL required for {attachment.type}", + ) + + if data is not None and (isinstance(data, memoryview) or not isinstance(data, bytes)): + data = bytes(data) + + parts.append( + _TelegramMediaGroupPart( + data=data, + filename=attachment.name if attachment.name is not None else f"attachment-{index}", + height=attachment.height, + # ``url`` is non-empty here whenever ``data`` is None. + media=f"attach://media{index}" if data is not None else cast(str, attachment.url), + mime_type=attachment.mime_type, + type=ATTACHMENT_MEDIA_GROUP_TYPES[attachment.type], + width=attachment.width, + ) + ) + + return await self._send_media_group(thread, parts, text, plain_text, parse_mode, reply_parameters) + + async def _send_media_group( + self, + thread: TelegramThreadId, + parts: list[_TelegramMediaGroupPart], + text: str, + plain_text: str, + parse_mode: str | None, + reply_parameters: TelegramReplyParameters | None, + ) -> list[TelegramMessage]: + """Call ``sendMediaGroup`` with the MarkdownV2 -> plain caption retry.""" + + async def _send(resolved_parse_mode: str | None, resolved_text: str) -> list[TelegramMessage]: + # FormData is rebuilt per attempt — see send_document. + return await self.telegram_fetch( + "sendMediaGroup", + self._create_telegram_media_group_form_data( + thread, parts, resolved_text, resolved_parse_mode, reply_parameters + ), + ) + + return await self.with_telegram_markdown_fallback( + parse_mode, + _send, + initial_text=text, + fallback_text=plain_text, + method="sendMediaGroup", + thread_id=self.encode_thread_id(thread), + ) + + def _create_telegram_media_group_form_data( + self, + thread: TelegramThreadId, + parts: list[_TelegramMediaGroupPart], + text: str, + parse_mode: str | None, + reply_parameters: TelegramReplyParameters | None = None, + ) -> Any: + """Build the multipart body for ``sendMediaGroup``. + + ``media`` is a JSON string of ``InputMedia`` items; binary parts follow + as ``media{i}`` file fields. + """ + import aiohttp + + form_data = aiohttp.FormData() + form_data.add_field("chat_id", thread.chat_id) + if isinstance(thread.message_thread_id, int): + form_data.add_field("message_thread_id", str(thread.message_thread_id)) + self._append_reply_parameters(form_data, reply_parameters) + + # Telegram shows an album's caption from the first item that carries + # one; on a later item it renders under that media instead of the + # whole group. + caption_index = 0 + media: list[dict[str, Any]] = [] + for index, part in enumerate(parts): + item: dict[str, Any] = {"media": part.media, "type": part.type} + + if index == caption_index and text.strip(): + item["caption"] = self.truncate_caption(text, parse_mode) + if parse_mode: + item["parse_mode"] = parse_mode + + if part.type == "video": + # Upstream's ``Number.isInteger`` check, the same rule as the + # webhook ``update_id`` (an integral float counts, bool does not). + width = _integral_update_id(part.width) + if width is not None: + item["width"] = width + height = _integral_update_id(part.height) + if height is not None: + item["height"] = height + + media.append(item) + form_data.add_field("media", json.dumps(media)) + + for index, part in enumerate(parts): + if part.data is None: + continue + form_data.add_field( + f"media{index}", + part.data, + filename=part.filename if part.filename is not None else f"media-{index}", + content_type=part.mime_type if part.mime_type is not None else "application/octet-stream", + ) + + return form_data + + @staticmethod + def _validate_media_group_length(count: int) -> None: + if count < TELEGRAM_MEDIA_GROUP_MIN or count > TELEGRAM_MEDIA_GROUP_MAX: + raise ValidationError("telegram", "Telegram media groups support 2-10 files") + + @staticmethod + def _validate_attachment_media_group_types(attachments: list[Attachment]) -> None: + categories = { + "document" if attachment.type == "file" else "audio" if attachment.type == "audio" else "visual" + for attachment in attachments + } + if len(categories) > 1: + raise ValidationError( + "telegram", + "Telegram media groups can mix photos and videos, but documents and audio files " + "must be grouped only with the same type", + ) + # -- Message caching ----------------------------------------------------- def cache_message(self, message: Message) -> None: diff --git a/tests/test_telegram_api.py b/tests/test_telegram_api.py index 0ca9ffeb..b06d9518 100644 --- a/tests/test_telegram_api.py +++ b/tests/test_telegram_api.py @@ -35,7 +35,7 @@ ) from chat_sdk.shared.mock_adapter import create_mock_state from chat_sdk.thread import ThreadImpl, _ThreadImplConfig -from chat_sdk.types import Attachment, FileUpload, PostableMarkdown, PostableRaw +from chat_sdk.types import Attachment, FetchOptions, FileUpload, Message, PostableMarkdown, PostableRaw # ============================================================================= # Helpers @@ -374,26 +374,6 @@ async def test_url_only_video_attachment_includes_dimensions(self): assert payload["width"] == 1280 assert payload["height"] == 720 - @pytest.mark.asyncio - async def test_rejects_multiple_attachments(self): - adapter = _make_adapter() - _init_adapter(adapter) - adapter.telegram_fetch = AsyncMock(return_value=_make_telegram_message()) - - with pytest.raises(ValidationError, match="single attachment upload"): - await adapter.post_message( - THREAD_ID, - PostableRaw( - raw="attachments", - attachments=[ - Attachment(type="image", data=b"one"), - Attachment(type="image", data=b"two"), - ], - ), - ) - - adapter.telegram_fetch.assert_not_called() - @pytest.mark.asyncio async def test_rejects_mixed_files_and_attachments(self): adapter = _make_adapter() @@ -453,6 +433,275 @@ async def test_rejects_unsupported_attachment_type(self): adapter.telegram_fetch.assert_not_called() +# ============================================================================= +# Tests -- outbound media groups (vercel/chat#605, #278) +# ============================================================================= + + +def _album_part(message_id: int, chat_id: str = "123", **media: Any) -> dict[str, Any]: + """A message Telegram returns from ``sendMediaGroup`` (``sampleMessage`` + media).""" + return { + "message_id": message_id, + "chat": {"id": int(chat_id), "type": "private"}, + "from": {"id": 999, "is_bot": True, "first_name": "Bot", "username": "mybot"}, + "date": 1700000000, + **media, + } + + +def _media_group(form_data: Any) -> list[dict[str, Any]]: + """``readMediaGroup``: the ``media`` field must be a JSON string.""" + media = _form_fields(form_data)["media"] + assert isinstance(media, str) + return json.loads(media) + + +def _form_field_names(form_data: Any) -> list[str]: + return [type_options["name"] for type_options, _headers, _value in form_data._fields] + + +_TWO_FILES = [ + FileUpload(data=b"one", filename="one.txt", mime_type="text/plain"), + FileUpload(data=b"two", filename="two.txt", mime_type="text/plain"), +] + + +class TestPostMessageMediaGroups: + """2-10 files or attachments go out as one ``sendMediaGroup``.""" + + @pytest.mark.asyncio + async def test_posts_multiple_files_as_a_telegram_media_group(self): + adapter = _make_adapter(user_name="mybot") + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock( + return_value=[ + _album_part( + 21, + media_group_id="group-1", + document={"file_id": "doc-1", "file_unique_id": "doc-unique-1", "file_name": "one.txt"}, + ), + _album_part( + 22, + media_group_id="group-1", + document={"file_id": "doc-2", "file_unique_id": "doc-unique-2", "file_name": "two.txt"}, + ), + ] + ) + + posted = await adapter.post_message( + "telegram:-100123:42", + PostableMarkdown(markdown="attached **files**", files=list(_TWO_FILES)), + ) + + assert posted.id == "123:22" + adapter.telegram_fetch.assert_awaited_once() + method, form_data = adapter.telegram_fetch.await_args.args + assert method == "sendMediaGroup" + + fields = _form_fields(form_data) + assert fields["chat_id"] == "-100123" + assert fields["message_thread_id"] == "42" + assert _media_group(form_data) == [ + { + "caption": "attached *files*", + "media": "attach://media0", + "parse_mode": "MarkdownV2", + "type": "document", + }, + {"media": "attach://media1", "type": "document"}, + ] + assert _form_binary_field(form_data, "media0") == (b"one", "one.txt", "text/plain") + assert _form_binary_field(form_data, "media1") == (b"two", "two.txt", "text/plain") + # Every returned message is cached, not only the one returned. + cached = await adapter.fetch_messages("telegram:123:42") + assert [message.id for message in cached.messages] == ["123:21", "123:22"] + + @pytest.mark.asyncio + async def test_posts_and_normalizes_mixed_image_and_video_attachments_as_a_telegram_media_group(self): + adapter = _make_adapter(user_name="mybot") + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock( + return_value=[ + _album_part( + 31, + media_group_id="group-2", + photo=[{"file_id": "photo-1", "file_unique_id": "p1", "width": 100, "height": 100}], + ), + _album_part( + 32, + media_group_id="group-2", + video={"file_id": "video-1", "file_unique_id": "v1", "width": 1280, "height": 720}, + ), + ] + ) + + posted = await adapter.post_message( + "telegram:123", + PostableMarkdown( + markdown="visual **album**", + attachments=[ + Attachment( + type="image", + mime_type="image/png", + name="image.png", + url="https://cdn.example.com/image.png", + ), + Attachment( + type="video", + data=b"video", + height=720, + mime_type="video/mp4", + name="video.mp4", + width=1280, + ), + ], + ), + ) + + assert posted.id == "123:32" + method, form_data = adapter.telegram_fetch.await_args.args + assert method == "sendMediaGroup" + assert _media_group(form_data) == [ + { + "caption": "visual *album*", + "media": "https://cdn.example.com/image.png", + "parse_mode": "MarkdownV2", + "type": "photo", + }, + {"height": 720, "media": "attach://media1", "type": "video", "width": 1280}, + ] + assert "media0" not in _form_field_names(form_data) + assert _form_binary_field(form_data, "media1") == (b"video", "video.mp4", "video/mp4") + + cached = await adapter.fetch_messages("telegram:123", FetchOptions(limit=10)) + round_tripped = [ + [ + adapter.rehydrate_attachment(attachment) + for attachment in Message.from_json(json.loads(json.dumps(message.to_json()))).attachments + ] + for message in cached.messages + ] + assert [[(a.type, a.mime_type, a.fetch_metadata) for a in group] for group in round_tripped] == [ + [("image", "image/jpeg", {"fileId": "photo-1", "fileUniqueId": "p1"})], + [("video", None, {"fileId": "video-1", "fileUniqueId": "v1"})], + ] + assert all(callable(a.fetch_data) for group in round_tripped for a in group) + + @pytest.mark.asyncio + async def test_rejects_incompatible_telegram_media_group_attachment_types(self): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[]) + + with pytest.raises(ValidationError, match="documents and audio files must be grouped only"): + await adapter.post_message( + "telegram:123", + PostableRaw( + raw="attachments", + attachments=[Attachment(type="image", data=b"one"), Attachment(type="file", data=b"two")], + ), + ) + + adapter.telegram_fetch.assert_not_awaited() + + @pytest.mark.asyncio + async def test_rejects_telegram_media_groups_with_more_than_10_files(self): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[]) + + with pytest.raises(ValidationError, match="Telegram media groups support 2-10 files"): + await adapter.post_message( + "telegram:123", + PostableRaw( + raw="files", + files=[FileUpload(data=str(index).encode(), filename=f"{index}.txt") for index in range(11)], + ), + ) + + adapter.telegram_fetch.assert_not_awaited() + + @pytest.mark.asyncio + async def test_sends_ten_audio_attachments_as_one_media_group(self): + # Edge case beyond upstream: the 10-item upper bound is inclusive and + # a same-category (audio) album passes the type check. + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[_album_part(index) for index in range(1, 11)]) + + posted = await adapter.post_message( + "telegram:123", + PostableRaw(raw="", attachments=[Attachment(type="audio", data=b"a") for _ in range(10)]), + ) + + assert posted.id == "123:10" + method, form_data = adapter.telegram_fetch.await_args.args + assert method == "sendMediaGroup" + media = _media_group(form_data) + assert [item["type"] for item in media] == ["audio"] * 10 + # ``raw=""`` carries no caption. + assert "caption" not in media[0] + assert _form_binary_field(form_data, "media9")[1] == "attachment-9" + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "uploads", + [ + pytest.param({"files": list(_TWO_FILES)}, id="files"), + pytest.param( + {"attachments": [Attachment(type="image", data=b"1"), Attachment(type="image", data=b"2")]}, + id="attachments", + ), + ], + ) + async def test_rejects_an_inline_keyboard_on_a_media_group(self, uploads: dict[str, Any]): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[]) + card = { + "type": "card", + "title": "Pick", + "children": [{"type": "actions", "children": [{"type": "button", "id": "yes", "label": "Yes"}]}], + } + + with pytest.raises(ValidationError, match="Telegram media groups do not support inline keyboards"): + await adapter.post_message("telegram:123", {"card": card, **uploads}) + + adapter.telegram_fetch.assert_not_awaited() + + @pytest.mark.asyncio + async def test_retries_a_media_group_caption_as_plain_text_when_markdown_v2_is_rejected(self): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock( + side_effect=[ + ValidationError("telegram", "Bad Request: can't parse caption entities: Can't find end of the entity"), + [_album_part(41), _album_part(42)], + ] + ) + + posted = await adapter.post_message( + "telegram:123", + PostableMarkdown(markdown="attached **files**", files=list(_TWO_FILES)), + ) + + assert posted.id == "123:42" + assert adapter.telegram_fetch.await_count == 2 + (first_method, first_form), (retry_method, retry_form) = [ + call.args for call in adapter.telegram_fetch.await_args_list + ] + assert first_method == retry_method == "sendMediaGroup" + assert _media_group(first_form)[0]["parse_mode"] == "MarkdownV2" + # A fresh multipart body (aiohttp FormData is single-use) with the + # plain caption and no parse_mode. + assert retry_form is not first_form + assert _media_group(retry_form) == [ + {"caption": "attached files", "media": "attach://media0", "type": "document"}, + {"media": "attach://media1", "type": "document"}, + ] + assert _form_binary_field(retry_form, "media1")[0] == b"two" + + # ============================================================================= # Tests -- edit_message # ============================================================================= @@ -2302,6 +2551,31 @@ async def test_threads_a_buffer_attachment_to_its_target(self): assert method == "sendPhoto" assert json.loads(_form_fields(form_data)["reply_parameters"]) == EXPECTED_REPLY_PARAMETERS + @pytest.mark.asyncio + async def test_threads_a_media_group_to_its_target(self): + adapter = _reply_adapter( + [ + _make_telegram_message(chat_id="123", message_id=11), + _make_telegram_message(chat_id="123", message_id=12), + ] + ) + + await adapter.reply( + REPLY_THREAD_ID, + "123:7", + PostableMarkdown( + markdown="album", + attachments=[ + Attachment(type="image", data=b"one", name="one.png"), + Attachment(type="image", data=b"two", name="two.png"), + ], + ), + ) + + method, form_data = _only_call(adapter) + assert method == "sendMediaGroup" + assert json.loads(_form_fields(form_data)["reply_parameters"]) == EXPECTED_REPLY_PARAMETERS + @pytest.mark.asyncio async def test_falls_back_to_a_regular_send_when_the_rich_endpoint_rejects_reply_parameters(self): # The error a 400 from the Bot API maps to. From 2cb701bff2a1504dd674319d11b916716cf88231 Mon Sep 17 00:00:00 2001 From: patrick-chinchill Date: Thu, 1 Oct 2026 03:16:36 -0700 Subject: [PATCH 2/3] diverge(telegram): reject an unknown attachment type in a media group before downloading (#278) Upstream's TS union rules the value out; in Python the ATTACHMENT_MEDIA_GROUP_TYPES lookup would raise a bare KeyError after earlier attachments were downloaded. Raise send_attachment's ValidationError up front instead. Non-parity row added. Closes #278 --- CHANGELOG.md | 1 + docs/UPSTREAM_SYNC.md | 8 ++++++- src/chat_sdk/adapters/telegram/adapter.py | 12 ++++++++++ tests/test_telegram_api.py | 28 +++++++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 217a3023..bddf6347 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Sync wave from `chat@4.31.0` to `chat@4.41.1` (tracking #184). `UPSTREAM_PARITY` - **Telegram: multiple files or attachments go out as one media group** (#278; ports vercel/chat `8d7ccdb1` #605, chat@4.34.0). - **Consumer-visible (Telegram):** `post_message` / `thread.post` with 2–10 `files` or 2–10 `attachments` now sends one `sendMediaGroup` album instead of raising `ValidationError("Telegram adapter supports a single file/attachment upload per message")`. Every sent message is cached and the last one is returned. The caption (with `parse_mode`) goes on the first item only, with the same MarkdownV2 → plain-text retry as single uploads. `thread.reply` threads the album to its target (`reply_parameters`). One file or attachment still uses `sendDocument` / `sendPhoto` / `sendVideo` / `sendAudio`. - New `ValidationError`s: more than 10 items ("Telegram media groups support 2-10 files"); a card with buttons ("Telegram media groups do not support inline keyboards"); documents or audio mixed with another type (photos and videos may mix). Mixing `files` and `attachments` still raises. + - **Python-specific (divergence from upstream):** an unknown `Attachment.type` in an album raises `ValidationError("Unsupported attachment type: ...")` before any download, as single attachments already do. - **Slack Agent Sessions lifecycle and native stop** (#215; Slack half of vercel/chat `2ce2be00` #862, chat@4.39.0, plus `8b6d7f3a` #882 and `2cc8cc3f` #897, chat@4.40.0). Only with `agent_view=True`; without it nothing changes (no `agents.sessions.*` call, byte-identical stream stop payloads). A live check in an `agent_view` workspace is still pending. - **Consumer-visible (agent_view typing):** `start_typing()` without a status (and `thread.start_typing()`) now moves the agent session to `processing` through `agents.sessions.setStatus` (with `initiator_user_id`) instead of calling `assistant.threads.setStatus` with "Typing..."; `start_typing(thread_id, "")` moves it to `active`. A custom status still goes through `assistant.threads.setStatus`. A failed `agents.sessions.setStatus` is logged, with no legacy fallback. The adapter now has `end_typing`, so a reply posted after `thread.start_typing()` (a post, or a post+edit stream) moves the session back to `active` (or the `StreamingPlanOptions.session_status`). diff --git a/docs/UPSTREAM_SYNC.md b/docs/UPSTREAM_SYNC.md index c48346f7..516f1589 100644 --- a/docs/UPSTREAM_SYNC.md +++ b/docs/UPSTREAM_SYNC.md @@ -1666,10 +1666,15 @@ Parity with `8d7ccdb1` (vercel/chat#605, chat@4.34.0) in `parse_mode` go on item 0 only. Video `width` / `height` are included when JS `Number.isInteger` would accept them (`_integral_update_id`: an integral float counts, `bool` does not). +- **Python-specific (divergence, one row in the non-parity table):** an + `Attachment.type` outside `ATTACHMENT_MEDIA_GROUP_TYPES` raises + `send_attachment`'s `ValidationError("Unsupported attachment type: ...")` + before any download (upstream's TS union rules it out; the dict lookup + would raise `KeyError`). - Tests: the four upstream media-group tests and "threads a media group to its target" in `tests/test_telegram_api.py` (the adapter test file is not fidelity-mapped, #78), plus Python-only tests for the inline-keyboard - rejection, the caption retry, and the 10-item audio album. + rejection, the caption retry, the 10-item audio album and the unknown type. ### Telegram replies (chat@4.38–4.39, #228) @@ -3301,6 +3306,7 @@ stay explicit instead of being rediscovered in code review. | Telegram `get_user().is_bot` | Always `False` (matches upstream — `getChat` does not expose `is_bot`) | Always `false` (same caveat documented in upstream code comment) | The Telegram Bot API's `getChat` endpoint does not surface the `is_bot` field that's available on the `User` object inside incoming `Message` updates. Callers needing bot detection must use `message.author.is_bot` from webhooks instead of `chat.get_user(...).is_bot`. | | Telegram webhook verification + `update_id` dedupe (4.41 wave, #224) | **Parity** with upstream `c4a359e7` (vercel/chat#858, chat@4.39), `1d2b78d9` (#799, chat@4.38) and the bot-identity scope helper from `7a1150ce` (#813): webhook mode requires `secret_token` unless `allow_unverified_webhooks` / `TELEGRAM_ALLOW_UNVERIFIED_WEBHOOKS=true`; each integer `update_id` is claimed as `telegram:webhook-update:{sha256(bot_user_id)}:{update_id}` (24h) before dispatch; state/identity failure → 503. Python-surface adaptations only: the `ValidationError` text names options in snake_case (`secret_token`, `allow_unverified_webhooks=True`); the shared `getMe` is an `asyncio.Task` awaited through `asyncio.shield` so a cancelled webhook does not cancel it for other waiters; `update_id` claiming mirrors `Number.isInteger`: an integral JSON float (`7.0`, `7e0` — floats under `json.loads`, the number 7 in JS) is normalised to `int` and shares the `...:7` key, while `bool` (an `int` subclass) and fractional floats are not claimed. **Deliberate Python divergence:** a non-`bool` `allow_unverified_webhooks` (e.g. the string `"false"`) raises `ValidationError` instead of being coerced truthy — upstream's TS `boolean` type rules this out at compile time, Python has no such guard and `bool("false")` would silently fail open. `secret_token` now resolves with `??` semantics (`is not None`), replacing the earlier `or` fallback, so an explicit `""` no longer silently picks up the env secret. **Deliberate Python divergence (fixes an upstream bug):** the `getMe` username is cached and reapplied on a repeat `initialize()` — upstream's `ensureBotIdentity` returns early once `webhookScope` is set, so after `initialize` re-applies `chat.getUserName()` the Telegram username is never restored and `@real_bot` / `/cmd@real_bot` stop routing after a shutdown + re-initialize. `allow_unverified_webhooks` is the *last* `TelegramAdapterConfig` field (not alphabetical) so positional callers are not shifted. | Same | Not ported here: the Vercel Connect async `bot_token` resolver (#189) and the polling checkpoint keyed on the same scope (#227, now ported: see the Telegram polling section above). Cross-instance dedupe on Postgres relies on #240, which makes `set_if_not_exists` reclaim expired rows. | | Telegram inbound parsing, allowlist and typing (4.41 wave, #225) | **Parity** with upstream `4ee187ac` (#612), `2531a422` (#621, Telegram half), `0701679e` (#706, regex cache only), `54eea715` (#742), `53bf73db` (#752), `a0ba9868` (#835), `a18e7922` (#836) and the Telegram half of `b6fa24c6` (#865). Python-surface adaptations only, no behavior divergence beyond the mention-regex fold and the `allowed_user_ids` type check noted here: location coordinates and dice values go through `_js_number_str`, which renders a JSON number as JS `String()` does (`51.0` -> `"51"`, `1e-05` -> `"0.00001"`, `1.5e-07` -> `"1.5e-7"`), since `json.loads` keeps floats that JS prints differently; invoice amounts use `f"{amount / 10**e:.{e}f}"` for `toFixed(e)`; the mention pattern is `@{re.escape(name)}(?![A-Za-z0-9_-])` with `re.IGNORECASE`, because JS `\w` without the `u` flag is ASCII-only while Python's is Unicode (JS `/i` still folds non-ASCII letters, so `re.ASCII` is not used: `@ботик` matches `@БОТИК` on both sides; one residual difference is that Python's Unicode folding also equates the Kelvin sign with `k` and long s `ſ` with `s`, which JS's non-`u` canonicalization never maps onto ASCII, so `@` + U+212A + `bot` mentions a `kbot` in Python only); allowlist ids are stringified with the same `_js_number_str` (`456.0` -> `"456"`); a non-list `allowed_user_ids` (e.g. a bare `"123,456"` string, which Python would iterate per character, where upstream's `.map` throws) raises `ValidationError`; and the acting-user chain (`callback_query.from` -> `message_reaction.user` -> first non-`None` of `message`/`edited_message`/`channel_post`/`edited_channel_post` `.from`) uses `is not None` at every step; the typing action runs as an `asyncio` task created before `Chat.process_message`/`process_slash_command` schedules the handler task (JS fires the request synchronously; in Python both are tasks and run FIFO, so typing still goes first), is passed to `wait_until` when given and otherwise held in `_typing_tasks` so it is not garbage-collected (`disconnect()` cancels and awaits any still pending before closing the aiohttp session, so none reopens it); the download uses the shared aiohttp session with `ClientTimeout(total=30)` (covers the body read) and a running byte count over `response.content.iter_chunked`, raising `NetworkError`. It deliberately does **not** use `chat_sdk.shared.download` (#204): its HTTPS/public-address checks would break self-hosted Bot API servers, which upstream also exempts, and `read_attachment_body` decodes `Content-Encoding` itself while the shared aiohttp session already auto-decompresses. | Same | The media-group (album) path, its typing and the `pollingGroup` allowlist check landed in #227 (see the Telegram polling section above). `reply_to_message` parsing and `mentionOnReply` landed in #228 (see the Telegram replies section). Not ported here: `business_message.from` in the allowlist chain (#189). | +| Telegram unknown `Attachment.type` in an outbound media group (#278) | `_validate_attachment_media_group_types` raises `ValidationError("Unsupported attachment type: ...")` before any `fetch_data` download, as `send_attachment` already does for one attachment | No check: `ATTACHMENT_MEDIA_GROUP_TYPES[type]` gives `undefined` and Telegram rejects the request | The TS `Attachment["type"]` union rules the value out at compile time; Python `Literal` does not, and the dict lookup would raise a bare `KeyError` after earlier attachments were already downloaded. Test: `test_rejects_an_unsupported_attachment_type_in_a_media_group_before_downloading`. | | WhatsApp `get_user` | Raises `ChatNotImplementedError` (`Chat.get_user` translates to "does not support get_user") | Not implemented upstream either (no `getUser` on the WhatsApp adapter) | WhatsApp Cloud API has no user lookup endpoint — phone numbers are the only stable identifier and there's no equivalent of `users.info` exposed to business apps. Documented explicitly so callers don't expect parity with Slack/Teams/Discord. | | Messenger `get_user` | Raising stub (`ChatNotImplementedError`); a Graph-API-backed impl is tracked as issue #132 | No `getUser` method on the Messenger adapter | **Parity — upstream Messenger has no user-lookup method**; the Python raising stub matches. (Meta's Graph API *could* back a real implementation, unlike WhatsApp — hence #132 stays open as an enhancement.) | | Linear agent sessions | **Complete** (5-PR wave, **#151** — Wave D done). All five landed on `main`: L1 agent-session types (`LinearAgentSessionThreadId`, `LinearAgentSessionCommentRawMessage`, `mode`/`kind`), L2 the `:s:{session}` thread-id encode/decode, L3 the webhook PARSE + routing (`_parse_message_from_agent_session_event`, `_handle_agent_session_event`), L4 the agent-activity EMIT path (`post_message`/`start_typing`/`stream` session branches as raw GraphQL — see the "Linear agent-activity emit" divergence row above), and **L5 (this change)**: the agent-session FETCH path (`fetch_messages` → `_fetch_agent_session_messages`, the `edit_message`/`delete_message` append-only guards, and `fetch_thread` `agentSessionId` metadata as raw GraphQL — see the "Linear agent-session fetch" divergence row above). | Full agent-sessions support (`adapter-linear` 4.27.0, `bc94f0a`): parses agent-session webhook events into messages, emits agent activity, fetches the session thread, and routes the agent-session thread id | Largest single gap from the 0.4.30 audit; pre-existing (present since 0.4.29). Closed across the 4.31 wave — tracked in **#151**. | diff --git a/src/chat_sdk/adapters/telegram/adapter.py b/src/chat_sdk/adapters/telegram/adapter.py index cf4f1b87..928891a0 100644 --- a/src/chat_sdk/adapters/telegram/adapter.py +++ b/src/chat_sdk/adapters/telegram/adapter.py @@ -4067,6 +4067,18 @@ def _validate_media_group_length(count: int) -> None: @staticmethod def _validate_attachment_media_group_types(attachments: list[Attachment]) -> None: + # Divergence from upstream — see docs/UPSTREAM_SYNC.md + # An unknown ``type`` is rejected here, before any download, with + # ``send_attachment``'s message (upstream's TS union rules it out at + # compile time; the dict lookup would raise KeyError). + for attachment in attachments: + if attachment.type not in ATTACHMENT_MEDIA_GROUP_TYPES: + raise ValidationError( + "telegram", + f"Unsupported attachment type: {attachment.type}. " + f"Supported types: {', '.join(ATTACHMENT_MEDIA_GROUP_TYPES)}", + ) + categories = { "document" if attachment.type == "file" else "audio" if attachment.type == "audio" else "visual" for attachment in attachments diff --git a/tests/test_telegram_api.py b/tests/test_telegram_api.py index b06d9518..ec4f9bed 100644 --- a/tests/test_telegram_api.py +++ b/tests/test_telegram_api.py @@ -701,6 +701,34 @@ async def test_retries_a_media_group_caption_as_plain_text_when_markdown_v2_is_r ] assert _form_binary_field(retry_form, "media1")[0] == b"two" + @pytest.mark.asyncio + async def test_rejects_an_unsupported_attachment_type_in_a_media_group_before_downloading(self): + """Divergence from upstream: an out-of-set ``type`` raises ValidationError + (not ``KeyError``) before any ``fetch_data`` download. + + ``Attachment.type`` is a ``Literal`` Python does not enforce; upstream's + TS union rules the value out at compile time (docs/UPSTREAM_SYNC.md). + """ + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[]) + fetch_data = AsyncMock(return_value=b"payload") + + with pytest.raises(ValidationError, match="Unsupported attachment type: sticker"): + await adapter.post_message( + "telegram:123", + PostableRaw( + raw="", + attachments=[ + Attachment(type="image", fetch_data=fetch_data), + Attachment(type="sticker", data=b"x"), # type: ignore[arg-type] + ], + ), + ) + + fetch_data.assert_not_awaited() + adapter.telegram_fetch.assert_not_awaited() + # ============================================================================= # Tests -- edit_message From faf6a302bd1bb5440acb6211b0a273823fad6e69 Mon Sep 17 00:00:00 2001 From: patrick-chinchill Date: Thu, 1 Oct 2026 03:27:12 -0700 Subject: [PATCH 3/3] test(telegram): pin media-group fetch_data upload, audio category, keyboard-before-download, video-only integral dimensions, empty result (#278) --- tests/test_telegram_api.py | 101 ++++++++++++++++++++++++++++++++----- 1 file changed, 88 insertions(+), 13 deletions(-) diff --git a/tests/test_telegram_api.py b/tests/test_telegram_api.py index ec4f9bed..03f7e336 100644 --- a/tests/test_telegram_api.py +++ b/tests/test_telegram_api.py @@ -31,6 +31,7 @@ AdapterPermissionError, AdapterRateLimitError, AuthenticationError, + NetworkError, ValidationError, ) from chat_sdk.shared.mock_adapter import create_mock_state @@ -588,7 +589,15 @@ async def test_posts_and_normalizes_mixed_image_and_video_attachments_as_a_teleg assert all(callable(a.fetch_data) for group in round_tripped for a in group) @pytest.mark.asyncio - async def test_rejects_incompatible_telegram_media_group_attachment_types(self): + @pytest.mark.parametrize( + "types", + [ + pytest.param(("image", "file"), id="image-and-document"), + # Audio is its own category: it may not join a photo/video album. + pytest.param(("audio", "image"), id="audio-and-image"), + ], + ) + async def test_rejects_incompatible_telegram_media_group_attachment_types(self, types: tuple[str, str]): adapter = _make_adapter() _init_adapter(adapter) adapter.telegram_fetch = AsyncMock(return_value=[]) @@ -598,7 +607,7 @@ async def test_rejects_incompatible_telegram_media_group_attachment_types(self): "telegram:123", PostableRaw( raw="attachments", - attachments=[Attachment(type="image", data=b"one"), Attachment(type="file", data=b"two")], + attachments=[Attachment(type=t, data=b"x") for t in types], # type: ignore[arg-type] ), ) @@ -644,20 +653,17 @@ async def test_sends_ten_audio_attachments_as_one_media_group(self): assert _form_binary_field(form_data, "media9")[1] == "attachment-9" @pytest.mark.asyncio - @pytest.mark.parametrize( - "uploads", - [ - pytest.param({"files": list(_TWO_FILES)}, id="files"), - pytest.param( - {"attachments": [Attachment(type="image", data=b"1"), Attachment(type="image", data=b"2")]}, - id="attachments", - ), - ], - ) - async def test_rejects_an_inline_keyboard_on_a_media_group(self, uploads: dict[str, Any]): + @pytest.mark.parametrize("kind", ["files", "attachments"]) + async def test_rejects_an_inline_keyboard_on_a_media_group(self, kind: str): adapter = _make_adapter() _init_adapter(adapter) adapter.telegram_fetch = AsyncMock(return_value=[]) + fetch_data = AsyncMock(return_value=b"payload") + uploads: dict[str, Any] = ( + {"files": list(_TWO_FILES)} + if kind == "files" + else {"attachments": [Attachment(type="image", fetch_data=fetch_data), Attachment(type="image", data=b"2")]} + ) card = { "type": "card", "title": "Pick", @@ -667,6 +673,8 @@ async def test_rejects_an_inline_keyboard_on_a_media_group(self, uploads: dict[s with pytest.raises(ValidationError, match="Telegram media groups do not support inline keyboards"): await adapter.post_message("telegram:123", {"card": card, **uploads}) + # The keyboard is rejected before any attachment is downloaded. + fetch_data.assert_not_awaited() adapter.telegram_fetch.assert_not_awaited() @pytest.mark.asyncio @@ -701,6 +709,73 @@ async def test_retries_a_media_group_caption_as_plain_text_when_markdown_v2_is_r ] assert _form_binary_field(retry_form, "media1")[0] == b"two" + @pytest.mark.asyncio + async def test_uploads_fetch_data_bytes_in_a_media_group_instead_of_the_url(self): + # Re-posting received attachments: they carry ``fetch_data`` (and maybe + # a URL); the downloaded bytes win, as upstream ``data ? attach:// : url``. + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[_album_part(51), _album_part(52)]) + fetch_data = AsyncMock(return_value=b"fetched") + + await adapter.post_message( + "telegram:123", + PostableRaw( + raw="", + attachments=[ + Attachment( + type="image", + url="https://cdn.example.com/image.png", + fetch_data=fetch_data, + mime_type="image/png", + name="image.png", + ), + Attachment(type="image", data=b"second"), + ], + ), + ) + + fetch_data.assert_awaited_once() + _method, form_data = adapter.telegram_fetch.await_args.args + assert [item["media"] for item in _media_group(form_data)] == ["attach://media0", "attach://media1"] + assert _form_binary_field(form_data, "media0") == (b"fetched", "image.png", "image/png") + + @pytest.mark.asyncio + async def test_media_group_sends_integral_dimensions_only_for_videos(self): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[_album_part(61), _album_part(62)]) + + await adapter.post_message( + "telegram:123", + PostableRaw( + raw="", + attachments=[ + Attachment(type="image", data=b"photo", width=640, height=480), + # ``Number.isInteger``: 1280.0 is the integer 1280, ``True`` is not a number. + Attachment(type="video", data=b"video", width=1280.0, height=True), # type: ignore[arg-type] + ], + ), + ) + + _method, form_data = adapter.telegram_fetch.await_args.args + photo, video = _media_group(form_data) + assert photo == {"media": "attach://media0", "type": "photo"} + assert video == {"media": "attach://media1", "type": "video", "width": 1280} + # JSON ``1280`` (int), not ``1280.0``. + assert type(video["width"]) is int + + @pytest.mark.asyncio + async def test_raises_network_error_when_send_media_group_returns_no_messages(self): + adapter = _make_adapter() + _init_adapter(adapter) + adapter.telegram_fetch = AsyncMock(return_value=[]) + + with pytest.raises(NetworkError, match="Telegram postMessage did not return any sent messages"): + await adapter.post_message("telegram:123", PostableRaw(raw="", files=list(_TWO_FILES))) + + adapter.telegram_fetch.assert_awaited_once() + @pytest.mark.asyncio async def test_rejects_an_unsupported_attachment_type_in_a_media_group_before_downloading(self): """Divergence from upstream: an out-of-set ``type`` raises ValidationError