Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(attachments): surface download failures to agents

cyh0fdc4125320e
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index cf100d07a..2c07f004a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,7 +1,7 @@
"""Message routing and Agent communication handlers"""
import logging
-from typing import Optional, List
+from typing import List, Optional, Tuple
from modules.agents import AgentRequest
from modules.im import MessageContext
@@ -197,8 +197,9 @@ class MessageHandler(BaseHandler):
# Process file attachments if present
processed_files = None
+ attachment_errors: List[str] = []
if context.files:
- processed_files = await self._process_file_attachments(context, working_path)
+ processed_files, attachment_errors = await self._process_file_attachments(context, working_path)
if processed_files:
logger.info(f"Processed {len(processed_files)} file attachments for message")
@@ -206,6 +207,8 @@ class MessageHandler(BaseHandler):
if self.config.include_user_info:
message = await self._prepend_user_info(context, message)
+ message = self._append_attachment_errors(message, attachment_errors)
+
request = AgentRequest(
context=context,
message=message,
@@ -537,7 +540,9 @@ class MessageHandler(BaseHandler):
agent_label = label.capitalize() if label else ""
return f"📨 {self._t('message.ack', agent=agent_label)}"
- async def _process_file_attachments(self, context: MessageContext, working_path: str) -> Optional[list]:
+ async def _process_file_attachments(
+ self, context: MessageContext, working_path: str
+ ) -> Tuple[Optional[List[FileAttachment]], List[str]]:
"""Download and process file attachments from the message.
All files (including images) are saved to ~/.vibe_remote/attachments/{channel_id}/
@@ -549,15 +554,15 @@ class MessageHandler(BaseHandler):
working_path: Working directory path (not used for storage, kept for API compat)
Returns:
- List of processed FileAttachment objects with local_path set
+ Tuple of processed attachments and download error messages
"""
import os
import time
from config.paths import get_attachments_dir
- from modules.im.base import FileAttachment
+ from modules.im.base import FileAttachment, FileDownloadResult
if not context.files:
- return None
+ return None, []
# Create channel-specific attachments directory
# Path: ~/.vibe_remote/attachments/{channel_id}/
@@ -565,6 +570,7 @@ class MessageHandler(BaseHandler):
attachments_dir.mkdir(parents=True, exist_ok=True)
processed = []
+ errors: List[str] = []
for attachment in context.files:
if not isinstance(attachment, FileAttachment):
continue
@@ -583,16 +589,27 @@ class MessageHandler(BaseHandler):
safe_name = self._sanitize_filename(attachment.name)
filename = f"{timestamp}_{safe_name}"
local_path = attachments_dir / filename
+ temp_path = attachments_dir / f"{filename}.part"
content = None
detected_sample = None
content_size = None
if hasattr(self.im_client, "download_file_to_path"):
- downloaded = await self.im_client.download_file_to_path(file_info, str(local_path))
- if downloaded:
+ self._cleanup_partial_attachment(temp_path)
+ result = await self.im_client.download_file_to_path(file_info, str(temp_path))
+ if not isinstance(result, FileDownloadResult):
+ result = FileDownloadResult(bool(result), None if result else "Download failed")
+
+ if result.success:
+ os.replace(temp_path, local_path)
content_size = local_path.stat().st_size
with open(local_path, "rb") as file_obj:
detected_sample = file_obj.read(16)
+ else:
+ self._cleanup_partial_attachment(temp_path)
+ error_text = result.error or "Download failed"
+ logger.warning("Failed to download file %s: %s", attachment.name, error_text)
+ errors.append(f"Attachment '{attachment.name}' could not be downloaded: {error_text}")
else:
content = await self.im_client.download_file(file_info)
if content:
@@ -600,6 +617,11 @@ class MessageHandler(BaseHandler):
f.write(content)
content_size = len(content)
detected_sample = content[:16]
+ else:
+ logger.warning("Failed to download file %s: download returned no content", attachment.name)
+ errors.append(
+ f"Attachment '{attachment.name}' could not be downloaded: Download returned no content"
+ )
if content is not None or content_size is not None:
# Detect actual MIME type from magic bytes for images
@@ -626,12 +648,34 @@ class MessageHandler(BaseHandler):
logger.warning(f"Failed to download file: {attachment.name}")
else:
logger.warning(f"Cannot download file: {attachment.name} (no URL or download method)")
+ errors.append(f"Attachment '{attachment.name}' could not be downloaded: No URL or download method")
except Exception as e:
+ self._cleanup_partial_attachment(locals().get("temp_path"))
logger.error(f"Error processing file attachment {attachment.name}: {e}")
+ errors.append(f"Attachment '{attachment.name}' could not be downloaded: {e}")
continue
- return processed if processed else None
+ return (processed if processed else None), errors
+
+ @staticmethod
+ def _cleanup_partial_attachment(path) -> None:
+ if not path:
+ return
+ try:
+ path.unlink(missing_ok=True)
+ except Exception as err:
+ logger.debug("Failed to remove partial attachment %s: %s", path, err)
+
+ @staticmethod
+ def _append_attachment_errors(message: str, errors: List[str]) -> str:
+ if not errors:
+ return message
+
+ error_block = "\n".join(["[Attachment Download Errors]", *[f"- {error}" for error in errors]])
+ if not message or not message.strip():
+ return error_block
+ return f"{message}\n\n{error_block}"
def _detect_image_mime(self, data: bytes) -> Optional[tuple]:
"""Detect image MIME type from magic bytes.
diff --git a/modules/im/base.py b/modules/im/base.py
index bac397a6a..35216a4fb 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -22,6 +22,14 @@ class FileAttachment:
size: Optional[int] = None # File size in bytes
+@dataclass
+class FileDownloadResult:
+ """Result for downloading a remote attachment to a local path."""
+
+ success: bool
+ error: Optional[str] = None
+
+
@dataclass
class MessageContext:
"""Platform-agnostic message context"""
@@ -358,7 +366,7 @@ class BaseIMClient(ABC):
target_path: str,
max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
- ) -> bool:
+ ) -> FileDownloadResult:
"""Download a remote file directly to a local path.
Platforms can override this to stream large files directly to disk.
@@ -368,12 +376,15 @@ class BaseIMClient(ABC):
"""
content = await self.download_file(file_info, max_bytes=max_bytes, timeout_seconds=timeout_seconds)
if content is None:
- return False
+ return FileDownloadResult(False, "Download returned no content")
path = Path(target_path)
path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(content)
- return True
+ try:
+ path.write_bytes(content)
+ except Exception as err:
+ return FileDownloadResult(False, f"Failed to write downloaded file: {err}")
+ return FileDownloadResult(True)
@abstractmethod
async def edit_message(
diff --git a/modules/im/discord.py b/modules/im/discord.py
index b31cbd4cc..b6d5f9944 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -12,6 +12,7 @@ import discord
from .base import (
BaseIMClient,
+ FileDownloadResult,
MessageContext,
InlineKeyboard,
InlineButton,
@@ -483,31 +484,33 @@ class DiscordBot(BaseIMClient):
target_path: str,
max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
- ) -> bool:
+ ) -> FileDownloadResult:
url = file_info.get("url") or file_info.get("url_private_download") or file_info.get("url_private")
if not url:
- return False
+ return FileDownloadResult(False, "No download URL available")
try:
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url) as response:
if response.status != 200:
- return False
+ return FileDownloadResult(False, f"Download failed with HTTP {response.status}")
content_length = response.headers.get("Content-Length")
if max_bytes is not None and content_length and int(content_length) > max_bytes:
- return False
+ return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")
total_size = 0
with open(target_path, "wb") as file_obj:
async for chunk in response.content.iter_chunked(64 * 1024):
total_size += len(chunk)
if max_bytes is not None and total_size > max_bytes:
- return False
+ return FileDownloadResult(
+ False, f"File exceeds the allowed size limit ({max_bytes} bytes)"
+ )
file_obj.write(chunk)
- return True
+ return FileDownloadResult(True)
except Exception as err:
logger.debug("Failed to download Discord file to path: %s", err)
- return False
+ return FileDownloadResult(False, f"Download error: {err}")
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
cached = self._user_info_cache.get(user_id)
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index c86afc5f8..d0424e036 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -12,6 +12,7 @@ import aiohttp
from .base import (
BaseIMClient,
+ FileDownloadResult,
FileAttachment,
InlineButton,
InlineKeyboard,
@@ -1134,14 +1135,14 @@ class FeishuBot(BaseIMClient):
target_path: str,
max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
- ) -> bool:
+ ) -> FileDownloadResult:
message_id = file_info.get("message_id")
file_key = file_info.get("file_key")
if not message_id or not file_key:
url = file_info.get("url")
if not url:
logger.warning("No download info for Feishu file: %s", file_info.get("name"))
- return False
+ return FileDownloadResult(False, "No download URL available")
try:
token = await self._get_tenant_token()
headers = {"Authorization": f"Bearer {token}"} if token else {}
@@ -1149,45 +1150,49 @@ class FeishuBot(BaseIMClient):
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers=headers) as resp:
if resp.status != 200:
- return False
+ return FileDownloadResult(False, f"Download failed with HTTP {resp.status}")
total = 0
with open(target_path, "wb") as file_obj:
async for chunk in resp.content.iter_chunked(64 * 1024):
total += len(chunk)
if max_bytes is not None and total > max_bytes:
- return False
+ return FileDownloadResult(
+ False, f"File exceeds the allowed size limit ({max_bytes} bytes)"
+ )
file_obj.write(chunk)
- return True
+ return FileDownloadResult(True)
except Exception as exc:
logger.error("Error downloading Feishu file: %s", exc)
- return False
+ return FileDownloadResult(False, f"Download error: {exc}")
try:
token = await self._get_tenant_token()
if not token:
- return False
+ return FileDownloadResult(False, "Failed to acquire tenant token")
url = f"{self.config.api_base_url}/open-apis/im/v1/messages/{message_id}/resources/{file_key}?type=file"
timeout = aiohttp.ClientTimeout(total=timeout_seconds)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers={"Authorization": f"Bearer {token}"}) as resp:
if resp.status != 200:
logger.error("Failed to download Feishu file: HTTP %s", resp.status)
- return False
+ return FileDownloadResult(False, f"Download failed with HTTP {resp.status}")
total = 0
with open(target_path, "wb") as file_obj:
async for chunk in resp.content.iter_chunked(64 * 1024):
total += len(chunk)
if max_bytes is not None and total > max_bytes:
logger.warning("Feishu file exceeds max size, aborting")
- return False
+ return FileDownloadResult(
+ False, f"File exceeds the allowed size limit ({max_bytes} bytes)"
+ )
file_obj.write(chunk)
- return True
+ return FileDownloadResult(True)
except asyncio.TimeoutError:
logger.error("Timeout downloading Feishu file")
- return False
+ return FileDownloadResult(False, f"Download timed out after {timeout_seconds} seconds")
except Exception as exc:
logger.error("Error downloading Feishu file: %s", exc)
- return False
+ return FileDownloadResult(False, f"Download error: {exc}")
def _extract_file_attachments(
self, message_id: str, msg_content: Dict[str, Any], msg_type: str
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 755b6d295..b40b3eafe 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -14,6 +14,7 @@ from markdown_to_mrkdwn import SlackMarkdownConverter
from .base import (
BaseIMClient,
+ FileDownloadResult,
MessageContext,
InlineKeyboard,
InlineButton,
@@ -404,16 +405,16 @@ class SlackBot(BaseIMClient):
target_path: str,
max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
- ) -> bool:
+ ) -> FileDownloadResult:
url = file_info.get("url_private_download") or file_info.get("url_private")
if not url:
logger.warning(f"No download URL for file: {file_info.get('name')}")
- return False
+ return FileDownloadResult(False, "No download URL available")
file_size = file_info.get("size")
if max_bytes is not None and file_size and file_size > max_bytes:
logger.warning(f"File too large ({file_size} bytes > {max_bytes}), skipping: {file_info.get('name')}")
- return False
+ return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")
try:
headers = {"Authorization": f"Bearer {self.config.bot_token}"}
@@ -422,12 +423,12 @@ class SlackBot(BaseIMClient):
async with session.get(url, headers=headers) as response:
if response.status != 200:
logger.error(f"Failed to download file: HTTP {response.status}")
- return False
+ return FileDownloadResult(False, f"Download failed with HTTP {response.status}")
content_length = response.headers.get("Content-Length")
if max_bytes is not None and content_length and int(content_length) > max_bytes:
logger.warning(f"File too large ({content_length} bytes), skipping: {file_info.get('name')}")
- return False
+ return FileDownloadResult(False, f"File exceeds the allowed size limit ({max_bytes} bytes)")
total_size = 0
with open(target_path, "wb") as file_obj:
@@ -437,16 +438,18 @@ class SlackBot(BaseIMClient):
logger.warning(
f"File exceeds max size during download, aborting: {file_info.get('name')}"
)
- return False
+ return FileDownloadResult(
+ False, f"File exceeds the allowed size limit ({max_bytes} bytes)"
+ )
file_obj.write(chunk)
- return True
+ return FileDownloadResult(True)
except asyncio.TimeoutError:
logger.error(f"Timeout downloading file: {file_info.get('name')}")
- return False
+ return FileDownloadResult(False, f"Download timed out after {timeout_seconds} seconds")
except Exception as e:
logger.error(f"Error downloading Slack file: {e}")
- return False
+ return FileDownloadResult(False, f"Download error: {e}")
def _extract_file_attachments(self, files: List[Dict[str, Any]]) -> List[FileAttachment]:
"""Convert Slack file objects to FileAttachment list.
diff --git a/tests/test_message_handler_attachments.py b/tests/test_message_handler_attachments.py
index ab5a94a05..bd7e18104 100644
--- a/tests/test_message_handler_attachments.py
+++ b/tests/test_message_handler_attachments.py
@@ -10,7 +10,7 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from modules.im import MessageContext
-from modules.im.base import FileAttachment
+from modules.im.base import FileAttachment, FileDownloadResult
def _load_message_handler_class():
@@ -49,9 +49,11 @@ MessageHandler = _load_message_handler_class()
class _StubIMClient:
- def __init__(self, download_result=None, stream_result=False):
+ def __init__(self, download_result=None, stream_result=False, stream_error=None, leave_partial=False):
self.download_result = download_result
self.stream_result = stream_result
+ self.stream_error = stream_error or "Download failed"
+ self.leave_partial = leave_partial
self.download_calls = []
self.stream_calls = []
self.sent_messages = []
@@ -71,9 +73,11 @@ class _StubIMClient:
async def download_file_to_path(self, file_info, target_path, max_bytes=None, timeout_seconds=30):
self.stream_calls.append((file_info, target_path, max_bytes, timeout_seconds))
if not self.stream_result:
- return False
+ if self.leave_partial:
+ Path(target_path).write_bytes(b"partial")
+ return FileDownloadResult(False, self.stream_error)
Path(target_path).write_bytes(self.download_result or b"")
- return True
+ return FileDownloadResult(True)
class _StubIMClientNoStream:
@@ -119,11 +123,12 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
with tempfile.TemporaryDirectory() as tmpdir:
with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
- processed = await handler._process_file_attachments(context, "/tmp/work")
+ processed, errors = await handler._process_file_attachments(context, "/tmp/work")
self.assertIsNotNone(processed)
assert processed is not None
self.assertEqual(len(processed), 1)
+ self.assertEqual(errors, [])
self.assertEqual(im_client.sent_messages, [])
self.assertEqual(im_client.download_calls, [])
self.assertEqual(len(im_client.stream_calls), 1)
@@ -143,17 +148,55 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
with tempfile.TemporaryDirectory() as tmpdir:
with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
- processed = await handler._process_file_attachments(context, "/tmp/work")
+ processed, errors = await handler._process_file_attachments(context, "/tmp/work")
self.assertIsNotNone(processed)
assert processed is not None
self.assertEqual(len(processed), 1)
+ self.assertEqual(errors, [])
self.assertEqual(im_client.sent_messages, [])
self.assertEqual(len(im_client.download_calls), 1)
self.assertEqual(im_client.stream_calls, [])
self.assertEqual(processed[0].size, len(b"%PDF-1.7\n"))
self.assertTrue(processed[0].local_path)
+ async def test_process_file_attachments_reports_download_errors_and_cleans_partial_files(self):
+ im_client = _StubIMClient(stream_result=False, stream_error="Download failed with HTTP 403", leave_partial=True)
+ handler = MessageHandler(_StubController(im_client))
+ attachment = FileAttachment(
+ name="blocked.pdf",
+ mimetype="application/pdf",
+ url="https://example.test/blocked.pdf",
+ size=1024,
+ )
+ context = MessageContext(user_id="U1", channel_id="C1", files=[attachment])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ attachments_dir = Path(tmpdir) / "C1"
+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
+ processed, errors = await handler._process_file_attachments(context, "/tmp/work")
+
+ residual_files = list(attachments_dir.glob("*")) if attachments_dir.exists() else []
+
+ self.assertIsNone(processed)
+ self.assertEqual(
+ errors,
+ ["Attachment 'blocked.pdf' could not be downloaded: Download failed with HTTP 403"],
+ )
+ self.assertEqual(residual_files, [])
+
+ def test_append_attachment_errors_uses_error_text_without_file_paths(self):
+ handler = MessageHandler(_StubController(_StubIMClient()))
+
+ message = handler._append_attachment_errors(
+ "please review the upload",
+ ["Attachment 'blocked.pdf' could not be downloaded: Download failed with HTTP 403"],
+ )
+
+ self.assertIn("[Attachment Download Errors]", message)
+ self.assertIn("Download failed with HTTP 403", message)
+ self.assertNotIn("/.vibe_remote/attachments/", message)
+
if __name__ == "__main__":
unittest.main()