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(interactions): keep answers visible and stream attachments

cyh06d8e7f172c7
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 48e217bae..cf100d07a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -579,11 +579,32 @@ class MessageHandler(BaseHandler):
"name": attachment.name,
"size": attachment.size,
}
- content = await self.im_client.download_file(file_info)
- if content:
+ timestamp = int(time.time())
+ safe_name = self._sanitize_filename(attachment.name)
+ filename = f"{timestamp}_{safe_name}"
+ local_path = attachments_dir / filename
+ 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:
+ content_size = local_path.stat().st_size
+ with open(local_path, "rb") as file_obj:
+ detected_sample = file_obj.read(16)
+ else:
+ content = await self.im_client.download_file(file_info)
+ if content:
+ with open(local_path, "wb") as f:
+ f.write(content)
+ content_size = len(content)
+ detected_sample = content[:16]
+
+ if content is not None or content_size is not None:
# Detect actual MIME type from magic bytes for images
# (some platforms don't provide accurate MIME, e.g. Feishu)
- detected = self._detect_image_mime(content)
+ detected = self._detect_image_mime(detected_sample or b"")
if detected:
attachment.mimetype = detected[0]
# Fix filename extension to match actual type
@@ -591,23 +612,14 @@ class MessageHandler(BaseHandler):
base = os.path.splitext(attachment.name)[0]
attachment.name = f"{base}{ext}"
- # Generate filename: {timestamp}_{original_name}
- timestamp = int(time.time())
- safe_name = self._sanitize_filename(attachment.name)
- filename = f"{timestamp}_{safe_name}"
- local_path = attachments_dir / filename
-
- with open(local_path, "wb") as f:
- f.write(content)
-
attachment.local_path = str(local_path)
- attachment.size = len(content)
+ attachment.size = content_size
# Determine file type for logging
is_image = (attachment.mimetype or "").startswith("image/")
file_type = "image" if is_image else "file"
- logger.info(f"Saved {file_type} '{attachment.name}' ({len(content)} bytes) to '{local_path}'")
+ logger.info(f"Saved {file_type} '{attachment.name}' ({content_size} bytes) to '{local_path}'")
processed.append(attachment)
else:
diff --git a/modules/agents/claude_question_handler.py b/modules/agents/claude_question_handler.py
index 8b61c4e94..ce00aa071 100644
--- a/modules/agents/claude_question_handler.py
+++ b/modules/agents/claude_question_handler.py
@@ -199,18 +199,14 @@ class ClaudeQuestionHandler:
return False
# Update UI to show selection
- await self._ui_handler.update_prompt_after_answer(
- request, pending, answers_payload
- )
+ await self._ui_handler.update_prompt_after_answer(request, pending)
# Build answer text for Claude
answer_text = self._build_answer_text(answers_payload, pending)
# Submit tool result to Claude
try:
- await self._submit_tool_result(
- client, composite_session_id, tool_use_id, answer_text
- )
+ await self._submit_tool_result(client, composite_session_id, tool_use_id, answer_text)
except Exception as err:
logger.error(f"Failed to submit answer to Claude: {err}", exc_info=True)
await self._controller.emit_agent_message(
@@ -220,6 +216,8 @@ class ClaudeQuestionHandler:
)
return False
+ await self._ui_handler.send_answer_receipt(request, answers_payload)
+
# Add reaction to indicate answer received
await self._ui_handler.add_answer_reaction(request, pending)
@@ -286,9 +284,7 @@ class ClaudeQuestionHandler:
return questions
- def _parse_answer(
- self, message: str, pending: PendingQuestion
- ) -> Optional[List[List[str]]]:
+ def _parse_answer(self, message: str, pending: PendingQuestion) -> Optional[List[List[str]]]:
"""Parse answer from callback data or user message.
Returns answers_payload in format [[answer1], [answer2], ...]
@@ -333,9 +329,7 @@ class ClaudeQuestionHandler:
return None
- def _build_answer_text(
- self, answers_payload: List[List[str]], pending: PendingQuestion
- ) -> str:
+ def _build_answer_text(self, answers_payload: List[List[str]], pending: PendingQuestion) -> str:
"""Build answer text to send back to Claude.
Format: "User has answered your questions: Q1=answer1, Q2=answer2"
@@ -393,9 +387,7 @@ class ClaudeQuestionHandler:
else:
raise RuntimeError("Claude SDK client transport not available")
- async def _on_timeout(
- self, request: AgentRequest, pending: PendingQuestion
- ) -> None:
+ async def _on_timeout(self, request: AgentRequest, pending: PendingQuestion) -> None:
"""Handle timeout when user doesn't answer."""
# Clean up our state
self._pending_tool_use_ids.pop(request.base_session_id, None)
diff --git a/modules/agents/opencode/question_handler.py b/modules/agents/opencode/question_handler.py
index 5d415d845..445dd8fda 100644
--- a/modules/agents/opencode/question_handler.py
+++ b/modules/agents/opencode/question_handler.py
@@ -16,6 +16,7 @@ from typing import Any, Dict, List, Optional
from modules.agents.base import AgentRequest
+from ..question_ui import build_answer_receipt_text
from .server import OpenCodeServerManager
from .types import PendingQuestionPayload
@@ -176,22 +177,15 @@ class OpenCodeQuestionHandler:
"Timed out waiting for your answer (30 minutes). Please re-run your request.",
)
- def _build_question_selection_note(self, answers_payload: List[List[str]]) -> str:
- if not answers_payload:
- return ""
-
- if len(answers_payload) == 1:
- joined = ", ".join([value for value in answers_payload[0] if value])
- return f"已选择:{joined}" if joined else ""
+ async def _send_answer_receipt(self, request: AgentRequest, answers_payload: List[List[str]]) -> None:
+ receipt_text = build_answer_receipt_text(self._controller, answers_payload)
+ if not receipt_text:
+ return
- lines = []
- for idx, answers in enumerate(answers_payload, start=1):
- joined = ", ".join([value for value in answers if value])
- if joined:
- lines.append(f"Q{idx}: {joined}")
- if not lines:
- return ""
- return "已选择:\n" + "\n".join(lines)
+ try:
+ await self._im_client.send_message(request.context, receipt_text)
+ except Exception as err:
+ logger.debug(f"Failed to send answer receipt: {err}")
async def open_question_modal(self, request: AgentRequest, pending: PendingQuestionPayload) -> None:
trigger_id = None
@@ -360,29 +354,16 @@ class OpenCodeQuestionHandler:
answers_payload = [[answer_text] for _ in range(question_count_int)]
if question_message_id and hasattr(self._im_client, "remove_inline_keyboard"):
- note = self._build_question_selection_note(answers_payload)
fallback_text = pending.get("prompt_text") if isinstance(pending, dict) else None
- if note:
- try:
- updated_text = f"{fallback_text}\n\n{note}" if fallback_text else note
- await self._im_client.remove_inline_keyboard(
- request.context,
- question_message_id,
- text=updated_text,
- parse_mode="markdown",
- )
- except Exception as err:
- logger.debug(f"Failed to update question message: {err}")
- else:
- try:
- await self._im_client.remove_inline_keyboard(
- request.context,
- question_message_id,
- text=fallback_text,
- parse_mode="markdown",
- )
- except Exception as err:
- logger.debug(f"Failed to remove question buttons: {err}")
+ try:
+ await self._im_client.remove_inline_keyboard(
+ request.context,
+ question_message_id,
+ text=fallback_text,
+ parse_mode="markdown",
+ )
+ except Exception as err:
+ logger.debug(f"Failed to remove question buttons: {err}")
try:
ok = await server.reply_question(question_id, directory, answers_payload)
@@ -407,6 +388,8 @@ class OpenCodeQuestionHandler:
)
return
+ await self._send_answer_receipt(request, answers_payload)
+
# Add 👀 reaction to question message to indicate answer received
# Track it for cleanup when the request completes
if question_message_id and hasattr(self._im_client, "add_reaction"):
diff --git a/modules/agents/question_ui.py b/modules/agents/question_ui.py
index b1be44b7d..7310a31bb 100644
--- a/modules/agents/question_ui.py
+++ b/modules/agents/question_ui.py
@@ -17,10 +17,45 @@ from dataclasses import dataclass, field
from typing import Any, Callable, Coroutine, Dict, List, Optional
from modules.agents.base import AgentRequest
+from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
+def _translate(controller, key: str, **kwargs: Any) -> str:
+ translator = getattr(controller, "_t", None)
+ if callable(translator):
+ return str(translator(key, **kwargs))
+
+ config = getattr(controller, "config", None)
+ lang = getattr(config, "language", "en")
+ return str(i18n_t(key, lang, **kwargs))
+
+
+def build_answer_summary(answers_payload: List[List[str]]) -> str:
+ if not answers_payload:
+ return ""
+
+ if len(answers_payload) == 1:
+ return ", ".join([value for value in answers_payload[0] if value])
+
+ lines = []
+ for idx, answers in enumerate(answers_payload, start=1):
+ joined = ", ".join([value for value in answers if value])
+ if joined:
+ lines.append(f"Q{idx}: {joined}")
+ return "\n".join(lines)
+
+
+def build_answer_receipt_text(controller, answers_payload: List[List[str]]) -> str:
+ summary = build_answer_summary(answers_payload)
+ if not summary:
+ return ""
+
+ receipt_value = f"\n{summary}" if "\n" in summary else summary
+ return _translate(controller, "message.quickReplyNote", text=receipt_value)
+
+
@dataclass
class QuestionOption:
"""A single option in a question."""
@@ -427,56 +462,42 @@ class QuestionUIHandler:
# Answer processing helpers
# -------------------------------------------------------------------------
- def build_selection_note(self, answers_payload: List[List[str]]) -> str:
- """Build a note showing what the user selected."""
- if not answers_payload:
- return ""
-
- if len(answers_payload) == 1:
- joined = ", ".join([value for value in answers_payload[0] if value])
- return f"已选择:{joined}" if joined else ""
-
- lines = []
- for idx, answers in enumerate(answers_payload, start=1):
- joined = ", ".join([value for value in answers if value])
- if joined:
- lines.append(f"Q{idx}: {joined}")
- if not lines:
- return ""
- return "已选择:\n" + "\n".join(lines)
-
async def update_prompt_after_answer(
self,
request: AgentRequest,
pending: PendingQuestion,
- answers_payload: List[List[str]],
) -> None:
- """Update the prompt message after answer is submitted."""
+ """Remove question controls without writing the answer into the prompt."""
question_message_id = pending.prompt_message_id
if not question_message_id or not hasattr(self._im_client, "remove_inline_keyboard"):
return
- note = self.build_selection_note(answers_payload)
fallback_text = pending.prompt_text
try:
- if note:
- updated_text = f"{fallback_text}\n\n{note}" if fallback_text else note
- await self._im_client.remove_inline_keyboard(
- request.context,
- question_message_id,
- text=updated_text,
- parse_mode="markdown",
- )
- else:
- await self._im_client.remove_inline_keyboard(
- request.context,
- question_message_id,
- text=fallback_text,
- parse_mode="markdown",
- )
+ await self._im_client.remove_inline_keyboard(
+ request.context,
+ question_message_id,
+ text=fallback_text,
+ parse_mode="markdown",
+ )
except Exception as err:
logger.debug(f"Failed to update question message: {err}")
+ async def send_answer_receipt(
+ self,
+ request: AgentRequest,
+ answers_payload: List[List[str]],
+ ) -> None:
+ """Send a visible follow-up message showing what the user selected."""
+ receipt_text = build_answer_receipt_text(self._controller, answers_payload)
+ if not receipt_text:
+ return
+
+ try:
+ await self._im_client.send_message(request.context, receipt_text)
+ except Exception as err:
+ logger.debug(f"Failed to send answer receipt: {err}")
+
async def add_answer_reaction(
self,
request: AgentRequest,
diff --git a/modules/im/base.py b/modules/im/base.py
index b0e2fb3dc..bac397a6a 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -1,6 +1,7 @@
"""Base classes and data structures for IM platform abstraction"""
import logging
+from pathlib import Path
from abc import ABC, abstractmethod
from typing import Optional, Callable, Dict, Any, List, Tuple, cast
from dataclasses import dataclass
@@ -342,6 +343,38 @@ class BaseIMClient(ABC):
"""
return await self.upload_file_from_path(context, file_path, title=title)
+ async def download_file(
+ self,
+ file_info: Dict[str, Any],
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> Optional[bytes]:
+ """Download a remote file into memory (optional per platform)."""
+ raise NotImplementedError
+
+ async def download_file_to_path(
+ self,
+ file_info: Dict[str, Any],
+ target_path: str,
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> bool:
+ """Download a remote file directly to a local path.
+
+ Platforms can override this to stream large files directly to disk.
+ The default implementation falls back to ``download_file`` and writes
+ the bytes afterward, which is less memory-efficient but preserves
+ compatibility.
+ """
+ content = await self.download_file(file_info, max_bytes=max_bytes, timeout_seconds=timeout_seconds)
+ if content is None:
+ return False
+
+ path = Path(target_path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(content)
+ return True
+
@abstractmethod
async def edit_message(
self,
diff --git a/modules/im/discord.py b/modules/im/discord.py
index b1dbea892..b31cbd4cc 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -10,7 +10,13 @@ from urllib.parse import urlsplit
import aiohttp
import discord
-from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachment
+from .base import (
+ BaseIMClient,
+ MessageContext,
+ InlineKeyboard,
+ InlineButton,
+ FileAttachment,
+)
from config.v2_config import DiscordConfig
from .formatters import DiscordFormatter
from vibe.i18n import get_supported_languages, t as i18n_t
@@ -444,7 +450,7 @@ class DiscordBot(BaseIMClient):
async def download_file(
self,
file_info: Dict[str, Any],
- max_bytes: int = 20 * 1024 * 1024,
+ max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
) -> Optional[bytes]:
url = file_info.get("url") or file_info.get("url_private_download") or file_info.get("url_private")
@@ -457,13 +463,13 @@ class DiscordBot(BaseIMClient):
if response.status != 200:
return None
content_length = response.headers.get("Content-Length")
- if content_length and int(content_length) > max_bytes:
+ if max_bytes is not None and content_length and int(content_length) > max_bytes:
return None
chunks = []
total_size = 0
async for chunk in response.content.iter_chunked(64 * 1024):
total_size += len(chunk)
- if total_size > max_bytes:
+ if max_bytes is not None and total_size > max_bytes:
return None
chunks.append(chunk)
return b"".join(chunks)
@@ -471,6 +477,38 @@ class DiscordBot(BaseIMClient):
logger.debug("Failed to download Discord file: %s", err)
return None
+ async def download_file_to_path(
+ self,
+ file_info: Dict[str, Any],
+ target_path: str,
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> bool:
+ url = file_info.get("url") or file_info.get("url_private_download") or file_info.get("url_private")
+ if not url:
+ return False
+ 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
+ content_length = response.headers.get("Content-Length")
+ if max_bytes is not None and content_length and int(content_length) > max_bytes:
+ return False
+
+ 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
+ file_obj.write(chunk)
+ return True
+ except Exception as err:
+ logger.debug("Failed to download Discord file to path: %s", err)
+ return False
+
async def get_user_info(self, user_id: str) -> Dict[str, Any]:
cached = self._user_info_cache.get(user_id)
if cached is not None:
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index c2001d6b4..c86afc5f8 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -10,7 +10,13 @@ from typing import Any, Callable, Dict, List, Optional
import aiohttp
-from .base import BaseIMClient, FileAttachment, InlineButton, InlineKeyboard, MessageContext
+from .base import (
+ BaseIMClient,
+ FileAttachment,
+ InlineButton,
+ InlineKeyboard,
+ MessageContext,
+)
from .formatters import FeishuFormatter
from config.v2_config import LarkConfig
from vibe.i18n import get_supported_languages, t as i18n_t
@@ -1063,7 +1069,7 @@ class FeishuBot(BaseIMClient):
async def download_file(
self,
file_info: Dict[str, Any],
- max_bytes: int = 20 * 1024 * 1024,
+ max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
) -> Optional[bytes]:
"""Download a file from Feishu."""
@@ -1087,7 +1093,7 @@ class FeishuBot(BaseIMClient):
total = 0
async for chunk in resp.content.iter_chunked(64 * 1024):
total += len(chunk)
- if total > max_bytes:
+ if max_bytes is not None and total > max_bytes:
return None
chunks.append(chunk)
return b"".join(chunks)
@@ -1110,7 +1116,7 @@ class FeishuBot(BaseIMClient):
total = 0
async for chunk in resp.content.iter_chunked(64 * 1024):
total += len(chunk)
- if total > max_bytes:
+ if max_bytes is not None and total > max_bytes:
logger.warning("Feishu file exceeds max size, aborting")
return None
chunks.append(chunk)
@@ -1122,6 +1128,67 @@ class FeishuBot(BaseIMClient):
logger.error("Error downloading Feishu file: %s", exc)
return None
+ async def download_file_to_path(
+ self,
+ file_info: Dict[str, Any],
+ target_path: str,
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> bool:
+ 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
+ try:
+ token = await self._get_tenant_token()
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(url, headers=headers) as resp:
+ if resp.status != 200:
+ return False
+ 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
+ file_obj.write(chunk)
+ return True
+ except Exception as exc:
+ logger.error("Error downloading Feishu file: %s", exc)
+ return False
+
+ try:
+ token = await self._get_tenant_token()
+ if not token:
+ return False
+ 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
+ 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
+ file_obj.write(chunk)
+ return True
+ except asyncio.TimeoutError:
+ logger.error("Timeout downloading Feishu file")
+ return False
+ except Exception as exc:
+ logger.error("Error downloading Feishu file: %s", exc)
+ return False
+
def _extract_file_attachments(
self, message_id: str, msg_content: Dict[str, Any], msg_type: str
) -> Optional[List[FileAttachment]]:
diff --git a/modules/im/slack.py b/modules/im/slack.py
index b290333b3..755b6d295 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -12,7 +12,13 @@ from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.errors import SlackApiError
from markdown_to_mrkdwn import SlackMarkdownConverter
-from .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachment
+from .base import (
+ BaseIMClient,
+ MessageContext,
+ InlineKeyboard,
+ InlineButton,
+ FileAttachment,
+)
from config.v2_config import SlackConfig
from core.auth import AuthResult
from .formatters import SlackFormatter
@@ -334,14 +340,14 @@ class SlackBot(BaseIMClient):
async def download_file(
self,
file_info: Dict[str, Any],
- max_bytes: int = 20 * 1024 * 1024, # 20MB default limit
+ max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
) -> Optional[bytes]:
"""Download a Slack file using the private URL.
Args:
file_info: Slack file object containing url_private_download and other metadata
- max_bytes: Maximum file size to download (default 20MB)
+ max_bytes: Maximum file size to download
timeout_seconds: Request timeout in seconds (default 30s)
Returns:
@@ -354,7 +360,7 @@ class SlackBot(BaseIMClient):
# Check file size before download if available
file_size = file_info.get("size")
- if file_size and file_size > max_bytes:
+ 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 None
@@ -369,7 +375,7 @@ class SlackBot(BaseIMClient):
# Check content-length header
content_length = response.headers.get("Content-Length")
- if content_length and int(content_length) > max_bytes:
+ 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 None
@@ -378,7 +384,7 @@ class SlackBot(BaseIMClient):
total_size = 0
async for chunk in response.content.iter_chunked(64 * 1024):
total_size += len(chunk)
- if total_size > max_bytes:
+ if max_bytes is not None and total_size > max_bytes:
logger.warning(f"File exceeds max size during download, aborting: {file_info.get('name')}")
return None
chunks.append(chunk)
@@ -392,6 +398,56 @@ class SlackBot(BaseIMClient):
logger.error(f"Error downloading Slack file: {e}")
return None
+ async def download_file_to_path(
+ self,
+ file_info: Dict[str, Any],
+ target_path: str,
+ max_bytes: Optional[int] = None,
+ timeout_seconds: int = 30,
+ ) -> bool:
+ 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
+
+ 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
+
+ try:
+ headers = {"Authorization": f"Bearer {self.config.bot_token}"}
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ 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
+
+ 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
+
+ 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:
+ logger.warning(
+ f"File exceeds max size during download, aborting: {file_info.get('name')}"
+ )
+ return False
+ file_obj.write(chunk)
+ return True
+
+ except asyncio.TimeoutError:
+ logger.error(f"Timeout downloading file: {file_info.get('name')}")
+ return False
+ except Exception as e:
+ logger.error(f"Error downloading Slack file: {e}")
+ return False
+
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
new file mode 100644
index 000000000..ab5a94a05
--- /dev/null
+++ b/tests/test_message_handler_attachments.py
@@ -0,0 +1,159 @@
+import importlib.util
+import sys
+import tempfile
+import types
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from modules.im import MessageContext
+from modules.im.base import FileAttachment
+
+
+def _load_message_handler_class():
+ with patch.dict(sys.modules, {}, clear=False):
+ agents_module = types.ModuleType("modules.agents")
+ setattr(agents_module, "AgentRequest", type("AgentRequest", (), {}))
+ sys.modules["modules.agents"] = agents_module
+
+ core_pkg = types.ModuleType("core")
+ core_pkg.__path__ = [str(ROOT / "core")]
+ sys.modules["core"] = core_pkg
+
+ handlers_pkg = types.ModuleType("core.handlers")
+ handlers_pkg.__path__ = [str(ROOT / "core" / "handlers")]
+ sys.modules["core.handlers"] = handlers_pkg
+
+ base_name = "core.handlers.base"
+ base_spec = importlib.util.spec_from_file_location(base_name, ROOT / "core" / "handlers" / "base.py")
+ assert base_spec is not None
+ assert base_spec.loader is not None
+ base_module = importlib.util.module_from_spec(base_spec)
+ sys.modules[base_name] = base_module
+ base_spec.loader.exec_module(base_module)
+
+ module_name = "core.handlers.message_handler"
+ spec = importlib.util.spec_from_file_location(module_name, ROOT / "core" / "handlers" / "message_handler.py")
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ return module.MessageHandler
+
+
+MessageHandler = _load_message_handler_class()
+
+
+class _StubIMClient:
+ def __init__(self, download_result=None, stream_result=False):
+ self.download_result = download_result
+ self.stream_result = stream_result
+ self.download_calls = []
+ self.stream_calls = []
+ self.sent_messages = []
+ self.formatter = None
+
+ def should_use_thread_for_reply(self):
+ return bool(False)
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ self.sent_messages.append((context.channel_id, context.thread_id, text, parse_mode, reply_to))
+ return "M1"
+
+ async def download_file(self, file_info):
+ self.download_calls.append(file_info)
+ return self.download_result
+
+ 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
+ Path(target_path).write_bytes(self.download_result or b"")
+ return True
+
+
+class _StubIMClientNoStream:
+ def __init__(self, download_result=None):
+ self.download_result = download_result
+ self.download_calls = []
+ self.stream_calls = []
+ self.sent_messages = []
+ self.formatter = None
+
+ def should_use_thread_for_reply(self):
+ return bool(False)
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ self.sent_messages.append((context.channel_id, context.thread_id, text, parse_mode, reply_to))
+ return "M1"
+
+ async def download_file(self, file_info):
+ self.download_calls.append(file_info)
+ return self.download_result
+
+
+class _StubController:
+ def __init__(self, im_client):
+ self.config = type("Config", (), {"platform": "slack", "language": "en"})()
+ self.im_client = im_client
+ self.settings_manager = type("Settings", (), {})()
+ self.session_manager = object()
+ self.receiver_tasks = {}
+
+
+class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
+ async def test_process_file_attachments_streams_large_files_without_app_limit(self):
+ im_client = _StubIMClient(download_result=b"%PDF-1.7\n", stream_result=True)
+ handler = MessageHandler(_StubController(im_client))
+ attachment = FileAttachment(
+ name="large.pdf",
+ mimetype="application/pdf",
+ url="https://example.test/large.pdf",
+ size=150 * 1024 * 1024,
+ )
+ context = MessageContext(user_id="U1", channel_id="C1", thread_id="T1", files=[attachment])
+
+ 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")
+
+ self.assertIsNotNone(processed)
+ assert processed is not None
+ self.assertEqual(len(processed), 1)
+ self.assertEqual(im_client.sent_messages, [])
+ self.assertEqual(im_client.download_calls, [])
+ self.assertEqual(len(im_client.stream_calls), 1)
+ self.assertIsNone(im_client.stream_calls[0][2])
+ self.assertEqual(processed[0].size, len(b"%PDF-1.7\n"))
+
+ async def test_process_file_attachments_falls_back_to_in_memory_download_when_streaming_unavailable(self):
+ im_client = _StubIMClientNoStream(download_result=b"%PDF-1.7\n")
+ handler = MessageHandler(_StubController(im_client))
+ attachment = FileAttachment(
+ name="supported.pdf",
+ mimetype="application/pdf",
+ url="https://example.test/supported.pdf",
+ size=50 * 1024 * 1024,
+ )
+ context = MessageContext(user_id="U1", channel_id="C1", files=[attachment])
+
+ 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")
+
+ self.assertIsNotNone(processed)
+ assert processed is not None
+ self.assertEqual(len(processed), 1)
+ 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)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_opencode_question_handler.py b/tests/test_opencode_question_handler.py
new file mode 100644
index 000000000..b0c08b442
--- /dev/null
+++ b/tests/test_opencode_question_handler.py
@@ -0,0 +1,189 @@
+import asyncio
+import importlib.util
+from pathlib import Path
+import sys
+import types
+import unittest
+
+from modules.im import MessageContext
+from vibe.i18n import t as i18n_t
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _ensure_package(name: str, path: Path) -> None:
+ module = sys.modules.get(name)
+ if module is None:
+ module = types.ModuleType(name)
+ module.__path__ = [str(path)]
+ sys.modules[name] = module
+
+
+def _load_module(name: str, relative_path: str):
+ module = sys.modules.get(name)
+ if module is not None:
+ return module
+
+ spec = importlib.util.spec_from_file_location(name, REPO_ROOT / relative_path)
+ if spec is None or spec.loader is None:
+ raise RuntimeError(f"Failed to load module {name} from {relative_path}")
+
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+_ensure_package("modules", REPO_ROOT / "modules")
+_ensure_package("modules.agents", REPO_ROOT / "modules/agents")
+_ensure_package("modules.agents.opencode", REPO_ROOT / "modules/agents/opencode")
+_ensure_package("modules.im", REPO_ROOT / "modules/im")
+
+server_stub = types.ModuleType("modules.agents.opencode.server")
+setattr(server_stub, "OpenCodeServerManager", type("OpenCodeServerManager", (), {}))
+sys.modules.setdefault("modules.agents.opencode.server", server_stub)
+
+base_module = _load_module("modules.agents.base", "modules/agents/base.py")
+question_ui_module = _load_module("modules.agents.question_ui", "modules/agents/question_ui.py")
+_load_module("modules.agents.opencode.types", "modules/agents/opencode/types.py")
+question_handler_module = _load_module(
+ "modules.agents.opencode.question_handler",
+ "modules/agents/opencode/question_handler.py",
+)
+
+AgentRequest = base_module.AgentRequest
+QuestionUIHandler = question_ui_module.QuestionUIHandler
+PendingQuestion = question_ui_module.PendingQuestion
+OpenCodeQuestionHandler = question_handler_module.OpenCodeQuestionHandler
+
+
+class _StubIMClient:
+ def __init__(self):
+ self.sent_messages = []
+ self.removed_keyboards = []
+ self.reactions = []
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ message_id = f"M{len(self.sent_messages) + 1}"
+ self.sent_messages.append((context.channel_id, context.thread_id, text, parse_mode, reply_to))
+ return message_id
+
+ async def remove_inline_keyboard(self, context, message_id, text=None, parse_mode=None):
+ self.removed_keyboards.append((context.channel_id, context.thread_id, message_id, text, parse_mode))
+ return True
+
+ async def add_reaction(self, context, message_id, emoji):
+ self.reactions.append((context.channel_id, context.thread_id, message_id, emoji))
+ return True
+
+
+class _StubConfig:
+ def __init__(self, language="zh"):
+ self.language = language
+
+
+class _StubController:
+ def __init__(self, lang="zh"):
+ self.config = _StubConfig(language=lang)
+ self.emitted_messages = []
+ self.cleared_consolidated_ids = []
+
+ def _t(self, key, **kwargs):
+ return i18n_t(key, self.config.language, **kwargs)
+
+ async def emit_agent_message(self, context, message_type, text, parse_mode=None):
+ self.emitted_messages.append((context.channel_id, message_type, text, parse_mode))
+
+ async def clear_consolidated_message_id(self, context, trigger_message_id=None):
+ self.cleared_consolidated_ids.append((context.channel_id, context.thread_id, trigger_message_id))
+
+
+class _StubServer:
+ def __init__(self, ok=True):
+ self.ok = ok
+ self.reply_calls = []
+
+ async def reply_question(self, question_id, directory, answers_payload):
+ self.reply_calls.append((question_id, directory, answers_payload))
+ return self.ok
+
+
+def _build_request(message: str) -> AgentRequest:
+ return AgentRequest(
+ context=MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ thread_id="T123",
+ message_id="USER1",
+ ),
+ message=message,
+ working_path="/tmp/work",
+ base_session_id="base-session",
+ composite_session_id="base-session:/tmp/work",
+ settings_key="C123",
+ )
+
+
+class OpenCodeQuestionHandlerTests(unittest.IsolatedAsyncioTestCase):
+ async def test_process_question_answer_sends_visible_reply_echo(self):
+ controller = _StubController(lang="zh")
+ im_client = _StubIMClient()
+ handler = OpenCodeQuestionHandler(controller, im_client, object())
+ server = _StubServer(ok=True)
+ request = _build_request("opencode_question:choose:2")
+ handler._question_answer_events[request.base_session_id] = asyncio.Event()
+
+ pending = {
+ "session_id": "oc-session",
+ "directory": "/tmp/work",
+ "question_id": "q-1",
+ "option_labels": ["Alpha", "Beta"],
+ "prompt_message_id": "PROMPT1",
+ "prompt_text": "Pick an option",
+ "trigger_message_id": "TRIGGER1",
+ }
+
+ await handler.process_question_answer(request, pending, server)
+
+ self.assertEqual(server.reply_calls, [("q-1", "/tmp/work", [["Beta"]])])
+ self.assertEqual(
+ im_client.removed_keyboards,
+ [("C123", "T123", "PROMPT1", "Pick an option", "markdown")],
+ )
+ self.assertEqual(im_client.sent_messages[0][2], "回复:Beta")
+ self.assertEqual(controller.cleared_consolidated_ids, [("C123", "T123", "TRIGGER1")])
+ self.assertTrue(handler._question_answer_events[request.base_session_id].is_set())
+
+
+class QuestionUIHandlerTests(unittest.IsolatedAsyncioTestCase):
+ async def test_send_answer_receipt_formats_multi_question_answers(self):
+ controller = _StubController(lang="en")
+ im_client = _StubIMClient()
+ ui_handler = QuestionUIHandler(controller, im_client, object(), "opencode_question")
+ request = _build_request("unused")
+
+ await ui_handler.send_answer_receipt(request, [["Alpha", "Beta"], ["Gamma"]])
+
+ self.assertEqual(im_client.sent_messages[0][2], "Reply: \nQ1: Alpha, Beta\nQ2: Gamma")
+
+ async def test_update_prompt_after_answer_does_not_append_selection_text(self):
+ controller = _StubController(lang="zh")
+ im_client = _StubIMClient()
+ ui_handler = QuestionUIHandler(controller, im_client, object(), "opencode_question")
+ request = _build_request("freeform answer")
+ pending = PendingQuestion(
+ questions=[],
+ prompt_text="请选择一个答案",
+ option_labels=[],
+ base_session_id=request.base_session_id,
+ thread_id=request.context.thread_id,
+ prompt_message_id="PROMPT2",
+ )
+
+ await ui_handler.update_prompt_after_answer(request, pending)
+
+ self.assertEqual(
+ im_client.removed_keyboards,
+ [("C123", "T123", "PROMPT2", "请选择一个答案", "markdown")],
+ )
+ self.assertNotIn("已选择", im_client.removed_keyboards[0][3])