"""Unit tests for multimodal image and file attachments across Telegram handlers and all LLM agents.""" from __future__ import annotations import asyncio import base64 from datetime import datetime import io import json import struct from typing import Any from unittest.mock import AsyncMock, MagicMock, patch import zipfile import zlib import httpx import pytest from aiogram import Bot, Dispatcher from aiogram.types import Chat, Document, Message, PhotoSize, Sticker, Update, User, Voice from homeagent.agent.antigravity import AntigravityAgent from homeagent.agent.attachments import ( Attachment, build_default_attachment_prompt, build_history_user_text, normalize_mime_type, stage_attachments_in_sandbox, ) from homeagent.agent.conversation import ConversationManager from homeagent.agent.gemini import GeminiAgent from homeagent.agent.mcp_bridge import MCPToolBridge from homeagent.agent.openai_agent import OpenAIAgent from homeagent.bot.handlers import create_bot_router from homeagent.bot.media import MediaGroupBuffer, extract_message_attachments from homeagent.bot.progress import format_tool_progress from homeagent.config import Settings from homeagent.skills.manager import SkillManager from homeagent.tools.registry import ToolRegistry def _make_png(w: int = 4, h: int = 4, rgb: tuple[int, int, int] = (255, 0, 0)) -> bytes: raw = b"".join(b"\x00" + bytes(rgb) * w for _ in range(h)) def _chunk(tag: bytes, data: bytes) -> bytes: return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) return ( b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + _chunk(b"IDAT", zlib.compress(raw)) + _chunk(b"IEND", b"") ) def _make_docx(paragraphs: list[str]) -> bytes: buf = io.BytesIO() body = "".join(f"{p}" for p in paragraphs) xml = ( '' '' f"{body}" ) with zipfile.ZipFile(buf, "w") as zf: zf.writestr("word/document.xml", xml) return buf.getvalue() def _make_xlsx() -> bytes: buf = io.BytesIO() shared = ( '' '' "NameScoreAlice" "" ) sheet = ( '' '' '01' '299' "" ) with zipfile.ZipFile(buf, "w") as zf: zf.writestr("xl/sharedStrings.xml", shared) zf.writestr("xl/worksheets/sheet1.xml", sheet) return buf.getvalue() # ------------------------------------------------------------------------------ # Attachment model & extraction tests # ------------------------------------------------------------------------------ def test_attachment_mime_sniffing_and_text_extraction(): png_bytes = _make_png() assert normalize_mime_type("file.bin", "application/octet-stream", data=png_bytes) == "image/png" assert normalize_mime_type("scan.bin", None, data=b"%PDF-1.7\n...") == "application/pdf" assert normalize_mime_type("script.py", "application/octet-stream", data=b"print(1)\n") in ( "text/x-python", "text/plain", "application/x-python-code", ) py_att = Attachment(filename="script.py", mime_type="text/x-python", data=b"print('hello')\n") assert py_att.is_text assert py_att.extract_text() == "print('hello')\n" png_att = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes) assert png_att.is_raster_image assert not png_att.is_text assert png_att.extract_text() is None docx_att = Attachment( filename="report.docx", mime_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", data=_make_docx(["Привет мир", "Второй абзац"]), ) assert docx_att.is_office_xml assert docx_att.extract_text() == "Привет мир\nВторой абзац" xlsx_att = Attachment( filename="metrics.xlsx", mime_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data=_make_xlsx(), ) xlsx_text = xlsx_att.extract_text() assert xlsx_text is not None assert "Name\tScore" in xlsx_text assert "Alice\t99" in xlsx_text def test_stage_attachments_in_sandbox_sanitizes_paths(tmp_path): settings = Settings(DATA_DIR=tmp_path, SANDBOX_ENABLED=True) att = Attachment( filename="../../etc/evil name.csv", mime_type="text/csv", data=b"a,b\n1,2\n", attachment_id="abcdef123456", ) staged = stage_attachments_in_sandbox([att], settings) assert len(staged) == 1 assert staged[0].sandbox_path is not None assert staged[0].sandbox_path.startswith("uploads/abcdef12_") assert ".." not in staged[0].sandbox_path written = tmp_path / "sandbox_workspace" / staged[0].sandbox_path assert written.read_bytes() == b"a,b\n1,2\n" def test_default_prompt_and_history_summary(): img = Attachment(filename="pic.jpg", mime_type="image/jpeg", data=b"\xff\xd8\xff\xe0", kind="image") assert "изображение" in build_default_attachment_prompt([img]) summary = build_history_user_text("Что тут?", [img]) assert "pic.jpg" in summary assert "Что тут?" in summary # ------------------------------------------------------------------------------ # Telegram media extraction & MediaGroupBuffer tests # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_extract_message_attachments_photo_doc_oversize_and_animated_sticker(): png_bytes = _make_png() bot = MagicMock(spec=Bot) async def fake_download(file_id: str, destination=None, **kwargs): payload = { "photo_large": png_bytes, "doc_txt": b"hello world", "voice_1": b"OggS\x00\x02data", }[file_id] if destination is not None: destination.write(payload) return destination bot.download = AsyncMock(side_effect=fake_download) chat = Chat(id=1, type="private") user = User(id=1, is_bot=False, first_name="U") msg_photo = Message( message_id=1, date=datetime.now(), chat=chat, from_user=user, photo=[ PhotoSize(file_id="photo_small", file_unique_id="s1", width=90, height=90, file_size=500), PhotoSize(file_id="photo_large", file_unique_id="l1", width=800, height=600, file_size=len(png_bytes)), ], ) msg_doc = Message( message_id=2, date=datetime.now(), chat=chat, from_user=user, document=Document(file_id="doc_txt", file_unique_id="d1", file_name="notes.txt", mime_type="text/plain", file_size=11), ) msg_huge = Message( message_id=3, date=datetime.now(), chat=chat, from_user=user, document=Document(file_id="doc_huge", file_unique_id="d2", file_name="huge.zip", file_size=50 * 1024 * 1024), ) msg_voice = Message( message_id=4, date=datetime.now(), chat=chat, from_user=user, voice=Voice(file_id="voice_1", file_unique_id="v1", duration=3, mime_type="audio/ogg", file_size=10), ) msg_tgs = Message( message_id=5, date=datetime.now(), chat=chat, from_user=user, sticker=Sticker( file_id="stk_1", file_unique_id="st1", type="regular", width=512, height=512, is_animated=True, is_video=False, ), ) atts, warns = await extract_message_attachments( bot, [msg_photo, msg_doc, msg_huge, msg_voice, msg_tgs], max_size_bytes=5 * 1024 * 1024, ) assert len(atts) == 3 assert atts[0].filename == "photo_l1.jpg" assert atts[0].data == png_bytes assert atts[1].filename == "notes.txt" assert atts[2].kind == "voice" assert atts[2].mime_type == "audio/ogg" assert len(warns) == 2 assert any("huge.zip" in w for w in warns) assert any(".tgs" in w for w in warns) @pytest.mark.asyncio async def test_media_group_buffer_batches_album(): buf = MediaGroupBuffer(delay_seconds=0.05, max_wait_seconds=0.5) chat = Chat(id=10, type="private") m1 = Message(message_id=101, date=datetime.now(), chat=chat, media_group_id="grp1", caption="Две фотки") m2 = Message(message_id=102, date=datetime.now(), chat=chat, media_group_id="grp1") t1 = asyncio.create_task(buf.collect(m1)) await asyncio.sleep(0.01) res2 = await buf.collect(m2) res1 = await t1 assert res2 is None assert res1 is not None assert [m.message_id for m in res1] == [101, 102] # ------------------------------------------------------------------------------ # GeminiAgent multimodal tests # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_gemini_agent_sends_multimodal_parts_and_persists_compact_history(tmp_path): settings = Settings(LLM_PROVIDER="gemini", GEMINI_API_KEY="fake-key", DATA_DIR=tmp_path) cm = ConversationManager(tmp_path) agent = GeminiAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) mock_resp = MagicMock() mock_resp.function_calls = None mock_resp.text = "На картинке красный квадрат, а в файле число 42." mock_client = MagicMock() mock_client.aio.models.generate_content = AsyncMock(return_value=mock_resp) agent._client = mock_client png_bytes = _make_png() atts = [ Attachment(filename="red.png", mime_type="image/png", data=png_bytes, kind="image"), Attachment(filename="data.txt", mime_type="text/plain", data=b"answer=42", kind="document"), ] reply = await agent.chat(chat_id=1, thread_id=None, user_message="Разбери", attachments=atts) assert "красный квадрат" in reply sent_contents = mock_client.aio.models.generate_content.await_args.kwargs["contents"] user_parts = sent_contents[-1].parts assert any(getattr(p, "text", None) and "answer=42" in p.text for p in user_parts) assert any( getattr(p, "inline_data", None) and p.inline_data.mime_type == "image/png" and p.inline_data.data == png_bytes for p in user_parts ) # Saved session history must NOT contain raw binary bytes, only compact summary saved_history = cm.get_openai_messages(1, None) assert len(saved_history) == 2 assert "red.png" in saved_history[0]["content"] assert "data.txt" in saved_history[0]["content"] # ------------------------------------------------------------------------------ # OpenAIAgent & DeepSeek multimodal tests # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_openai_agent_sends_image_pdf_and_inline_text(tmp_path): settings = Settings(LLM_PROVIDER="openai", OPENAI_API_KEY="sk-test", OPENAI_MODEL="gpt-4o", DATA_DIR=tmp_path) cm = ConversationManager(tmp_path) agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) mock_choice = MagicMock() mock_choice.message.content = "Вижу фото, PDF и код." mock_choice.message.tool_calls = None mock_resp = MagicMock(choices=[mock_choice]) mock_client = MagicMock() mock_client.chat.completions.create = AsyncMock(return_value=mock_resp) agent._client = mock_client png_bytes = _make_png() pdf_bytes = b"%PDF-1.4\n%%EOF" atts = [ Attachment(filename="screen.png", mime_type="image/png", data=png_bytes, kind="image"), Attachment(filename="doc.pdf", mime_type="application/pdf", data=pdf_bytes, kind="document"), Attachment(filename="main.py", mime_type="text/x-python", data=b"x = 123", kind="document"), ] reply = await agent.chat(chat_id=2, thread_id=5, user_message="Проверь вложения", attachments=atts) assert reply == "Вижу фото, PDF и код." sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"] user_content = sent_messages[-1]["content"] assert isinstance(user_content, list) block_types = [b["type"] for b in user_content] assert block_types == ["text", "image_url", "file"] assert "x = 123" in user_content[0]["text"] assert user_content[1]["image_url"]["url"].startswith("data:image/png;base64,") assert user_content[2]["file"]["filename"] == "doc.pdf" assert user_content[2]["file"]["file_data"].startswith("data:application/pdf;base64,") # History persisted as compact string (no base64 data URI) saved = cm.get_openai_messages(2, 5) assert isinstance(saved[0]["content"], str) assert "base64," not in saved[0]["content"] assert "screen.png" in saved[0]["content"] @pytest.mark.asyncio async def test_deepseek_agent_inlines_text_and_avoids_image_url_blocks(tmp_path): settings = Settings(LLM_PROVIDER="deepseek", DEEPSEEK_API_KEY="sk-ds", DATA_DIR=tmp_path) cm = ConversationManager(tmp_path) agent = OpenAIAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) mock_choice = MagicMock() mock_choice.message.content = "Прочитал текст, картинку посмотреть не могу." mock_choice.message.tool_calls = None mock_resp = MagicMock(choices=[mock_choice]) mock_client = MagicMock() mock_client.chat.completions.create = AsyncMock(return_value=mock_resp) agent._client = mock_client atts = [ Attachment(filename="pic.png", mime_type="image/png", data=_make_png(), kind="image"), Attachment(filename="log.txt", mime_type="text/plain", data=b"ERROR: boom", kind="document"), ] reply = await agent.chat(chat_id=3, thread_id=None, user_message="Что здесь?", attachments=atts) assert "Прочитал текст" in reply sent_messages = mock_client.chat.completions.create.await_args.kwargs["messages"] user_content = sent_messages[-1]["content"] assert isinstance(user_content, str) assert "ERROR: boom" in user_content assert "DeepSeek текстовый" in user_content # ------------------------------------------------------------------------------ # MCPToolBridge & AntigravityAgent multimodal tests # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_mcp_tool_bridge_inspect_attachment_image_pdf_and_text(tmp_path): bridge = MCPToolBridge(ToolRegistry()) png_bytes = _make_png() pdf_bytes = b"%PDF-1.4\n%%EOF" img = Attachment(filename="shot.png", mime_type="image/png", data=png_bytes, attachment_id="img1") pdf = Attachment(filename="spec.pdf", mime_type="application/pdf", data=pdf_bytes, attachment_id="pdf1") txt = Attachment(filename="note.md", mime_type="text/markdown", data=b"# Title\nBody", attachment_id="txt1") bridge.register_attachments([img, pdf, txt]) await bridge.ensure_started() try: url = bridge.get_endpoint_url(subagent=False) sub_url = bridge.get_endpoint_url(subagent=True) headers = {"Authorization": f"Bearer {bridge.token}"} async with httpx.AsyncClient(trust_env=False) as client: # Main endpoint exposes inspect_attachment; subagent endpoint does not main_tools = ( await client.post(url, headers=headers, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}) ).json()["result"]["tools"] assert any(t["name"] == "inspect_attachment" for t in main_tools) sub_tools = ( await client.post(sub_url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) ).json()["result"]["tools"] assert all(t["name"] != "inspect_attachment" for t in sub_tools) # 1. Image returns native MCP image block img_res = ( await client.post( url, headers=headers, json={ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "img1"}}, }, ) ).json()["result"] assert img_res["isError"] is False assert img_res["content"][1]["type"] == "image" assert img_res["content"][1]["mimeType"] == "image/png" assert base64.b64decode(img_res["content"][1]["data"]) == png_bytes # 2. PDF returns native MCP resource blob pdf_res = ( await client.post( url, headers=headers, json={ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "pdf1"}}, }, ) ).json()["result"] assert pdf_res["isError"] is False assert pdf_res["content"][1]["type"] == "resource" assert pdf_res["content"][1]["resource"]["mimeType"] == "application/pdf" assert base64.b64decode(pdf_res["content"][1]["resource"]["blob"]) == pdf_bytes # 3. Text returns text content txt_res = ( await client.post( url, headers=headers, json={ "jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "inspect_attachment", "arguments": {"attachment_id": "txt1"}}, }, ) ).json()["result"] assert txt_res["isError"] is False assert "# Title" in txt_res["content"][0]["text"] # mcp_config.json marks inspect_attachment as eager cfg_path = bridge.write_mcp_config(tmp_path) cfg = json.loads(cfg_path.read_text(encoding="utf-8")) assert cfg["mcpServers"]["homeagent"]["tools"]["inspect_attachment"] == {"eager": True} finally: await bridge.stop() @pytest.mark.asyncio async def test_antigravity_agent_chat_with_attachments_keeps_read_file_denied(tmp_path): settings = Settings(LLM_PROVIDER="antigravity", DATA_DIR=tmp_path) cm = ConversationManager(tmp_path) agent = AntigravityAgent(settings=settings, registry=ToolRegistry(), conversation_manager=cm) captured_cmd: list[str] = [] class _FakeStream: def __init__(self, lines: list[bytes]) -> None: self._lines = list(lines) async def readline(self) -> bytes: return self._lines.pop(0) if self._lines else b"" async def read(self) -> bytes: return b"".join(self._lines) class _FakeProc: def __init__(self) -> None: self.stdout = _FakeStream( [ ( json.dumps( { "event": "result", "result": { "conversation_id": "conv-att-1", "status": "SUCCESS", "response": "На фото зелёный квадрат, конфиг корректный.", }, } ) + "\n" ).encode("utf-8") ] ) self.stderr = _FakeStream([]) self.returncode = 0 async def wait(self) -> int: return 0 async def fake_exec(*cmd: str, **kwargs: Any) -> _FakeProc: captured_cmd.extend(cmd) return _FakeProc() img = Attachment(filename="green.png", mime_type="image/png", data=_make_png(), attachment_id="att999") cfg_att = Attachment(filename="app.json", mime_type="application/json", data=b'{"ok": true}', attachment_id="att888") try: with ( patch("homeagent.agent.antigravity._resolve_cli_binary", return_value="/usr/bin/agy"), patch("asyncio.create_subprocess_exec", side_effect=fake_exec), ): res = await agent.chat(chat_id=50, thread_id=None, user_message="Проверь", attachments=[img, cfg_att]) assert "зелёный квадрат" in res prompt = captured_cmd[captured_cmd.index("-p") + 1] assert "mcp_homeagent_inspect_attachment" in prompt assert "att999" in prompt assert '{"ok": true}' in prompt # Host read_file(*) MUST remain strictly denied settings_arg = json.loads(captured_cmd[captured_cmd.index("--settings") + 1]) assert "read_file(*)" in settings_arg["permissions"]["deny"] assert agent._bridge.get_attachment("att999") is not None finally: await agent.close() # ------------------------------------------------------------------------------ # End-to-end Telegram handler tests (photo, reply, album, ghost mode) # ------------------------------------------------------------------------------ @pytest.mark.asyncio async def test_handle_message_photo_without_caption_and_reply_attachment(tmp_path): settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], DATA_DIR=tmp_path) agent = MagicMock() agent.chat = AsyncMock(return_value="Это красная картинка!") router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) dp = Dispatcher() dp.include_router(router) png_bytes = _make_png() bot = MagicMock(spec=Bot) bot.send_rich_message = AsyncMock() bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock())) bot.send_chat_action = AsyncMock() async def fake_download(file_id: str, destination=None, **kwargs): if destination is not None: destination.write(png_bytes) return destination bot.download = AsyncMock(side_effect=fake_download) user = User(id=111, is_bot=False, first_name="Owner") chat = Chat(id=111, type="private") photo_msg = Message( message_id=10, date=datetime.now(), chat=chat, from_user=user, photo=[PhotoSize(file_id="p_1", file_unique_id="u1", width=64, height=64, file_size=len(png_bytes))], ) photo_msg._bot = bot await dp.feed_update(bot, Update(update_id=1, message=photo_msg)) agent.chat.assert_awaited_once() kwargs = agent.chat.await_args.kwargs assert "изображение без подписи" in kwargs["user_message"] assert len(kwargs["attachments"]) == 1 assert kwargs["attachments"][0].mime_type == "image/png" assert kwargs["attachments"][0].data == png_bytes bot.send_rich_message.assert_awaited_once() # Now test replying to a photo with a text question agent.chat.reset_mock() reply_msg = Message( message_id=11, date=datetime.now(), chat=chat, from_user=user, text="Какой здесь цвет?", reply_to_message=photo_msg, ) reply_msg._bot = bot await dp.feed_update(bot, Update(update_id=2, message=reply_msg)) agent.chat.assert_awaited_once() reply_kwargs = agent.chat.await_args.kwargs assert reply_kwargs["user_message"] == "Какой здесь цвет?" assert len(reply_kwargs["attachments"]) == 1 assert reply_kwargs["attachments"][0].source == "reply" @pytest.mark.asyncio async def test_handle_message_oversized_document_replies_with_warning(tmp_path): settings = Settings(ALLOWED_TELEGRAM_USER_IDS=[111], MAX_ATTACHMENT_SIZE_MB=1, DATA_DIR=tmp_path) agent = MagicMock() agent.chat = AsyncMock() router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) dp = Dispatcher() dp.include_router(router) bot = MagicMock(spec=Bot) bot.send_rich_message = AsyncMock() bot.send_message = AsyncMock(return_value=MagicMock(edit_text=AsyncMock(), delete=AsyncMock())) bot.send_chat_action = AsyncMock() user = User(id=111, is_bot=False, first_name="Owner") chat = Chat(id=111, type="private") huge_msg = Message( message_id=20, date=datetime.now(), chat=chat, from_user=user, document=Document(file_id="big", file_unique_id="b1", file_name="video.zip", file_size=5 * 1024 * 1024), ) huge_msg._bot = bot await dp.feed_update(bot, Update(update_id=3, message=huge_msg)) agent.chat.assert_not_awaited() bot.send_rich_message.assert_awaited_once() sent_md = bot.send_rich_message.await_args.kwargs["rich_message"].markdown assert "video.zip" in sent_md assert "слишком большой" in sent_md @pytest.mark.asyncio async def test_guest_message_with_replied_photo(tmp_path): settings = Settings(GHOST_MODE_ENABLED=True, ALLOWED_TELEGRAM_USER_IDS=[777], DATA_DIR=tmp_path) agent = MagicMock() agent.chat = AsyncMock(return_value="На скриншоте ошибка 502.") router = create_bot_router(settings, agent, SkillManager(tmp_path / "skills"), ToolRegistry()) dp = Dispatcher() dp.include_router(router) png_bytes = _make_png() bot = MagicMock(spec=Bot) bot.get_me = AsyncMock(return_value=MagicMock(username="homeagent_bot")) bot.answer_guest_query = AsyncMock() bot.send_chat_action = AsyncMock() async def fake_download(file_id: str, destination=None, **kwargs): if destination is not None: destination.write(png_bytes) return destination bot.download = AsyncMock(side_effect=fake_download) replied = Message( message_id=50, date=datetime.now(), chat=Chat(id=-100500, type="supergroup"), from_user=User(id=222, is_bot=False, first_name="Alice"), photo=[PhotoSize(file_id="gp_1", file_unique_id="gu1", width=320, height=240, file_size=len(png_bytes))], caption="Смотрите что вылезло", ) caller = User(id=777, is_bot=False, first_name="Owner") guest = Message( message_id=51, date=datetime.now(), chat=Chat(id=-100500, type="supergroup"), from_user=caller, reply_to_message=replied, text="@homeagent_bot что это за ошибка?", guest_query_id="gq_photo_1", guest_bot_caller_user=caller, ) guest._bot = bot await dp.feed_update(bot, Update(update_id=4, guest_message=guest)) agent.chat.assert_awaited_once() kwargs = agent.chat.await_args.kwargs assert "Смотрите что вылезло" in kwargs["user_message"] assert "что это за ошибка?" in kwargs["user_message"] assert len(kwargs["attachments"]) == 1 assert kwargs["attachments"][0].source == "reply" bot.answer_guest_query.assert_awaited_once() def test_progress_format_for_inspect_attachment(): assert "прикреплённый файл" in format_tool_progress("inspect_attachment", {"attachment_id": "abc"})