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(slack): handle connect mentions and thin file events

cyhf01a42db59bb
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 3f2396b30..1a45f79d0 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -750,16 +750,20 @@ class MessageHandler(BaseHandler):
try:
im_client = self._get_im_client(context)
- # Download the file content
- if hasattr(im_client, "download_file") and attachment.url:
+ # Download the file content. Some platforms receive a thin
+ # attachment event first and resolve the actual URL from
+ # platform metadata such as a Slack file id.
+ can_download = hasattr(im_client, "download_file_to_path") or hasattr(im_client, "download_file")
+ if can_download:
# Platform-agnostic download info dict
file_info = {
"url": attachment.url,
- "url_private_download": attachment.url, # Slack compat
"name": attachment.name,
"size": attachment.size,
"platform": context.platform,
}
+ if attachment.url:
+ file_info["url_private_download"] = attachment.url # Slack compat
attachment_data = getattr(attachment, "__dict__", {})
for key, value in attachment_data.items():
if key in {"name", "mimetype", "url", "content", "local_path", "size"}:
diff --git a/modules/im/slack.py b/modules/im/slack.py
index cd307c3c3..fe9ec5308 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -74,6 +74,7 @@ class SlackBot(BaseIMClient):
self._controller = None
self._recent_event_ids: Dict[str, float] = {}
self._user_info_cache: Dict[str, Dict[str, Any]] = {}
+ self._channel_info_cache: Dict[str, Dict[str, Any]] = {}
self._bot_user_id: Optional[str] = None
self._stop_event: Optional[asyncio.Event] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
@@ -332,6 +333,35 @@ class SlackBot(BaseIMClient):
return True
return self._channel_looks_like_dm(context.channel_id)
+ async def _get_channel_info_cached(self, channel_id: Optional[str]) -> Dict[str, Any]:
+ if not channel_id:
+ return {}
+ cached = self._channel_info_cache.get(channel_id)
+ if cached is not None:
+ return cached
+
+ self._ensure_clients()
+ conversations_info = getattr(self.web_client, "conversations_info", None)
+ if not callable(conversations_info):
+ return {}
+
+ try:
+ response = await conversations_info(channel=channel_id)
+ channel = response.get("channel") if isinstance(response, dict) else None
+ if isinstance(channel, dict):
+ self._channel_info_cache[channel_id] = channel
+ return channel
+ except SlackApiError as err:
+ error_code = getattr(err, "response", {}).get("error") if getattr(err, "response", None) else None
+ logger.debug("Failed to fetch Slack channel info for %s: %s", channel_id, error_code or err)
+ except Exception as err:
+ logger.debug("Failed to fetch Slack channel info for %s: %s", channel_id, err)
+ return {}
+
+ async def _is_slack_connect_channel(self, channel_id: Optional[str]) -> bool:
+ channel = await self._get_channel_info_cached(channel_id)
+ return bool(channel.get("is_ext_shared"))
+
async def _open_dm_channel(self, user_id: str) -> Optional[str]:
self._ensure_clients()
resp = await self.web_client.conversations_open(users=[user_id])
@@ -582,7 +612,8 @@ class SlackBot(BaseIMClient):
Returns:
File content as bytes, or None if download fails
"""
- url = file_info.get("url_private_download") or file_info.get("url_private")
+ file_info = await self._resolve_downloadable_file_info(file_info)
+ url = file_info.get("url_private_download") or file_info.get("url_private") or file_info.get("url")
if not url:
logger.warning(f"No download URL for file: {file_info.get('name')}")
return None
@@ -634,7 +665,8 @@ class SlackBot(BaseIMClient):
max_bytes: Optional[int] = None,
timeout_seconds: int = 30,
) -> FileDownloadResult:
- url = file_info.get("url_private_download") or file_info.get("url_private")
+ file_info = await self._resolve_downloadable_file_info(file_info)
+ url = file_info.get("url_private_download") or file_info.get("url_private") or file_info.get("url")
if not url:
logger.warning(f"No download URL for file: {file_info.get('name')}")
return FileDownloadResult(False, "No download URL available")
@@ -679,6 +711,30 @@ class SlackBot(BaseIMClient):
logger.error(f"Error downloading Slack file: {e}")
return FileDownloadResult(False, f"Download error: {e}")
+ async def _resolve_downloadable_file_info(self, file_info: Dict[str, Any]) -> Dict[str, Any]:
+ """Best-effort hydrate a thin Slack file event before download."""
+ if file_info.get("url_private_download") or file_info.get("url_private") or file_info.get("url"):
+ return file_info
+
+ file_id = file_info.get("slack_file_id") or file_info.get("id") or file_info.get("file_id")
+ if not file_id or not self.web_client:
+ return file_info
+
+ try:
+ response = await self.web_client.files_info(file=file_id)
+ slack_file = response.get("file") if isinstance(response, dict) else None
+ if not isinstance(slack_file, dict) or not slack_file:
+ return file_info
+ resolved = {**file_info, **slack_file}
+ resolved.setdefault("slack_file_id", file_id)
+ return resolved
+ except SlackApiError as err:
+ error_code = getattr(err, "response", {}).get("error") if getattr(err, "response", None) else None
+ logger.warning("Failed to resolve Slack file info for %s: %s", file_id, error_code or err)
+ except Exception as err:
+ logger.warning("Failed to resolve Slack file info for %s: %s", file_id, err)
+ return file_info
+
def _extract_file_attachments(self, files: List[Dict[str, Any]]) -> List[FileAttachment]:
"""Convert Slack file objects to FileAttachment list.
@@ -690,12 +746,16 @@ class SlackBot(BaseIMClient):
"""
attachments = []
for f in files:
+ file_id = f.get("id")
+ name = f.get("name") or f.get("title") or file_id or "slack-file"
attachment = FileAttachment(
- name=f.get("name", "unknown"),
+ name=name,
mimetype=f.get("mimetype", "application/octet-stream"),
url=f.get("url_private_download") or f.get("url_private"),
size=f.get("size"),
)
+ if file_id:
+ attachment.__dict__["slack_file_id"] = file_id
attachments.append(attachment)
return attachments
@@ -1309,10 +1369,15 @@ class SlackBot(BaseIMClient):
bot_user_id = await self._get_bot_user_id(payload)
has_bot_mention = self._has_specific_mention(text, bot_user_id)
cleaned_text = self._strip_specific_mention(text, bot_user_id)
+ handled_bot_mention_in_message_event = False
if has_bot_mention:
if is_dm:
text = cleaned_text
had_dm_mention_only = not text
+ elif await self._is_slack_connect_channel(channel_id):
+ text = cleaned_text
+ handled_bot_mention_in_message_event = True
+ logger.info("Processing Slack Connect message event with bot mention: '%s'", event.get("text"))
else:
logger.info(f"Skipping message event with bot mention: '{text}'")
return
@@ -1346,12 +1411,14 @@ class SlackBot(BaseIMClient):
if effective_require_mention and not is_dm:
# In channel main thread: require mention (silently ignore)
- if not is_thread_reply:
+ if handled_bot_mention_in_message_event:
+ logger.debug("Processing message event because Slack Connect bot mention was already detected")
+ elif not is_thread_reply:
logger.debug(f"Ignoring non-mention message in channel: '{text}'")
return
# In thread: check if bot is active in this thread
- if is_thread_reply:
+ elif is_thread_reply:
thread_ts = event.get("thread_ts")
# If we have settings_manager, check if thread is active
if self.settings_manager:
@@ -1410,6 +1477,11 @@ class SlackBot(BaseIMClient):
files=file_attachments,
)
+ if handled_bot_mention_in_message_event and self.settings_manager and thread_id:
+ if self.sessions:
+ self.sessions.mark_thread_active(user_id, channel_id, thread_id)
+ logger.info(f"Marked thread {thread_id} as active due to Slack Connect @mention")
+
# Handle slash commands in regular messages (before appending shared content)
# Use only the user's original text for command detection
if await self.dispatch_text_command(
diff --git a/tests/test_message_handler_attachments.py b/tests/test_message_handler_attachments.py
index c134b4e85..6723b2b84 100644
--- a/tests/test_message_handler_attachments.py
+++ b/tests/test_message_handler_attachments.py
@@ -16,8 +16,13 @@ from modules.im.base import FileAttachment, FileDownloadResult
def _load_message_handler_class():
with patch.dict(sys.modules, {}, clear=False):
agents_module = types.ModuleType("modules.agents")
- setattr(agents_module, "AgentRequest", type("AgentRequest", (), {}))
+ agents_module.__path__ = []
+ agent_request = type("AgentRequest", (), {})
+ setattr(agents_module, "AgentRequest", agent_request)
sys.modules["modules.agents"] = agents_module
+ agents_base_module = types.ModuleType("modules.agents.base")
+ setattr(agents_base_module, "AgentRequest", agent_request)
+ sys.modules["modules.agents.base"] = agents_base_module
core_pkg = types.ModuleType("core")
core_pkg.__path__ = [str(ROOT / "core")]
@@ -209,6 +214,29 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(file_info["cdn_info"]["encrypt_query_param"], "encrypted-param")
self.assertEqual(file_info["wechat_item"]["aeskey"], "00112233445566778899aabbccddeeff")
+ async def test_process_file_attachments_allows_platform_download_without_url(self):
+ im_client = _StubIMClient(download_result=b"%PDF-1.7\n", stream_result=True)
+ handler = MessageHandler(_StubController(im_client))
+ attachment = FileAttachment(
+ name="F123",
+ mimetype="application/pdf",
+ url=None,
+ size=1024,
+ )
+ attachment.__dict__["slack_file_id"] = "F123"
+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack", files=[attachment])
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ with patch("config.paths.get_attachments_dir", return_value=Path(tmpdir)):
+ processed, errors = await handler._process_file_attachments(context, "/tmp/work")
+
+ self.assertIsNotNone(processed)
+ self.assertEqual(errors, [])
+ self.assertEqual(len(im_client.stream_calls), 1)
+ file_info = im_client.stream_calls[0][0]
+ self.assertIsNone(file_info["url"])
+ self.assertEqual(file_info["slack_file_id"], "F123")
+
def test_append_attachment_errors_uses_error_text_without_file_paths(self):
handler = MessageHandler(_StubController(_StubIMClient()))
diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.py
index 4e659e249..e884bf7b4 100644
--- a/tests/test_slack_app_mention_empty.py
+++ b/tests/test_slack_app_mention_empty.py
@@ -137,5 +137,37 @@ class SlackAppMentionEmptyTests(unittest.IsolatedAsyncioTestCase):
slack.sessions.mark_thread_active.assert_not_called()
+class SlackFileAttachmentTests(unittest.IsolatedAsyncioTestCase):
+ async def test_extract_file_attachments_preserves_file_id_when_url_missing(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+
+ attachments = slack._extract_file_attachments([{"id": "F123", "mimetype": "application/pdf"}])
+
+ self.assertEqual(len(attachments), 1)
+ self.assertEqual(attachments[0].name, "F123")
+ self.assertIsNone(attachments[0].url)
+ self.assertEqual(attachments[0].__dict__["slack_file_id"], "F123")
+
+ async def test_resolve_downloadable_file_info_hydrates_thin_file_event(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ slack.web_client = SimpleNamespace(
+ files_info=AsyncMock(
+ return_value={
+ "file": {
+ "id": "F123",
+ "name": "report.pdf",
+ "url_private_download": "https://files.slack.test/report.pdf",
+ }
+ }
+ )
+ )
+
+ resolved = await slack._resolve_downloadable_file_info({"slack_file_id": "F123", "name": "F123"})
+
+ self.assertEqual(resolved["name"], "report.pdf")
+ self.assertEqual(resolved["url_private_download"], "https://files.slack.test/report.pdf")
+ slack.web_client.files_info.assert_awaited_once_with(file="F123")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 122d9ce66..5317845f9 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -783,6 +783,80 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(received["called"])
+ async def test_slack_connect_channel_mention_falls_back_to_message_event(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", require_mention=True))
+ received = {}
+
+ class _WebClient:
+ async def conversations_info(self, channel):
+ return {"channel": {"id": channel, "is_ext_shared": True}}
+
+ async def _on_message(context, text):
+ received["text"] = text
+ received["thread_id"] = context.thread_id
+
+ slack.web_client = _WebClient()
+ slack.register_callbacks(on_message=_on_message)
+
+ payload = {
+ "event_id": "evt-slack-connect-mention",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "message",
+ "channel": "C_CONNECT",
+ "user": "U123",
+ "text": "<@U_BOT> please help",
+ "ts": "1710000000.000350",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertEqual(received, {"text": "please help", "thread_id": "1710000000.000350"})
+
+ async def test_slack_connect_channel_mention_marks_thread_active(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test", require_mention=True))
+ marked = []
+
+ class _WebClient:
+ async def conversations_info(self, channel):
+ return {"channel": {"id": channel, "is_ext_shared": True}}
+
+ class _Sessions:
+ def mark_thread_active(self, user_id, channel_id, thread_id):
+ marked.append((user_id, channel_id, thread_id))
+
+ class _SettingsManager:
+ sessions = _Sessions()
+
+ def get_require_mention(self, _channel_id, global_default=False):
+ return global_default
+
+ async def _on_message(_context, _text):
+ return None
+
+ slack.web_client = _WebClient()
+ slack.set_settings_manager(_SettingsManager())
+ slack.register_callbacks(on_message=_on_message)
+
+ payload = {
+ "event_id": "evt-slack-connect-mark-thread",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "message",
+ "channel": "C_CONNECT",
+ "user": "U123",
+ "text": "<@U_BOT> please help",
+ "ts": "1710000000.000360",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertEqual(marked, [("U123", "C_CONNECT", "1710000000.000360")])
+
async def test_dm_preserves_non_bot_mentions(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
received = {}