Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: Support Slack attachments in agent context (#14934)

Rohit Malhotra8f28477d46e3
diff --git a/enterprise/integrations/slack/slack_attachments.py b/enterprise/integrations/slack/slack_attachments.py
new file mode 100644
index 0000000000..826285f752
--- /dev/null
+++ b/enterprise/integrations/slack/slack_attachments.py
@@ -0,0 +1,310 @@
+"""Helpers for reading Slack file attachments for agent context."""
+
+import base64
+import mimetypes
+from dataclasses import dataclass, field
+from io import BytesIO
+from typing import Any
+
+import httpx
+from integrations.slack.slack_errors import SlackError, SlackErrorCode
+from slack_sdk import WebClient
+from slack_sdk.errors import SlackApiError
+
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+MAX_SLACK_ATTACHMENTS_PER_MESSAGE = 5
+MAX_SLACK_ATTACHMENT_BYTES = 5 * 1024 * 1024
+MAX_ATTACHMENT_TEXT_CHARS = 50_000
+
+TEXT_FILE_EXTENSIONS = {
+ '.bash',
+ '.cfg',
+ '.conf',
+ '.config',
+ '.css',
+ '.csv',
+ '.env',
+ '.go',
+ '.html',
+ '.ini',
+ '.java',
+ '.js',
+ '.json',
+ '.jsx',
+ '.log',
+ '.md',
+ '.properties',
+ '.py',
+ '.rb',
+ '.rs',
+ '.sh',
+ '.sql',
+ '.toml',
+ '.ts',
+ '.tsx',
+ '.txt',
+ '.xml',
+ '.yaml',
+ '.yml',
+}
+
+PDF_MIME_TYPES = {'application/pdf'}
+DOCX_MIME_TYPES = {
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+}
+
+
+@dataclass
+class SlackAttachmentContent:
+ descriptions: list[str] = field(default_factory=list)
+ image_urls: list[str] = field(default_factory=list)
+
+
+def collect_message_attachment_content(
+ slack_client: WebClient,
+ bot_access_token: str,
+ message: dict[str, Any],
+) -> SlackAttachmentContent:
+ """Download and convert Slack file attachments attached to a message."""
+ files = message.get('files') or []
+ content = SlackAttachmentContent()
+ if not isinstance(files, list) or not files:
+ return content
+
+ for file_info in files[:MAX_SLACK_ATTACHMENTS_PER_MESSAGE]:
+ if not isinstance(file_info, dict):
+ continue
+ try:
+ attachment = _collect_file_attachment_content(
+ slack_client, bot_access_token, file_info
+ )
+ except SlackError:
+ raise
+ except Exception as e:
+ logger.warning(
+ 'slack_attachment_collect_failed',
+ extra={
+ 'file_id': file_info.get('id'),
+ 'file_title': _attachment_title(file_info),
+ 'error': str(e),
+ },
+ )
+ attachment = SlackAttachmentContent(
+ descriptions=[
+ f'- {_attachment_title(file_info)} could not be read due to an error.'
+ ]
+ )
+ content.descriptions.extend(attachment.descriptions)
+ content.image_urls.extend(attachment.image_urls)
+
+ skipped_count = len(files) - MAX_SLACK_ATTACHMENTS_PER_MESSAGE
+ if skipped_count > 0:
+ content.descriptions.append(
+ f'- {skipped_count} additional Slack attachment(s) were skipped because '
+ f'only {MAX_SLACK_ATTACHMENTS_PER_MESSAGE} attachments per message are read.'
+ )
+
+ return content
+
+
+def _collect_file_attachment_content(
+ slack_client: WebClient,
+ bot_access_token: str,
+ file_info: dict[str, Any],
+) -> SlackAttachmentContent:
+ file_info = _hydrate_file_info(slack_client, file_info)
+ title = _attachment_title(file_info)
+ mimetype = _attachment_mimetype(file_info, title)
+ size = _safe_int(file_info.get('size'))
+ size_label = _format_size(size)
+
+ if size and size > MAX_SLACK_ATTACHMENT_BYTES:
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype or "unknown type"}, {size_label}) was not '
+ 'read because it exceeds the Slack attachment size limit.'
+ ]
+ )
+
+ download_url = file_info.get('url_private_download') or file_info.get('url_private')
+ if not download_url:
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype or "unknown type"}, {size_label}) could not '
+ 'be downloaded from Slack.'
+ ]
+ )
+
+ file_bytes = _download_slack_file(bot_access_token, download_url)
+ if len(file_bytes) > MAX_SLACK_ATTACHMENT_BYTES:
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype or "unknown type"}, '
+ f'{_format_size(len(file_bytes))}) was not read because it exceeds '
+ 'the Slack attachment size limit.'
+ ]
+ )
+
+ if mimetype.startswith('image/'):
+ data_url = _to_data_url(mimetype, file_bytes)
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype}, {_format_size(len(file_bytes))}) is included '
+ 'as image content.'
+ ],
+ image_urls=[data_url],
+ )
+
+ extracted_text = _extract_attachment_text(file_bytes, title, mimetype)
+ if extracted_text:
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype or "unknown type"}, '
+ f'{_format_size(len(file_bytes))}) content:\n{_truncate_text(extracted_text)}'
+ ]
+ )
+
+ return SlackAttachmentContent(
+ descriptions=[
+ f'- {title} ({mimetype or "unknown type"}, {_format_size(len(file_bytes))}) '
+ 'was downloaded from Slack, but this file type is not currently readable '
+ 'as text or image context.'
+ ]
+ )
+
+
+def _hydrate_file_info(
+ slack_client: WebClient, file_info: dict[str, Any]
+) -> dict[str, Any]:
+ if file_info.get('url_private') or file_info.get('url_private_download'):
+ return file_info
+
+ file_id = file_info.get('id')
+ if not file_id:
+ return file_info
+
+ try:
+ response = slack_client.files_info(file=file_id)
+ except SlackApiError as e:
+ if e.response.get('error') == 'missing_scope':
+ raise SlackError(SlackErrorCode.MISSING_SLACK_SCOPES) from e
+ raise
+
+ detailed_file = response.get('file') or {}
+ return {**file_info, **detailed_file}
+
+
+def _download_slack_file(bot_access_token: str, url: str) -> bytes:
+ try:
+ with httpx.Client(timeout=30.0, follow_redirects=True) as client:
+ response = client.get(
+ url,
+ headers={'Authorization': f'Bearer {bot_access_token}'},
+ )
+ response.raise_for_status()
+ return response.content
+ except httpx.HTTPStatusError as e:
+ if e.response.status_code in {401, 403}:
+ raise SlackError(SlackErrorCode.MISSING_SLACK_SCOPES) from e
+ raise
+
+
+def _extract_attachment_text(
+ file_bytes: bytes,
+ title: str,
+ mimetype: str,
+) -> str | None:
+ if _is_text_attachment(title, mimetype):
+ return file_bytes.decode('utf-8', errors='replace').strip()
+ if mimetype in PDF_MIME_TYPES:
+ return _extract_pdf_text(file_bytes)
+ if mimetype in DOCX_MIME_TYPES:
+ return _extract_docx_text(file_bytes)
+ return None
+
+
+def _extract_pdf_text(file_bytes: bytes) -> str | None:
+ try:
+ from pypdf import PdfReader
+
+ reader = PdfReader(BytesIO(file_bytes))
+ text = '\n\n'.join(page.extract_text() or '' for page in reader.pages)
+ return text.strip() or None
+ except Exception as e:
+ logger.warning('slack_attachment_pdf_extract_failed', extra={'error': str(e)})
+ return None
+
+
+def _extract_docx_text(file_bytes: bytes) -> str | None:
+ try:
+ from docx import Document
+
+ document = Document(BytesIO(file_bytes))
+ text = '\n'.join(paragraph.text for paragraph in document.paragraphs)
+ return text.strip() or None
+ except Exception as e:
+ logger.warning('slack_attachment_docx_extract_failed', extra={'error': str(e)})
+ return None
+
+
+def _is_text_attachment(title: str, mimetype: str) -> bool:
+ if mimetype.startswith('text/'):
+ return True
+ extension = _attachment_extension(title)
+ return extension in TEXT_FILE_EXTENSIONS
+
+
+def _to_data_url(mimetype: str, file_bytes: bytes) -> str:
+ encoded = base64.b64encode(file_bytes).decode('ascii')
+ return f'data:{mimetype};base64,{encoded}'
+
+
+def _truncate_text(text: str) -> str:
+ if len(text) <= MAX_ATTACHMENT_TEXT_CHARS:
+ return text
+ return (
+ text[:MAX_ATTACHMENT_TEXT_CHARS]
+ + f'\n\n[Slack attachment text truncated after {MAX_ATTACHMENT_TEXT_CHARS} characters]'
+ )
+
+
+def _attachment_title(file_info: dict[str, Any]) -> str:
+ return str(
+ file_info.get('title')
+ or file_info.get('name')
+ or file_info.get('id')
+ or 'Slack attachment'
+ )
+
+
+def _attachment_mimetype(file_info: dict[str, Any], title: str) -> str:
+ mimetype = file_info.get('mimetype')
+ if isinstance(mimetype, str) and mimetype:
+ return mimetype
+ guessed_mimetype, _ = mimetypes.guess_type(title)
+ return guessed_mimetype or ''
+
+
+def _attachment_extension(title: str) -> str:
+ _, _, extension = title.rpartition('.')
+ if not extension or extension == title:
+ return ''
+ return f'.{extension.lower()}'
+
+
+def _safe_int(value: Any) -> int | None:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _format_size(size: int | None) -> str:
+ if size is None:
+ return 'unknown size'
+ if size < 1024:
+ return f'{size} bytes'
+ if size < 1024 * 1024:
+ return f'{size / 1024:.1f} KB'
+ return f'{size / (1024 * 1024):.1f} MB'
diff --git a/enterprise/integrations/slack/slack_manager.py b/enterprise/integrations/slack/slack_manager.py
index e2bc2e97ba..97bfc6d064 100644
--- a/enterprise/integrations/slack/slack_manager.py
+++ b/enterprise/integrations/slack/slack_manager.py
@@ -48,7 +48,16 @@ from openhands.app_server.utils.logger import openhands_logger as logger
authorize_url_generator = AuthorizeUrlGenerator(
client_id=SLACK_CLIENT_ID,
- scopes=['app_mentions:read', 'chat:write'],
+ scopes=[
+ 'app_mentions:read',
+ 'chat:write',
+ 'users:read',
+ 'files:read',
+ 'channels:history',
+ 'groups:history',
+ 'mpim:history',
+ 'im:history',
+ ],
user_scopes=['search:read'],
)
diff --git a/enterprise/integrations/slack/slack_view.py b/enterprise/integrations/slack/slack_view.py
index 73d0a2ce74..1a90a3a868 100644
--- a/enterprise/integrations/slack/slack_view.py
+++ b/enterprise/integrations/slack/slack_view.py
@@ -1,10 +1,11 @@
import asyncio
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from uuid import UUID, uuid4
from integrations.models import Message
from integrations.resolver_context import ResolverUserContext
from integrations.resolver_org_router import resolve_org_for_repo
+from integrations.slack.slack_attachments import collect_message_attachment_content
from integrations.slack.slack_errors import SlackError, SlackErrorCode
from integrations.slack.slack_types import (
SlackMessageView,
@@ -37,7 +38,7 @@ from openhands.app_server.user.specifiy_user_context import USER_CONTEXT_ATTR
from openhands.app_server.user_auth.user_auth import UserAuth
from openhands.app_server.utils.async_utils import GENERAL_TIMEOUT
from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.sdk import TextContent
+from openhands.sdk import ImageContent, TextContent
# =================================================
# SECTION: Slack view types
@@ -64,6 +65,7 @@ class SlackNewConversationView(SlackViewInterface):
send_summary_instruction: bool
conversation_id: str
team_id: str
+ attachment_image_urls: list[str] = field(default_factory=list, init=False)
def _get_initial_prompt(self, text: str, blocks: list[dict]):
bot_id = self._get_bot_id(blocks)
@@ -81,13 +83,32 @@ class SlackNewConversationView(SlackViewInterface):
return block['user_id']
return ''
+ def _process_attachment_content_for_message(self, message: dict) -> list[str]:
+ attachment_content = collect_message_attachment_content(
+ WebClient(token=self.bot_access_token),
+ self.bot_access_token,
+ message,
+ )
+ self.attachment_image_urls.extend(attachment_content.image_urls)
+ return attachment_content.descriptions
+
+ def _format_slack_message_context(self, message: dict) -> str:
+ return message.get('text') or ''
+
+ def _build_message_content(self, text: str) -> list[TextContent | ImageContent]:
+ content: list[TextContent | ImageContent] = [TextContent(text=text)]
+ if self.attachment_image_urls:
+ content.append(ImageContent(image_urls=self.attachment_image_urls))
+ return content
+
async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
- """Instructions passed when conversation is first initialized"""
+ """Return instructions passed when conversation is first initialized."""
user_info: SlackUser = self.slack_to_openhands_user
+ self.attachment_image_urls = []
messages = []
+ client = WebClient(token=self.bot_access_token)
if self.thread_ts:
- client = WebClient(token=self.bot_access_token)
try:
result = client.conversations_replies(
channel=self.channel_id,
@@ -104,7 +125,6 @@ class SlackNewConversationView(SlackViewInterface):
messages = result['messages']
else:
- client = WebClient(token=self.bot_access_token)
try:
result = client.conversations_history(
channel=self.channel_id,
@@ -129,17 +149,30 @@ class SlackNewConversationView(SlackViewInterface):
user_message = self._get_initial_prompt(
trigger_msg['text'], trigger_msg['blocks']
)
+ trigger_attachment_descriptions = self._process_attachment_content_for_message(
+ trigger_msg
+ )
+ if trigger_attachment_descriptions:
+ user_message = user_message or 'Please review the attached Slack file(s).'
+ user_message = (
+ f'{user_message}\n\nSlack attachments included with this message:\n'
+ + '\n'.join(trigger_attachment_descriptions)
+ )
conversation_instructions = ''
if len(messages) > 1:
messages.pop()
- text_messages = [m['text'] for m in messages if m.get('text')]
+ context_messages = [
+ formatted_message
+ for message in messages
+ if (formatted_message := self._format_slack_message_context(message))
+ ]
conversation_instructions_template = jinja_env.get_template(
'user_message_conversation_instructions.j2'
)
conversation_instructions = conversation_instructions_template.render(
- messages=text_messages,
+ messages=context_messages,
username=user_info.slack_display_name,
conversation_url=CONVERSATION_URL,
)
@@ -190,7 +223,7 @@ class SlackNewConversationView(SlackViewInterface):
)
async def create_or_update_conversation(self, jinja: Environment) -> str:
- """Only creates a new conversation"""
+ """Create a new conversation."""
self._verify_necessary_values_are_set()
provider_tokens = await self.saas_user_auth.get_provider_tokens()
@@ -223,7 +256,7 @@ class SlackNewConversationView(SlackViewInterface):
# Create the initial message request
initial_message = SendMessageRequest(
- role='user', content=[TextContent(text=user_instructions)]
+ role='user', content=self._build_message_content(user_instructions)
)
# Create the Slack V1 callback processor
@@ -291,6 +324,7 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
slack_conversation: SlackConversation
async def _get_instructions(self, jinja_env: Environment) -> tuple[str, str]:
+ self.attachment_image_urls = []
client = WebClient(token=self.bot_access_token)
try:
result = client.conversations_replies(
@@ -305,10 +339,19 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
raise SlackError(SlackErrorCode.MISSING_SLACK_SCOPES) from e
raise
- user_message = result['messages'][0]
+ slack_message = result['messages'][0]
user_message = self._get_initial_prompt(
- user_message['text'], user_message['blocks']
+ slack_message['text'], slack_message['blocks']
)
+ attachment_descriptions = self._process_attachment_content_for_message(
+ slack_message
+ )
+ if attachment_descriptions:
+ user_message = user_message or 'Please review the attached Slack file(s).'
+ user_message = (
+ f'{user_message}\n\nSlack attachments included with this message:\n'
+ + '\n'.join(attachment_descriptions)
+ )
return user_message, ''
@@ -378,7 +421,7 @@ class SlackUpdateExistingConversationView(SlackNewConversationView):
# 5. Create the message request
send_message_request = SendMessageRequest(
- role='user', content=[TextContent(text=user_msg)], run=True
+ role='user', content=self._build_message_content(user_msg), run=True
)
# 6. Send the message to the agent server
diff --git a/enterprise/server/routes/integration/slack.py b/enterprise/server/routes/integration/slack.py
index c483f1e4ce..61dc88e824 100644
--- a/enterprise/server/routes/integration/slack.py
+++ b/enterprise/server/routes/integration/slack.py
@@ -56,6 +56,7 @@ authorize_url_generator = AuthorizeUrlGenerator(
'app_mentions:read',
'chat:write',
'users:read',
+ 'files:read',
'channels:history',
'groups:history',
'mpim:history',
@@ -71,7 +72,7 @@ jwt_service_dependency = depends_jwt_service()
@slack_router.get('/install')
async def install(state: str = ''):
- """Forward into slack OAuth. (Most workflows can skip this and jump directly into slack authentication, so we skip OAuth state generation)"""
+ """Forward into Slack OAuth."""
url = authorize_url_generator.generate(state=state)
return RedirectResponse(url)
diff --git a/enterprise/tests/unit/integrations/slack/test_slack_attachments.py b/enterprise/tests/unit/integrations/slack/test_slack_attachments.py
new file mode 100644
index 0000000000..0712c7b672
--- /dev/null
+++ b/enterprise/tests/unit/integrations/slack/test_slack_attachments.py
@@ -0,0 +1,201 @@
+from unittest.mock import MagicMock, patch
+
+import httpx
+from integrations.slack.slack_attachments import (
+ MAX_SLACK_ATTACHMENT_BYTES,
+ MAX_SLACK_ATTACHMENTS_PER_MESSAGE,
+ collect_message_attachment_content,
+)
+from slack_sdk.errors import SlackApiError
+
+
+def test_slack_authorize_urls_request_files_read_scope():
+ from integrations.slack.slack_manager import authorize_url_generator
+ from server.routes.integration.slack import (
+ authorize_url_generator as install_authorize_url_generator,
+ )
+
+ assert 'files:read' in authorize_url_generator.scopes
+ assert 'files:read' in install_authorize_url_generator.scopes
+
+
+def _mock_download(mock_client_cls: MagicMock, content: bytes) -> MagicMock:
+ response = MagicMock()
+ response.content = content
+ response.raise_for_status = MagicMock()
+ http_client = mock_client_cls.return_value.__enter__.return_value
+ http_client.get.return_value = response
+ return http_client
+
+
+@patch('integrations.slack.slack_attachments.httpx.Client')
+def test_collect_message_attachment_content_includes_image_data_url(mock_client_cls):
+ http_client = _mock_download(mock_client_cls, b'image-bytes')
+ slack_client = MagicMock()
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {
+ 'files': [
+ {
+ 'title': 'screenshot.png',
+ 'mimetype': 'image/png',
+ 'size': 11,
+ 'url_private': 'https://files.slack.com/files-pri/screenshot.png',
+ }
+ ]
+ },
+ )
+
+ assert content.image_urls == ['data:image/png;base64,aW1hZ2UtYnl0ZXM=']
+ assert 'screenshot.png' in content.descriptions[0]
+ assert 'included as image content' in content.descriptions[0]
+ http_client.get.assert_called_once_with(
+ 'https://files.slack.com/files-pri/screenshot.png',
+ headers={'Authorization': 'Bearer xoxb-test-token'},
+ )
+
+
+@patch('integrations.slack.slack_attachments.httpx.Client')
+def test_collect_message_attachment_content_extracts_text_files(mock_client_cls):
+ _mock_download(mock_client_cls, b'apiVersion: v1\nkind: ConfigMap\n')
+ slack_client = MagicMock()
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {
+ 'files': [
+ {
+ 'title': 'config.yaml',
+ 'mimetype': 'application/x-yaml',
+ 'url_private': 'https://files.slack.com/files-pri/config.yaml',
+ }
+ ]
+ },
+ )
+
+ assert content.image_urls == []
+ assert 'config.yaml' in content.descriptions[0]
+ assert 'apiVersion: v1' in content.descriptions[0]
+ assert 'kind: ConfigMap' in content.descriptions[0]
+
+
+@patch('integrations.slack.slack_attachments.httpx.Client')
+def test_collect_message_attachment_content_hydrates_file_info(mock_client_cls):
+ _mock_download(mock_client_cls, b'log line')
+ slack_client = MagicMock()
+ slack_client.files_info.return_value = {
+ 'file': {
+ 'title': 'debug.log',
+ 'mimetype': 'text/plain',
+ 'url_private': 'https://files.slack.com/files-pri/debug.log',
+ }
+ }
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {'files': [{'id': 'F123'}]},
+ )
+
+ slack_client.files_info.assert_called_once_with(file='F123')
+ assert 'debug.log' in content.descriptions[0]
+ assert 'log line' in content.descriptions[0]
+
+
+@patch('integrations.slack.slack_attachments.httpx.Client')
+def test_collect_message_attachment_content_isolates_download_errors(mock_client_cls):
+ http_client = mock_client_cls.return_value.__enter__.return_value
+ http_client.get.side_effect = httpx.TimeoutException('timeout')
+ slack_client = MagicMock()
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {
+ 'files': [
+ {
+ 'title': 'flaky.png',
+ 'mimetype': 'image/png',
+ 'url_private': 'https://files.slack.com/files-pri/flaky.png',
+ }
+ ]
+ },
+ )
+
+ assert content.image_urls == []
+ assert content.descriptions == ['- flaky.png could not be read due to an error.']
+
+
+def test_collect_message_attachment_content_isolates_non_scope_slack_api_errors():
+ slack_client = MagicMock()
+ slack_client.files_info.side_effect = SlackApiError(
+ message='Slack unavailable', response={'error': 'internal_error'}
+ )
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {'files': [{'id': 'F123', 'title': 'metadata-only.txt'}]},
+ )
+
+ assert content.image_urls == []
+ assert content.descriptions == [
+ '- metadata-only.txt could not be read due to an error.'
+ ]
+
+
+@patch('integrations.slack.slack_attachments.httpx.Client')
+def test_collect_message_attachment_content_caps_attachments_per_message(
+ mock_client_cls,
+):
+ _mock_download(mock_client_cls, b'content')
+ slack_client = MagicMock()
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {
+ 'files': [
+ {
+ 'title': f'file-{index}.txt',
+ 'mimetype': 'text/plain',
+ 'url_private': f'https://files.slack.com/files-pri/file-{index}.txt',
+ }
+ for index in range(MAX_SLACK_ATTACHMENTS_PER_MESSAGE + 2)
+ ]
+ },
+ )
+
+ assert len(content.descriptions) == MAX_SLACK_ATTACHMENTS_PER_MESSAGE + 1
+ assert content.descriptions[-1] == (
+ '- 2 additional Slack attachment(s) were skipped because only '
+ f'{MAX_SLACK_ATTACHMENTS_PER_MESSAGE} attachments per message are read.'
+ )
+ http_client = mock_client_cls.return_value.__enter__.return_value
+ assert http_client.get.call_count == MAX_SLACK_ATTACHMENTS_PER_MESSAGE
+
+
+def test_collect_message_attachment_content_rejects_oversized_files_before_download():
+ slack_client = MagicMock()
+
+ content = collect_message_attachment_content(
+ slack_client,
+ 'xoxb-test-token',
+ {
+ 'files': [
+ {
+ 'title': 'huge.log',
+ 'mimetype': 'text/plain',
+ 'size': MAX_SLACK_ATTACHMENT_BYTES + 1,
+ 'url_private': 'https://files.slack.com/files-pri/huge.log',
+ }
+ ]
+ },
+ )
+
+ assert content.image_urls == []
+ assert 'huge.log' in content.descriptions[0]
+ assert 'exceeds the Slack attachment size limit' in content.descriptions[0]
diff --git a/enterprise/tests/unit/integrations/slack/test_slack_view.py b/enterprise/tests/unit/integrations/slack/test_slack_view.py
index f7612da14f..e4181f0eb6 100644
--- a/enterprise/tests/unit/integrations/slack/test_slack_view.py
+++ b/enterprise/tests/unit/integrations/slack/test_slack_view.py
@@ -102,6 +102,47 @@ def slack_update_conversation_view_v1(mock_slack_user, mock_user_auth):
# ---------------------------------------------------------------------------
+
+
+def test_build_message_content_includes_slack_attachment_images(
+ slack_new_conversation_view,
+):
+ slack_new_conversation_view.attachment_image_urls = [
+ 'data:image/png;base64,aW1hZ2UtYnl0ZXM='
+ ]
+
+ content = slack_new_conversation_view._build_message_content('hello')
+
+ assert len(content) == 2
+ assert content[0].type == 'text'
+ assert content[0].text == 'hello'
+ assert content[1].type == 'image'
+ assert content[1].image_urls == ['data:image/png;base64,aW1hZ2UtYnl0ZXM=']
+
+
+def test_format_slack_message_context_ignores_historical_attachments(
+ slack_new_conversation_view,
+):
+ with patch(
+ 'integrations.slack.slack_view.collect_message_attachment_content'
+ ) as mock_collect_attachment_content:
+ context = slack_new_conversation_view._format_slack_message_context(
+ {
+ 'text': 'Earlier thread message',
+ 'files': [
+ {
+ 'title': 'earlier-screenshot.png',
+ 'mimetype': 'image/png',
+ }
+ ],
+ }
+ )
+
+ assert context == 'Earlier thread message'
+ assert slack_new_conversation_view.attachment_image_urls == []
+ mock_collect_attachment_content.assert_not_called()
+
+
# Test: V1 Conversation Creation
# ---------------------------------------------------------------------------
diff --git a/openhands/app_server/integrations/templates/resolver/slack/user_message_conversation_instructions.j2 b/openhands/app_server/integrations/templates/resolver/slack/user_message_conversation_instructions.j2
index cef1453491..a1a4d1ae7f 100644
--- a/openhands/app_server/integrations/templates/resolver/slack/user_message_conversation_instructions.j2
+++ b/openhands/app_server/integrations/templates/resolver/slack/user_message_conversation_instructions.j2
@@ -1,5 +1,5 @@
When performing your task, make sure to reference the additional context if needed.
-These are a list of text messages attached in order of most recent.
+These are Slack text messages attached in order of most recent.
{% for message in messages %}
{{ message }}