Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(bridges): agents can send images relayed out via Slack + Mattermost (CHOO-1396) (#16)

Louis Amaudruz1505af0e8f50
diff --git a/connectors/claude-code-plugin/.claude-plugin/plugin.json b/connectors/claude-code-plugin/.claude-plugin/plugin.json
index 98e725330..f2eb9b019 100644
--- a/connectors/claude-code-plugin/.claude-plugin/plugin.json
+++ b/connectors/claude-code-plugin/.claude-plugin/plugin.json
@@ -1,5 +1,5 @@
{
"name": "switch-connector",
- "version": "0.1.13",
+ "version": "0.1.14",
"description": "Connect Claude Code to a Switch platform instance as a participating agent"
}
\ No newline at end of file
diff --git a/connectors/claude-code-plugin/channel/server.ts b/connectors/claude-code-plugin/channel/server.ts
index 7f09d9895..80fe9a98c 100644
--- a/connectors/claude-code-plugin/channel/server.ts
+++ b/connectors/claude-code-plugin/channel/server.ts
@@ -196,6 +196,7 @@ const mcp = new Server(
'If a message event has an image_path attribute, the sender attached one or more images. Each path is a local file already downloaded for you (comma-separated if several) — Read it to see the image before responding.',
'',
'To view an image that appears in read_context history but did NOT arrive with an image_path (e.g. an unaddressed image posted earlier), call the download_attachment tool with the attachment\'s mxc (from the read_context attachments field). It writes the file locally and returns the path — then Read that path.',
+ 'To send an image (or other file) into the room, call the send_attachment tool with the local file path and an optional caption/thread_id. It posts as a native room attachment and bridged platforms (Slack, Mattermost) receive it as a real file upload.',
'',
'When you receive a task_delegate event (only delivered if your integration profile has can_accept=true):',
'1. Call accept_task with the task_id to move it to ongoing.',
@@ -245,15 +246,61 @@ const DOWNLOAD_ATTACHMENT_TOOL = {
},
}
+// The outbound counterpart of download_attachment: the agent names a local
+// file (e.g. a screenshot it produced) and the channel uploads the bytes to
+// the agent bridge, which posts them into the room as an m.image / m.file
+// event — from there the collaboration bridges relay it out to Slack /
+// Mattermost like any other room message.
+const SEND_ATTACHMENT_TOOL = {
+ name: 'send_attachment',
+ description:
+ 'Send a local file (e.g. an image) into the connected Switch room as an ' +
+ 'attachment. It enters the room as a native image/file event and bridged ' +
+ 'platforms (Slack, Mattermost) receive it as a real file upload. ' +
+ 'Operates on the currently connected room unless room_id is given.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: {
+ type: 'string',
+ description: 'Absolute path of the local file to send.',
+ },
+ caption: {
+ type: 'string',
+ description: 'Optional text to accompany the attachment.',
+ },
+ thread_id: {
+ type: 'string',
+ description:
+ 'Optional message id to reply into, making this a threaded reply ' +
+ '(normalised to the thread root).',
+ },
+ room_id: {
+ type: 'string',
+ description:
+ 'Optional Switch room id. Defaults to the currently polling room.',
+ },
+ },
+ required: ['path'],
+ },
+}
+
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
- tools: [DOWNLOAD_ATTACHMENT_TOOL],
+ tools: [DOWNLOAD_ATTACHMENT_TOOL, SEND_ATTACHMENT_TOOL],
}))
mcp.setRequestHandler(CallToolRequestSchema, async req => {
- if (req.params.name !== 'download_attachment') {
- throw new Error(`Unknown tool: ${req.params.name}`)
+ if (req.params.name === 'download_attachment') {
+ return handleDownloadAttachment(req.params.arguments ?? {})
+ }
+ if (req.params.name === 'send_attachment') {
+ return handleSendAttachment(req.params.arguments ?? {})
}
- const args = (req.params.arguments ?? {}) as {
+ throw new Error(`Unknown tool: ${req.params.name}`)
+})
+
+async function handleDownloadAttachment(rawArgs: Record<string, unknown>) {
+ const args = rawArgs as {
mxc?: string
filename?: string
room_id?: string
@@ -285,7 +332,88 @@ mcp.setRequestHandler(CallToolRequestSchema, async req => {
content: [{ type: 'text', text: `Download failed: ${err}` }],
}
}
-})
+}
+
+// Minimal extension → mimetype map for common attachment types; anything else
+// goes up as application/octet-stream and enters the room as an m.file.
+const MIME_BY_EXT: Record<string, string> = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml',
+ '.bmp': 'image/bmp',
+ '.pdf': 'application/pdf',
+ '.txt': 'text/plain',
+}
+
+async function handleSendAttachment(rawArgs: Record<string, unknown>) {
+ const args = rawArgs as {
+ path?: string
+ caption?: string
+ thread_id?: string
+ room_id?: string
+ }
+ const filePath = typeof args.path === 'string' ? args.path : ''
+ if (!filePath) {
+ return { isError: true, content: [{ type: 'text', text: 'path is required' }] }
+ }
+ const roomId = args.room_id ?? pollingRoomId
+ if (!roomId) {
+ return {
+ isError: true,
+ content: [
+ {
+ type: 'text',
+ text: 'Not connected to a room — call connect_to_room first or pass room_id.',
+ },
+ ],
+ }
+ }
+
+ let bytes: Buffer
+ try {
+ bytes = fs.readFileSync(filePath)
+ } catch (err) {
+ return {
+ isError: true,
+ content: [{ type: 'text', text: `Cannot read ${filePath}: ${err}` }],
+ }
+ }
+
+ const filename = path.basename(filePath)
+ const mimetype = MIME_BY_EXT[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream'
+ const form = new FormData()
+ form.append('file', new Blob([bytes], { type: mimetype }), filename)
+ if (typeof args.caption === 'string' && args.caption) form.append('caption', args.caption)
+ if (typeof args.thread_id === 'string' && args.thread_id) form.append('thread_id', args.thread_id)
+
+ try {
+ const resp = await fetch(`${API_ENDPOINT}/agents/${AGENT_ID}/rooms/${roomId}/media`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${API_TOKEN}` },
+ body: form,
+ })
+ if (!resp.ok) {
+ throw new Error(`HTTP ${resp.status}: ${await resp.text()}`)
+ }
+ const data = (await resp.json()) as { event_id?: string }
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Sent ${filename} to the room (event_id: ${data.event_id ?? 'unknown'}).`,
+ },
+ ],
+ }
+ } catch (err) {
+ return {
+ isError: true,
+ content: [{ type: 'text', text: `Send failed: ${err}` }],
+ }
+ }
+}
// -- Polling loop ------------------------------------------------------------
diff --git a/connectors/claude-code-plugin/skills/switch/SKILL.md b/connectors/claude-code-plugin/skills/switch/SKILL.md
index fff506593..350de1fed 100644
--- a/connectors/claude-code-plugin/skills/switch/SKILL.md
+++ b/connectors/claude-code-plugin/skills/switch/SKILL.md
@@ -84,6 +84,33 @@ Both `post_message` and `send_targeted_message` accept an optional
threaded replies that address you; pull unaddressed thread activity with
`read_context` as usual.
+## Sending and receiving attachments
+
+Messages can carry file attachments (images most commonly). Both directions
+work in any room; on bridged rooms the attachment crosses the bridge as a
+real platform file upload (Slack, Mattermost).
+
+- **Receiving:** an addressed message with images arrives with an
+ `image_path` on the notification (already downloaded — Read the path). For
+ an attachment seen in `read_context` history (its `attachments` field),
+ pass its `mxc` to the channel's `download_attachment` tool, then Read the
+ returned path.
+- **Sending:** call the channel's **`send_attachment`** tool with the local
+ file `path`, an optional `caption`, and an optional `thread_id` (same
+ threading semantics as `post_message`). The file enters the room as a
+ native image/file event; bridges relay it out as a platform file upload.
+ Note on Slack the upload renders under the Switch app identity (Slack file
+ uploads can't carry the per-agent name/icon); your name is bolded in the
+ file's comment instead.
+- **No channel tool available?** (e.g. a switchdash-managed session where the
+ channel process is not running): upload directly to the bridge API —
+ `curl -X POST "$SWITCH_API_ENDPOINT/agents/$SWITCH_AGENT_ID/rooms/<room_id>/media"
+ -H "Authorization: Bearer $SWITCH_API_TOKEN" -F "file=@/path/to/image.png"
+ -F "caption=..."` (optional `-F "thread_id=..."`). Returns the posted
+ `event_id`.
+- Attachments are capped (20MB by default, server-configurable); oversize
+ uploads are rejected loudly rather than truncated.
+
**Match the mode to the recipient's `agent_type`:**
- `always_on` — safe to use targeted messages; prompt response expected.
- `session_addressable` — targeted messages work when the agent is in an
diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.py
index f3e488437..8157c3348 100644
--- a/core/switch_core/bridges/agent/api/handlers.py
+++ b/core/switch_core/bridges/agent/api/handlers.py
@@ -5,7 +5,15 @@ import logging
from datetime import UTC, datetime
from typing import Annotated, Any
-from fastapi import APIRouter, Depends, Header, HTTPException, Query
+from fastapi import (
+ APIRouter,
+ Depends,
+ Form,
+ Header,
+ HTTPException,
+ Query,
+ UploadFile,
+)
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import Response
@@ -416,6 +424,42 @@ async def download_media(
)
[email protected]("/{agent_id}/rooms/{room_id}/media")
+async def upload_media(
+ agent_id: str,
+ room_id: str,
+ file: UploadFile,
+ agent: Annotated[Agent, Depends(get_agent_from_scope)],
+ protocol: Annotated[ProtocolService, Depends(get_protocol)],
+ caption: Annotated[str | None, Form()] = None,
+ thread_id: Annotated[str | None, Form()] = None,
+) -> dict[str, object]:
+ """Post an attachment to a room as the agent (multipart upload).
+
+ The inverse of the GET media endpoint: the local channel (or any connector
+ holding the bridge API token) sends the file's bytes here; they are
+ uploaded to the Matrix media repo and posted to the room as an
+ m.image / m.file event, with optional caption and threading.
+ """
+ data = await file.read()
+ try:
+ result = await protocol.send_media(
+ agent.id,
+ room_id,
+ data,
+ filename=file.filename or "attachment",
+ mimetype=file.content_type or "application/octet-stream",
+ caption=caption,
+ thread_id=thread_id,
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=400, detail=str(e)) from e
+ except PermissionError as e:
+ raise HTTPException(status_code=403, detail=str(e)) from e
+
+ return {"ok": True, **result}
+
+
@router.post("/{agent_id}/typing")
async def set_typing(
agent_id: str,
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 92e9d3e9f..3c18f089b 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -753,6 +753,65 @@ class ProtocolService:
)
return event_id
+ async def send_media(
+ self,
+ agent_id: str,
+ room_id: str,
+ data: bytes,
+ filename: str,
+ mimetype: str,
+ caption: str | None = None,
+ thread_id: str | None = None,
+ ) -> dict[str, str]:
+ """Upload bytes to the Matrix media repository and post them to a room
+ as an m.image / m.file event. Returns {"event_id": ..., "mxc": ...}.
+
+ Membership in `room_id` is required, mirroring download_media. The
+ payload is capped by config.agent_media_max_bytes — an oversize upload
+ raises rather than being truncated. When `caption` is set it becomes
+ the event body (the filename rides in the `filename` field, per the
+ caption convention the bridges already use inbound). When `thread_id`
+ is set the event is posted into that thread (normalised to its root).
+ """
+ if not data:
+ raise ValueError("attachment is empty")
+ max_bytes = self.config.agent_media_max_bytes
+ if len(data) > max_bytes:
+ raise ValueError(
+ f"attachment '{filename}' is {len(data)} bytes, over the "
+ f"{max_bytes}-byte limit (AGENT_MEDIA_MAX_BYTES)"
+ )
+ room = await self.require_room_member(agent_id, room_id)
+ client = self.client_lifecycle.get_by_agent_id(agent_id)
+ if client is None:
+ raise ValueError("Agent client not running")
+ thread_root_id: str | None = None
+ if thread_id is not None:
+ thread_root_id = await self._resolve_thread_root(
+ client, room.matrix_room_id, thread_id
+ )
+ mxc = await client.upload_media(data, mimetype, filename)
+ msgtype = "m.image" if mimetype.startswith("image/") else "m.file"
+ event_id = await client.send_media(
+ room.matrix_room_id,
+ mxc,
+ filename,
+ mimetype,
+ len(data),
+ msgtype=msgtype,
+ caption=caption if caption and caption.strip() else None,
+ thread_root_id=thread_root_id,
+ )
+ if event_id is None:
+ raise ValueError("Failed to send media message")
+ try:
+ await self.set_typing(agent_id, room_id, False)
+ except Exception:
+ logger.warning(
+ "Failed to clear typing indicator for room %s", room_id, exc_info=True
+ )
+ return {"event_id": event_id, "mxc": mxc}
+
async def send_targeted_message(
self,
agent_id: str,
diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.py
index 7aa4faa73..7d8d3b538 100644
--- a/core/switch_core/bridges/collaboration/adapter.py
+++ b/core/switch_core/bridges/collaboration/adapter.py
@@ -78,6 +78,30 @@ class CollaborationAdapter(ABC):
def _bridge_display_name(self) -> str:
return "Switch"
+ async def send_attachment(
+ self,
+ channel_id: str,
+ sender_name: str,
+ filename: str,
+ mimetype: str,
+ data: bytes,
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Relay a file attachment to the external channel as `sender_name`,
+ returning the platform message ref (like send_message).
+
+ Platforms with a file API override this to upload the bytes natively.
+ This default is the disclosed degradation for adapters without native
+ support: a text message that names the attachment instead of silently
+ dropping it.
+ """
+ note = f"_sent an attachment that couldn't be relayed: {filename}_"
+ body = f"{caption}\n{note}" if caption else note
+ return await self.send_message(
+ channel_id, sender_name, self.translate_outbound(body), thread_root_id
+ )
+
@abstractmethod
async def update_message(
self, channel_id: str, message_ref: str, new_content: str
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 0331c4724..a89205beb 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -3,9 +3,15 @@ from __future__ import annotations
import asyncio
import logging
import re
-from typing import TYPE_CHECKING
-
-from nio import MatrixRoom, RoomMessageText, RoomSendError
+from typing import TYPE_CHECKING, Any
+
+from nio import (
+ DownloadError,
+ MatrixRoom,
+ RoomMessageMedia,
+ RoomMessageText,
+ RoomSendError,
+)
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.collaboration.adapter import CollaborationAdapter
@@ -71,6 +77,7 @@ class BridgeCore:
session_factory: async_sessionmaker[AsyncSession],
matrix_server_name: str,
bridge_client_matrix_user_id: str,
+ max_attachment_bytes: int,
) -> None:
self._bridge_id = bridge_id
self._bridge_type = bridge_type
@@ -87,6 +94,7 @@ class BridgeCore:
self._session_factory = session_factory
self._matrix_server_name = matrix_server_name
self._bridge_client_matrix_user_id = bridge_client_matrix_user_id
+ self._max_attachment_bytes = max_attachment_bytes
self._channel_to_room: dict[str, tuple[str, str]] = {}
self._room_to_channel: dict[tuple[str, str], str] = {}
@@ -786,23 +794,9 @@ class BridgeCore:
admin_marker is not None,
)
- # Bridge threads outbound: if this Matrix message is a threaded reply,
- # resolve its thread root to the external post that anchors the thread.
- thread_root_ref: str | None = None
- relates = event_content.get("m.relates_to") or {}
- if relates.get("rel_type") == "m.thread":
- root_event_id = relates.get("event_id")
- if root_event_id:
- thread_root_ref = await self._external_post_for_matrix_event(
- root_event_id
- )
- if thread_root_ref is None:
- logger.warning(
- "[BRIDGE-OUT] no external post mapped for thread root %s; "
- "posting top-level in channel %s",
- root_event_id,
- channel_id,
- )
+ thread_root_ref = await self._outbound_thread_root_ref(
+ event_content, channel_id
+ )
content = self._adapter.translate_outbound(event.body)
if admin_marker is not None:
@@ -828,6 +822,155 @@ class BridgeCore:
external_post_id=message_ref,
)
+ async def _outbound_thread_root_ref(
+ self, event_content: dict[str, object], channel_id: str
+ ) -> str | None:
+ """Bridge threads outbound: if this Matrix message is a threaded reply,
+ resolve its thread root to the external post that anchors the thread."""
+ relates = event_content.get("m.relates_to") or {}
+ if not isinstance(relates, dict) or relates.get("rel_type") != "m.thread":
+ return None
+ root_event_id = relates.get("event_id")
+ if not root_event_id:
+ return None
+ thread_root_ref = await self._external_post_for_matrix_event(str(root_event_id))
+ if thread_root_ref is None:
+ logger.warning(
+ "[BRIDGE-OUT] no external post mapped for thread root %s; "
+ "posting top-level in channel %s",
+ root_event_id,
+ channel_id,
+ )
+ return thread_root_ref
+
+ async def handle_outbound_media(
+ self,
+ room: MatrixRoom,
+ event: RoomMessageMedia,
+ client: ClientBase[Any],
+ ) -> None:
+ """Relay a Matrix media event (an agent-sent image/file) out to the
+ external channel.
+
+ Mirrors handle_outbound_message: puppet media is skipped (it originated
+ on the platform), the caption convention is unpacked (a `filename` key
+ means the body is a caption), and the relayed post is recorded in the
+ message map so replies thread both ways. Images relay natively via the
+ adapter's send_attachment; other file types get a disclosed text notice
+ (matching the images-only inbound path) rather than a silent drop.
+ `client` is the bridge's Matrix client, used to fetch the media bytes.
+ """
+ logger.debug(
+ "[BRIDGE-OUT] matrix media event from=%s room=%s body=%s",
+ event.sender,
+ room.room_id,
+ event.body[:80] if event.body else "",
+ )
+ if event.sender in self._puppet_matrix_ids:
+ return
+ if event.sender == self._bridge_client_matrix_user_id:
+ return
+
+ channel_id = self._find_channel(matrix_room_id=room.room_id)
+ if channel_id is None:
+ logger.debug("[BRIDGE-OUT] no channel mapping for room %s", room.room_id)
+ return
+
+ event_content = event.source.get("content", {}) or {}
+ sender_name = event_content.get("sender_name")
+ if sender_name is None:
+ logger.error(
+ "No sender_name in media event from %s — skipping outbound",
+ event.sender,
+ )
+ return
+ sender_name = str(sender_name)
+
+ thread_root_ref = await self._outbound_thread_root_ref(
+ event_content, channel_id
+ )
+
+ # Caption convention (mirrors the inbound path): when a `filename` key
+ # is present the event body is a caption; otherwise the body IS the
+ # filename and there is no caption.
+ explicit_filename = event_content.get("filename")
+ filename = str(explicit_filename or event.body or "attachment")
+ caption = event.body if explicit_filename else None
+
+ info = event_content.get("info") or {}
+ mimetype = str(
+ (info.get("mimetype") if isinstance(info, dict) else None)
+ or "application/octet-stream"
+ )
+
+ message_ref: str | None
+ if event_content.get("msgtype") != "m.image":
+ note = f"_sent a file that isn't relayed yet: {filename}_"
+ body = f"{caption}\n{note}" if caption else note
+ message_ref = await self._adapter.send_message(
+ channel_id,
+ sender_name,
+ self._adapter.translate_outbound(body),
+ thread_root_id=thread_root_ref,
+ )
+ else:
+ data = await self._download_matrix_media(client, event.url, filename)
+ if data is None or len(data) > self._max_attachment_bytes:
+ if data is not None:
+ logger.warning(
+ "[BRIDGE-OUT] attachment %s is %d bytes, over the "
+ "%d-byte relay cap",
+ filename,
+ len(data),
+ self._max_attachment_bytes,
+ )
+ note = f"_sent an attachment that couldn't be relayed: {filename}_"
+ body = f"{caption}\n{note}" if caption else note
+ message_ref = await self._adapter.send_message(
+ channel_id,
+ sender_name,
+ self._adapter.translate_outbound(body),
+ thread_root_id=thread_root_ref,
+ )
+ else:
+ message_ref = await self._adapter.send_attachment(
+ channel_id,
+ sender_name,
+ filename,
+ mimetype,
+ data,
+ caption=caption,
+ thread_root_id=thread_root_ref,
+ )
+
+ if message_ref is not None:
+ await self._record_message_map(
+ external_channel_id=channel_id,
+ matrix_event_id=event.event_id,
+ external_post_id=message_ref,
+ )
+
+ async def _download_matrix_media(
+ self, client: ClientBase[Any], mxc: str | None, filename: str
+ ) -> bytes | None:
+ """Fetch an mxc URI's bytes via the bridge client, or None on failure
+ (logged — the caller posts a disclosed fallback, never a silent drop)."""
+ if not mxc:
+ logger.error("[BRIDGE-OUT] media event for %s has no mxc URI", filename)
+ return None
+ if client.nio_client is None:
+ logger.error(
+ "[BRIDGE-OUT] bridge client not connected; cannot fetch %s", mxc
+ )
+ return None
+ resp = await client.nio_client.download(mxc=mxc)
+ if isinstance(resp, DownloadError):
+ logger.error(
+ "[BRIDGE-OUT] failed to download media %s: %s", mxc, resp.message
+ )
+ return None
+ return resp.body # type: ignore[no-any-return]
+
async def handle_outbound_typing(
self, room_id: str, agent_name: str, is_typing: bool
) -> None:
diff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.py
index bc44468fd..eae33d03a 100644
--- a/core/switch_core/bridges/collaboration/lifecycle_service.py
+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py
@@ -177,6 +177,7 @@ class CollaborationBridgeLifecycleService:
session_factory=self._session_factory,
matrix_server_name=self._config.matrix_server_name,
bridge_client_matrix_user_id=bridge_client_record.matrix_user_id,
+ max_attachment_bytes=self._config.agent_media_max_bytes,
)
bridge_client = BridgeClient(
diff --git a/core/switch_core/bridges/collaboration/mattermost/adapter.py b/core/switch_core/bridges/collaboration/mattermost/adapter.py
index 5644eda77..e4ac1af33 100644
--- a/core/switch_core/bridges/collaboration/mattermost/adapter.py
+++ b/core/switch_core/bridges/collaboration/mattermost/adapter.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import io
import json
import logging
import re
@@ -194,6 +195,77 @@ class MattermostAdapter(CollaborationAdapter):
return None
return await self._create_post(driver, channel_id, content, thread_root_id)
+ async def send_attachment(
+ self,
+ channel_id: str,
+ sender_name: str,
+ filename: str,
+ mimetype: str,
+ data: bytes,
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Upload the file with the agent's own bot and attach it to a post —
+ full identity and threading parity with text messages."""
+ loop = self._main_loop
+ if loop is None:
+ logger.error("Cannot send attachment: event loop not initialized")
+ return None
+ driver = self._bot_drivers.get(sender_name)
+ if not driver:
+ logger.error("No Mattermost driver found for sender '%s'", sender_name)
+ if not self._admin_driver:
+ return None
+ driver = self._admin_driver
+
+ def _upload() -> list[str]:
+ result = driver.files.upload_file(
+ channel_id,
+ files={"files": (filename, io.BytesIO(data), mimetype)},
+ )
+ return [info["id"] for info in result.get("file_infos", [])]
+
+ try:
+ file_ids = await loop.run_in_executor(None, _upload)
+ except Exception as e:
+ logger.error(
+ "Failed to upload attachment '%s' to Mattermost channel %s: %s",
+ filename,
+ channel_id,
+ e,
+ )
+ file_ids = []
+ if not file_ids:
+ return await super().send_attachment(
+ channel_id,
+ sender_name,
+ filename,
+ mimetype,
+ data,
+ caption,
+ thread_root_id,
+ )
+
+ post: dict[str, object] = {
+ "channel_id": channel_id,
+ "message": self.translate_outbound(caption) if caption else "",
+ "file_ids": file_ids,
+ }
+ if thread_root_id is not None:
+ post["root_id"] = thread_root_id
+ try:
+ result = await loop.run_in_executor(None, driver.posts.create_post, post)
+ post_id: str = result.get("id", "")
+ return post_id or None
+ except Exception as e:
+ logger.error(
+ "Failed to post attachment '%s' to Mattermost channel %s: %s",
+ filename,
+ channel_id,
+ e,
+ )
+ return None
+
async def _create_post(
self,
driver: Driver,
diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.py
index 6ed927bf1..bdd9b8336 100644
--- a/core/switch_core/bridges/collaboration/slack/adapter.py
+++ b/core/switch_core/bridges/collaboration/slack/adapter.py
@@ -216,6 +216,91 @@ class SlackAdapter(CollaborationAdapter):
)
return None
+ async def send_attachment(
+ self,
+ channel_id: str,
+ sender_name: str,
+ filename: str,
+ mimetype: str,
+ data: bytes,
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ """Upload a file natively via files_upload_v2.
+
+ Slack's file upload cannot carry the per-message username/icon
+ override that send_message uses, so the file post renders as the
+ Switch app itself; the sender's identity is preserved by bolding
+ their name in the comment. The upload's shared-message ts is pulled
+ from the response when Slack provides it (v2 completes the share
+ asynchronously, so it may be absent — then no ref is returned and
+ replies to the file won't thread back to Matrix).
+ """
+ if not self._web_client:
+ logger.error("Cannot send attachment: Slack client not connected")
+ return None
+
+ thread_ts: str | None = None
+ if thread_root_id:
+ thread_ts = (
+ self._parse_message_ref(thread_root_id)[1]
+ if ":" in thread_root_id
+ else thread_root_id
+ )
+
+ comment = (
+ f"*{sender_name}*: {self.translate_outbound(caption)}"
+ if caption
+ else f"*{sender_name}* sent `{filename}`"
+ )
+
+ try:
+ result = await self._web_client.files_upload_v2(
+ channel=channel_id,
+ file=data,
+ filename=filename,
+ initial_comment=comment,
+ thread_ts=thread_ts,
+ )
+ except SlackApiError as e:
+ logger.error(
+ "Failed to upload attachment '%s' to Slack channel %s: %s",
+ filename,
+ channel_id,
+ e,
+ )
+ return await super().send_attachment(
+ channel_id,
+ sender_name,
+ filename,
+ mimetype,
+ data,
+ caption,
+ thread_root_id,
+ )
+
+ ts = self._extract_share_ts(result.get("files") or [], channel_id)
+ return f"{channel_id}:{ts}" if ts else None
+
+ @staticmethod
+ def _extract_share_ts(
+ files: list[dict[str, object]], channel_id: str
+ ) -> str | None:
+ """The ts of the message that shared an uploaded file into the channel,
+ when the upload response already carries it."""
+ for file in files:
+ shares = file.get("shares")
+ if not isinstance(shares, dict):
+ continue
+ for scope in ("public", "private"):
+ entries = shares.get(scope)
+ if isinstance(entries, dict):
+ for entry in entries.get(channel_id, []):
+ ts = entry.get("ts")
+ if ts:
+ return str(ts)
+ return None
+
async def update_message(
self, channel_id: str, message_ref: str, new_content: str
) -> None:
diff --git a/core/switch_core/clients/bridge_client.py b/core/switch_core/clients/bridge_client.py
index 3d62aa183..ab860bd45 100644
--- a/core/switch_core/clients/bridge_client.py
+++ b/core/switch_core/clients/bridge_client.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
-from nio import MatrixRoom, RoomMessageText
+from nio import MatrixRoom, RoomMessageMedia, RoomMessageText
from switch_core.clients.client_base import ClientBase, ClientConfig
from switch_core.events import AgentRuntimeStateEvent
@@ -33,6 +33,14 @@ class BridgeClient(ClientBase[BridgeClientConfig]):
)
await self._bridge_core.handle_outbound_message(room, event)
+ async def on_media(self, room: MatrixRoom, event: RoomMessageMedia) -> None:
+ logger.debug(
+ "[BRIDGE-CLIENT] on_media room=%s sender=%s",
+ room.room_id,
+ event.sender,
+ )
+ await self._bridge_core.handle_outbound_media(room, event, self)
+
async def on_agent_runtime_state(
self, room: MatrixRoom, event: AgentRuntimeStateEvent
) -> None:
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index ddad3e149..8e118bd0a 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -56,6 +56,11 @@ class SwitchConfig(BaseSettings):
frontend_base_url: str | None = None
+ # Upper bound on a single attachment an agent may post to a room (and that
+ # a collaboration bridge will relay out). Uploads over this raise instead
+ # of being truncated or silently dropped.
+ agent_media_max_bytes: int = 20 * 1024 * 1024
+
db_pool_size: int = 20
db_max_overflow: int = 10
db_pool_recycle: int = 1800
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py
new file mode 100644
index 000000000..2833c9a07
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from switch_core.bridges.agent.protocol.service import ProtocolService
+
+
+class _FakeClient:
+ def __init__(self) -> None:
+ self.uploads: list[tuple[bytes, str, str]] = []
+ self.sends: list[dict[str, Any]] = []
+
+ async def upload_media(self, data: bytes, content_type: str, filename: str) -> str:
+ self.uploads.append((data, content_type, filename))
+ return "mxc://s/uploaded"
+
+ async def send_media(
+ self,
+ room_id: str,
+ mxc: str,
+ filename: str,
+ mimetype: str,
+ size: int,
+ *,
+ msgtype: str,
+ caption: str | None = None,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ self.sends.append(
+ {
+ "room_id": room_id,
+ "mxc": mxc,
+ "filename": filename,
+ "mimetype": mimetype,
+ "size": size,
+ "msgtype": msgtype,
+ "caption": caption,
+ "thread_root_id": thread_root_id,
+ }
+ )
+ return "$media-event"
+
+
+def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolService:
+ async def _require(agent_id: str, room_id: str):
+ return SimpleNamespace(matrix_room_id="!room")
+
+ async def _set_typing(agent_id: str, room_id: str, is_typing: bool) -> None:
+ pass
+
+ async def _resolve_thread_root(client_: Any, matrix_room_id: str, thread_id: str):
+ return f"root-of-{thread_id}"
+
+ svc = object.__new__(ProtocolService)
+ svc.require_room_member = _require # type: ignore[assignment]
+ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]
+ get_by_agent_id=lambda agent_id: client
+ )
+ svc.config = SimpleNamespace(agent_media_max_bytes=max_bytes) # type: ignore[assignment]
+ svc.set_typing = _set_typing # type: ignore[assignment]
+ svc._resolve_thread_root = _resolve_thread_root # type: ignore[assignment]
+ return svc
+
+
+async def test_send_media_uploads_and_posts_image() -> None:
+ client = _FakeClient()
+ svc = _build_service(client)
+
+ result = await svc.send_media(
+ "agent-1", "room-1", b"png-bytes", filename="cat.png", mimetype="image/png"
+ )
+
+ assert result == {"event_id": "$media-event", "mxc": "mxc://s/uploaded"}
+ assert client.uploads == [(b"png-bytes", "image/png", "cat.png")]
+ sent = client.sends[0]
+ assert sent["room_id"] == "!room"
+ assert sent["msgtype"] == "m.image"
+ assert sent["caption"] is None
+ assert sent["thread_root_id"] is None
+
+
+async def test_send_media_caption_and_thread() -> None:
+ client = _FakeClient()
+ svc = _build_service(client)
+
+ await svc.send_media(
+ "agent-1",
+ "room-1",
+ b"x",
+ filename="cat.png",
+ mimetype="image/png",
+ caption="look",
+ thread_id="$mid-thread",
+ )
+
+ sent = client.sends[0]
+ assert sent["caption"] == "look"
+ assert sent["thread_root_id"] == "root-of-$mid-thread"
+
+
+async def test_send_media_non_image_is_file_msgtype() -> None:
+ client = _FakeClient()
+ svc = _build_service(client)
+
+ await svc.send_media(
+ "agent-1", "room-1", b"%PDF", filename="doc.pdf", mimetype="application/pdf"
+ )
+
+ assert client.sends[0]["msgtype"] == "m.file"
+
+
+async def test_send_media_oversize_raises() -> None:
+ client = _FakeClient()
+ svc = _build_service(client, max_bytes=3)
+
+ with pytest.raises(ValueError, match="over the 3-byte limit"):
+ await svc.send_media(
+ "agent-1", "room-1", b"toolarge", filename="c.png", mimetype="image/png"
+ )
+ assert client.uploads == []
+
+
+async def test_send_media_empty_raises() -> None:
+ client = _FakeClient()
+ svc = _build_service(client)
+
+ with pytest.raises(ValueError, match="empty"):
+ await svc.send_media(
+ "agent-1", "room-1", b"", filename="c.png", mimetype="image/png"
+ )
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py
new file mode 100644
index 000000000..ade988fea
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py
@@ -0,0 +1,243 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import nio
+from nio import DownloadError
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+
+
+def _media_event(
+ *,
+ msgtype: str = "m.image",
+ body: str = "cat.png",
+ filename: str | None = None,
+ sender: str = "@agent:s",
+ sender_name: str | None = "agent-a",
+ thread_root: str | None = None,
+) -> nio.RoomMessageMedia:
+ content: dict[str, Any] = {
+ "msgtype": msgtype,
+ "body": body,
+ "url": "mxc://s/abc",
+ "info": {"mimetype": "image/png", "size": 5},
+ }
+ if filename is not None:
+ content["filename"] = filename
+ if sender_name is not None:
+ content["sender_name"] = sender_name
+ if thread_root is not None:
+ content["m.relates_to"] = {"rel_type": "m.thread", "event_id": thread_root}
+ cls = nio.RoomMessageImage if msgtype == "m.image" else nio.RoomMessageFile
+ return cls.from_dict(
+ {
+ "type": "m.room.message",
+ "event_id": "$media-event",
+ "sender": sender,
+ "origin_server_ts": 1700000000000,
+ "content": content,
+ }
+ )
+
+
+class _FakeAdapter:
+ def __init__(self) -> None:
+ self.attachments: list[dict[str, Any]] = []
+ self.messages: list[dict[str, Any]] = []
+
+ async def send_attachment(
+ self,
+ channel_id,
+ sender_name,
+ filename,
+ mimetype,
+ data,
+ caption=None,
+ thread_root_id=None,
+ ): # noqa: ANN001, ANN201
+ self.attachments.append(
+ {
+ "channel_id": channel_id,
+ "sender_name": sender_name,
+ "filename": filename,
+ "mimetype": mimetype,
+ "data": data,
+ "caption": caption,
+ "thread_root_id": thread_root_id,
+ }
+ )
+ return "ext-ref-1"
+
+ async def send_message(self, channel_id, sender_name, content, thread_root_id=None): # noqa: ANN001, ANN201
+ self.messages.append(
+ {
+ "channel_id": channel_id,
+ "sender_name": sender_name,
+ "content": content,
+ "thread_root_id": thread_root_id,
+ }
+ )
+ return "ext-ref-2"
+
+ def translate_outbound(self, content: str) -> str:
+ return content
+
+
+def _fake_bridge(
+ *,
+ download: object = SimpleNamespace(body=b"bytes"),
+ matrix_to_external: dict[str, str] | None = None,
+ max_bytes: int = 1024,
+) -> SimpleNamespace:
+ adapter = _FakeAdapter()
+ recorded: list[dict[str, str]] = []
+ lookup = matrix_to_external or {}
+
+ async def _external_post_for_matrix_event(matrix_event_id: str) -> str | None:
+ return lookup.get(matrix_event_id)
+
+ async def _record_message_map(**kwargs: str) -> None:
+ recorded.append(kwargs)
+
+ ns = SimpleNamespace(
+ _adapter=adapter,
+ _puppet_matrix_ids={"@puppet:s"},
+ _bridge_client_matrix_user_id="@bridge:s",
+ _max_attachment_bytes=max_bytes,
+ _external_post_for_matrix_event=_external_post_for_matrix_event,
+ _record_message_map=_record_message_map,
+ recorded=recorded,
+ )
+ ns._find_channel = lambda room_id=None, matrix_room_id=None: (
+ "chan-1" if matrix_room_id == "!room:s" else None
+ )
+ ns._outbound_thread_root_ref = BridgeCore._outbound_thread_root_ref.__get__(ns)
+ ns._download_matrix_media = BridgeCore._download_matrix_media.__get__(ns)
+
+ async def _nio_download(mxc: str):
+ return download
+
+ ns.client = SimpleNamespace(nio_client=SimpleNamespace(download=_nio_download))
+ return ns
+
+
+def _room() -> SimpleNamespace:
+ return SimpleNamespace(room_id="!room:s")
+
+
+async def test_image_relays_via_send_attachment_and_records_map() -> None:
+ bridge = _fake_bridge()
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(), bridge.client
+ )
+
+ assert bridge._adapter.attachments == [
+ {
+ "channel_id": "chan-1",
+ "sender_name": "agent-a",
+ "filename": "cat.png",
+ "mimetype": "image/png",
+ "data": b"bytes",
+ "caption": None,
+ "thread_root_id": None,
+ }
+ ]
+ assert bridge.recorded == [
+ {
+ "external_channel_id": "chan-1",
+ "matrix_event_id": "$media-event",
+ "external_post_id": "ext-ref-1",
+ }
+ ]
+
+
+async def test_caption_convention_unpacks_body_and_filename() -> None:
+ bridge = _fake_bridge()
+
+ await BridgeCore.handle_outbound_media(
+ bridge,
+ _room(),
+ _media_event(body="look at this", filename="plot.png"),
+ bridge.client,
+ )
+
+ sent = bridge._adapter.attachments[0]
+ assert sent["filename"] == "plot.png"
+ assert sent["caption"] == "look at this"
+
+
+async def test_threaded_media_resolves_external_root() -> None:
+ bridge = _fake_bridge(matrix_to_external={"$root": "ext-root"})
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(thread_root="$root"), bridge.client
+ )
+
+ assert bridge._adapter.attachments[0]["thread_root_id"] == "ext-root"
+
+
+async def test_puppet_media_is_skipped() -> None:
+ # Media a puppet posted originated on the platform — relaying it back
+ # would echo it.
+ bridge = _fake_bridge()
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(sender="@puppet:s"), bridge.client
+ )
+
+ assert bridge._adapter.attachments == []
+ assert bridge._adapter.messages == []
+
+
+async def test_media_without_sender_name_is_skipped() -> None:
+ bridge = _fake_bridge()
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(sender_name=None), bridge.client
+ )
+
+ assert bridge._adapter.attachments == []
+ assert bridge._adapter.messages == []
+
+
+async def test_non_image_file_posts_disclosed_notice() -> None:
+ bridge = _fake_bridge()
+
+ await BridgeCore.handle_outbound_media(
+ bridge,
+ _room(),
+ _media_event(msgtype="m.file", body="report.pdf"),
+ bridge.client,
+ )
+
+ assert bridge._adapter.attachments == []
+ assert len(bridge._adapter.messages) == 1
+ assert "report.pdf" in bridge._adapter.messages[0]["content"]
+ # The notice still threads/correlates like a real relay.
+ assert bridge.recorded[0]["external_post_id"] == "ext-ref-2"
+
+
+async def test_download_failure_posts_disclosed_fallback() -> None:
+ bridge = _fake_bridge(download=DownloadError("boom"))
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(), bridge.client
+ )
+
+ assert bridge._adapter.attachments == []
+ assert len(bridge._adapter.messages) == 1
+ assert "couldn't be relayed" in bridge._adapter.messages[0]["content"]
+
+
+async def test_oversize_media_posts_disclosed_fallback() -> None:
+ bridge = _fake_bridge(download=SimpleNamespace(body=b"too big"), max_bytes=3)
+
+ await BridgeCore.handle_outbound_media(
+ bridge, _room(), _media_event(), bridge.client
+ )
+
+ assert bridge._adapter.attachments == []
+ assert "couldn't be relayed" in bridge._adapter.messages[0]["content"]
diff --git a/core/tests/switch_core/bridges/collaboration/test_mattermost_attachments.py b/core/tests/switch_core/bridges/collaboration/test_mattermost_attachments.py
index 13aeab8d7..9c45d9efa 100644
--- a/core/tests/switch_core/bridges/collaboration/test_mattermost_attachments.py
+++ b/core/tests/switch_core/bridges/collaboration/test_mattermost_attachments.py
@@ -96,3 +96,130 @@ def test_failed_download_skips_only_that_file() -> None:
def test_no_file_ids_returns_empty() -> None:
adapter = _adapter_with_files(_FakeFiles(meta={}, data={}))
assert _fetch(adapter, []) == []
+
+
+# ── Outbound attachments ─────────────────────────────────────────────────────
+
+
+class _FakeUploadFiles:
+ def __init__(self, *, fail: bool = False) -> None:
+ self.uploads: list[tuple[str, dict[str, object]]] = []
+ self._fail = fail
+
+ def upload_file(self, channel_id: str, files: dict[str, object]): # noqa: ANN201
+ if self._fail:
+ raise RuntimeError("upload boom")
+ self.uploads.append((channel_id, files))
+ return {"file_infos": [{"id": "fid-1"}]}
+
+
+class _FakePosts:
+ def __init__(self) -> None:
+ self.posts: list[dict[str, object]] = []
+
+ def create_post(self, post: dict[str, object]) -> dict[str, str]:
+ self.posts.append(post)
+ return {"id": "post-1"}
+
+
+def _egress_adapter(
+ *, upload_fail: bool = False
+) -> tuple[MattermostAdapter, _FakeUploadFiles, _FakePosts]:
+ adapter = MattermostAdapter(
+ config=MattermostConnectionConfig(
+ url="http://mm",
+ admin_user="admin",
+ admin_password="pw",
+ team_name="team",
+ )
+ )
+ files = _FakeUploadFiles(fail=upload_fail)
+ posts = _FakePosts()
+ driver = type("_Driver", (), {"files": files, "posts": posts})()
+ adapter._bot_drivers["agent-a"] = driver # type: ignore[assignment]
+ return adapter, files, posts
+
+
+def _send(adapter: MattermostAdapter, **kwargs: object):
+ loop = asyncio.new_event_loop()
+ try:
+
+ async def go():
+ adapter._main_loop = asyncio.get_event_loop()
+ return await adapter.send_attachment(**kwargs) # type: ignore[arg-type]
+
+ return loop.run_until_complete(go())
+ finally:
+ loop.close()
+
+
+def test_send_attachment_uploads_and_posts_as_agent_bot() -> None:
+ adapter, files, posts = _egress_adapter()
+
+ ref = _send(
+ adapter,
+ channel_id="chan-1",
+ sender_name="agent-a",
+ filename="plot.png",
+ mimetype="image/png",
+ data=b"bytes",
+ caption="the plot",
+ thread_root_id="root-post",
+ )
+
+ assert ref == "post-1"
+ assert len(files.uploads) == 1
+ channel_id, upload_files = files.uploads[0]
+ assert channel_id == "chan-1"
+ filename, blob, mimetype = upload_files["files"] # type: ignore[misc]
+ assert filename == "plot.png"
+ assert blob.read() == b"bytes"
+ assert mimetype == "image/png"
+ assert posts.posts == [
+ {
+ "channel_id": "chan-1",
+ "message": "the plot",
+ "file_ids": ["fid-1"],
+ "root_id": "root-post",
+ }
+ ]
+
+
+def test_send_attachment_without_caption_or_thread() -> None:
+ adapter, _files, posts = _egress_adapter()
+
+ ref = _send(
+ adapter,
+ channel_id="chan-1",
+ sender_name="agent-a",
+ filename="cat.png",
+ mimetype="image/png",
+ data=b"x",
+ )
+
+ assert ref == "post-1"
+ assert posts.posts[0]["message"] == ""
+ assert "root_id" not in posts.posts[0]
+
+
+def test_send_attachment_upload_failure_falls_back_to_disclosed_text() -> None:
+ adapter, files, posts = _egress_adapter(upload_fail=True)
+
+ ref = _send(
+ adapter,
+ channel_id="chan-1",
+ sender_name="agent-a",
+ filename="cat.png",
+ mimetype="image/png",
+ data=b"x",
+ caption="look",
+ )
+
+ # The failure surfaces as a visible text post, never a silent drop.
+ assert ref == "post-1"
+ assert files.uploads == []
+ assert len(posts.posts) == 1
+ message = str(posts.posts[0]["message"])
+ assert "couldn't be relayed" in message
+ assert "cat.png" in message
+ assert "file_ids" not in posts.posts[0]
diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
index 1f0dde142..a283f8676 100644
--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py
@@ -958,3 +958,91 @@ def test_user_join_does_not_fire_on_app_joined() -> None:
assert app_joins == []
assert len(user_joins) == 1
assert user_joins[0].external_user_id == "U1"
+
+
+# ── Outbound attachments ─────────────────────────────────────────────────────
+
+
+class _FakeUploadWebClient(_FakeWebClient):
+ """Adds files_upload_v2 capture on top of the postMessage fake."""
+
+ def __init__(
+ self,
+ *,
+ upload_response: dict[str, Any] | None = None,
+ upload_error: str | None = None,
+ ) -> None:
+ super().__init__()
+ self.uploads: list[dict[str, Any]] = []
+ self._upload_response = upload_response or {"files": []}
+ self._upload_error = upload_error
+
+ async def files_upload_v2(self, **kwargs: Any) -> dict[str, Any]:
+ self.uploads.append(kwargs)
+ if self._upload_error:
+ raise SlackApiError(self._upload_error, {"error": self._upload_error})
+ return self._upload_response
+
+
+def test_send_attachment_uploads_file_with_sender_and_caption() -> None:
+ adapter = _adapter()
+ fake = _FakeUploadWebClient(
+ upload_response={"files": [{"shares": {"public": {"C123": [{"ts": "42.1"}]}}}]}
+ )
+ adapter._web_client = fake # type: ignore[assignment]
+
+ ref = _run(
+ adapter.send_attachment(
+ "C123",
+ "agent-a",
+ "plot.png",
+ "image/png",
+ b"bytes",
+ caption="the **plot**",
+ thread_root_id="C123:11.0",
+ )
+ )
+
+ assert len(fake.uploads) == 1
+ up = fake.uploads[0]
+ assert up["channel"] == "C123"
+ assert up["file"] == b"bytes"
+ assert up["filename"] == "plot.png"
+ # Sender identity is preserved in the comment (bolded), caption translated
+ # to mrkdwn (** → *).
+ assert up["initial_comment"] == "*agent-a*: the *plot*"
+ assert up["thread_ts"] == "11.0"
+ # The share ts from the upload response becomes the message ref.
+ assert ref == "C123:42.1"
+
+
+def test_send_attachment_without_caption_names_sender_and_file() -> None:
+ adapter = _adapter()
+ fake = _FakeUploadWebClient()
+ adapter._web_client = fake # type: ignore[assignment]
+
+ ref = _run(adapter.send_attachment("C123", "agent-a", "cat.png", "image/png", b"x"))
+
+ assert fake.uploads[0]["initial_comment"] == "*agent-a* sent `cat.png`"
+ assert fake.uploads[0]["thread_ts"] is None
+ # No share info in the response → no ref (threading correlation degraded).
+ assert ref is None
+
+
+def test_send_attachment_upload_failure_falls_back_to_disclosed_text() -> None:
+ adapter = _adapter()
+ fake = _FakeUploadWebClient(upload_error="upload_failed")
+ adapter._web_client = fake # type: ignore[assignment]
+
+ ref = _run(
+ adapter.send_attachment(
+ "C123", "agent-a", "cat.png", "image/png", b"x", caption="look"
+ )
+ )
+
+ # The failure surfaces as a visible text message, never a silent drop.
+ assert len(fake.calls) == 1
+ assert "couldn't be relayed" in fake.calls[0]["text"]
+ assert "cat.png" in fake.calls[0]["text"]
+ assert fake.calls[0]["username"] == "agent-a"
+ assert ref == "C123:999.9"