Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions plugins/platforms/slack/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import asyncio
import contextvars
import hashlib
import inspect
import json
import logging
Expand Down Expand Up @@ -649,6 +650,40 @@ def _sanitize(value):
return f"[Slack Block Kit payload for this message]\n```json\n{payload}\n```"


def _slack_message_body_signature(message: dict) -> str:
"""Return the part of a message body the agent is shown, as one value.

The inbound path builds the agent's text from the flat ``text`` *and* the
Block Kit payload, so an update that rewrites a bot card while keeping a
static fallback text changes what the agent reads even though ``text``
compares equal. Link unfurls are deliberately left out: Slack attaches
them to the message on its own, and treating that as a body change would
turn its own re-emit into another turn.
"""
text = str((message or {}).get("text") or "")
blocks = (message or {}).get("blocks") or []
if not blocks:
return text
return "\n".join(
part
for part in (
text,
_extract_text_from_slack_blocks(blocks),
_serialize_slack_blocks_for_agent(blocks),
)
if part
)


def _slack_body_digest(body: str) -> str:
"""Return a fixed-size fingerprint of a rendered message body.

Encoded with ``surrogatepass`` so an unpaired surrogate in a payload
cannot raise.
"""
return hashlib.sha256(body.encode("utf-8", "surrogatepass")).hexdigest()


def _extract_urls_from_slack_blocks(blocks: list) -> list[str]:
"""Walk a Block Kit ``blocks`` tree and return URLs found on any element.

Expand Down Expand Up @@ -984,6 +1019,13 @@ def __init__(self, config: PlatformConfig):
# is later edited.
self._processed_message_ts: Dict[str, float] = {}
self._PROCESSED_MESSAGE_TS_MAX = 5000
# Digest of the message body last seen for a message ts, recorded
# before any await in _handle_slack_message. Lets the message_changed
# branch drop a re-emit whose body is unchanged while
# _processed_message_ts above is still unarmed. Only the digest is
# kept, so a rendered Block Kit payload never stays in memory.
self._seen_message_body_digest: Dict[str, str] = {}
self._SEEN_MESSAGE_BODY_DIGEST_MAX = 5000
# Track pending approval message_ts → resolved flag to prevent
# double-clicks on approval buttons. Bounded: an approval prompt the
# user never clicks would otherwise leak its entry forever. Keys may
Expand Down Expand Up @@ -1147,6 +1189,19 @@ def _discard_oldest_slack_timestamps(
for old_ts in sorted(timestamps, key=cls._slack_timestamp_sort_key)[:count]:
timestamps.discard(old_ts)

def _remember_message_body(self, ts: str, body: str) -> None:
"""Record a digest of the body last seen for *ts* (bounded).

Empty bodies are skipped so that edits to messages carrying only
files are never treated as unchanged.
"""
if not ts or not body:
return
self._seen_message_body_digest[ts] = _slack_body_digest(body)
self._trim_oldest_dict_entries(
self._seen_message_body_digest, self._SEEN_MESSAGE_BODY_DIGEST_MAX
)

def _trim_bot_message_timestamps(self) -> None:
if len(self._bot_message_ts) <= self._BOT_TS_MAX:
return
Expand Down Expand Up @@ -5781,6 +5836,29 @@ async def _handle_slack_message(
and original_message_ts in self._processed_message_ts
):
return
new_message_body = _slack_message_body_signature(updated_message)
if (
original_message_ts
and new_message_body
and self._seen_message_body_digest.get(original_message_ts)
== _slack_body_digest(new_message_body)
):
# Slack re-dispatches message_changed for its own metadata
# updates (async language detection, unfurl) with the body
# byte-identical, typically while the original message is
# still in ingress. Such an event carries nothing new, and
# neither the guard above nor the dedup below stops it: the
# first is armed only after ingress, the second keys on
# _slack_changed_event_ts. An edit that changes the body —
# including one adding a bot mention, in the text or in the
# blocks — still passes.
logger.info(
"[Slack] dropped message_changed with unchanged body "
"ts=%s channel=%s",
original_message_ts,
event.get("channel", ""),
)
return
edited = updated_message.get("edited")
edited_ts = ""
if isinstance(edited, dict):
Expand Down Expand Up @@ -5820,6 +5898,19 @@ async def _handle_slack_message(
logger.info("[Slack] Ignoring message in configured ignored channel %s", channel_id)
return

# Baseline for the unchanged-body guard above. Still ahead of the
# first await, so a message_changed arriving mid-ingress has
# something to compare against, and past the two filters that
# precede it — the redelivery dedup and the ignored-channel check —
# so neither a replay nor an ignored channel takes a slot. The
# sender and content filters below run after this call, so those
# bodies are recorded even though the event is then dropped. After
# normalization ``event`` is the message body, so a let-through edit
# becomes the new baseline.
self._remember_message_body(
str(event.get("ts") or ""), _slack_message_body_signature(event)
)

# Bot/app-authored message filtering (SLACK_ALLOW_BOTS / config
# allow_bots):
# "none" — ignore all bot/app-authored messages (default,
Expand Down
232 changes: 232 additions & 0 deletions tests/gateway/test_slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -1834,6 +1834,38 @@ async def _fake_download(url, ext, audio=False, team_id=""):
# ---------------------------------------------------------------------------


class _IngressGate:
"""Holds ``users.info`` open so a second event races an in-flight ingress.

``entry`` fires when a handler reaches the ingress, ``second_entry`` when
another one does; :meth:`release` lets them all finish.
"""

def __init__(self, adapter):
self.entry = asyncio.Event()
self.second_entry = asyncio.Event()
self._release = asyncio.Event()
self._entered = 0
adapter._app.client.users_info = AsyncMock(side_effect=self._users_info)

async def _users_info(self, *_args, **_kwargs):
self._entered += 1
if self._entered >= 2:
self.second_entry.set()
self.entry.set()
await self._release.wait()
return {
"user": {
"is_bot": False,
"profile": {"display_name": "Test User"},
"real_name": "Test User",
}
}

def release(self) -> None:
self._release.set()


class TestMessageRouting:
@pytest.mark.asyncio
async def test_dm_processed_without_mention(self, adapter):
Expand Down Expand Up @@ -1967,6 +1999,206 @@ async def test_message_edit_with_new_mention_processed(self, adapter):
assert msg_event.text == "whats the rapchat summary for last 12 hours"
assert msg_event.message_id == "1234567890.000001"

@pytest.mark.parametrize("with_blocks", [False, True])
@pytest.mark.asyncio
async def test_metadata_only_edit_during_ingress_routes_once(
self, adapter, with_blocks
):
"""A metadata-only message_changed must not become a second turn.

Slack re-dispatches it with the body untouched while the original is
still in ingress, i.e. before ``_processed_message_ts`` is armed and
with a dedup key of its own. Runs with and without the ``rich_text``
blocks a composed message carries, since they feed the compared body.
"""
gate = _IngressGate(adapter)
loop = asyncio.get_event_loop()

text = "<@U_BOT> check the gateway logs"
body: dict = {
"text": text,
"user": "U_USER",
"channel": "C123",
"ts": "1234567890.000001",
}
if with_blocks:
body["blocks"] = [
{
"type": "rich_text",
"elements": [
{
"type": "rich_text_section",
"elements": [
{"type": "user", "user_id": "U_BOT"},
{"type": "text", "text": " check the gateway logs"},
],
}
],
}
]

original = loop.create_task(
adapter._handle_slack_message(
{
**body,
"channel_type": "channel",
"team": "T123",
}
)
)
await asyncio.wait_for(gate.entry.wait(), 5)

# Same body, new event ts, no ``edited`` marker. Runs as its own task
# because unguarded it blocks in the ingress instead of returning.
reemit = loop.create_task(
adapter._handle_slack_message(
{
"subtype": "message_changed",
"channel": "C123",
"channel_type": "channel",
"team": "T123",
"ts": "1234567891.000000",
"event_ts": "1234567891.000000",
"message": dict(body),
}
)
)
# The guard drops it, so it returns instead of reaching the ingress.
try:
await asyncio.wait_for(reemit, 5)
except asyncio.TimeoutError:
pytest.fail("the re-emit entered the ingress instead of being dropped")
assert not gate.second_entry.is_set()

gate.release()
await asyncio.wait_for(original, 5)

adapter.handle_message.assert_awaited_once()

@pytest.mark.asyncio
async def test_real_edit_during_ingress_still_routes(self, adapter):
"""The guard keys on the body, so a genuine edit is not swallowed."""
gate = _IngressGate(adapter)
loop = asyncio.get_event_loop()

original = loop.create_task(
adapter._handle_slack_message(
{
"text": "<@U_BOT> check the gateway logs",
"user": "U_USER",
"channel": "C123",
"channel_type": "channel",
"team": "T123",
"ts": "1234567890.000001",
}
)
)
await asyncio.wait_for(gate.entry.wait(), 5)

edit = loop.create_task(
adapter._handle_slack_message(
{
"subtype": "message_changed",
"channel": "C123",
"channel_type": "channel",
"team": "T123",
"ts": "1234567891.000000",
"event_ts": "1234567891.000000",
"message": {
"text": "<@U_BOT> check the agent logs instead",
"user": "U_USER",
"channel": "C123",
"ts": "1234567890.000001",
"edited": {"user": "U_USER", "ts": "1234567891.000000"},
},
}
)
)
# Past the unchanged-body guard, both handlers now block on users.info.
await asyncio.wait_for(gate.second_entry.wait(), 5)

gate.release()
await asyncio.wait_for(asyncio.gather(original, edit), 5)

assert adapter.handle_message.await_count == 2

@pytest.mark.asyncio
async def test_block_only_update_during_ingress_still_routes(self, adapter):
"""Blocks reach the agent too, so a static fallback text is not enough."""
gate = _IngressGate(adapter)
loop = asyncio.get_event_loop()

fallback_text = "<@U_BOT> deploy status"

def _card(step: str) -> list:
return [
{
"type": "section",
"text": {"type": "mrkdwn", "text": step},
}
]

original = loop.create_task(
adapter._handle_slack_message(
{
"text": fallback_text,
"blocks": _card("step 1 running"),
"user": "U_USER",
"channel": "C123",
"channel_type": "channel",
"team": "T123",
"ts": "1234567890.000001",
}
)
)
await asyncio.wait_for(gate.entry.wait(), 5)

update = loop.create_task(
adapter._handle_slack_message(
{
"subtype": "message_changed",
"channel": "C123",
"channel_type": "channel",
"team": "T123",
"ts": "1234567891.000000",
"event_ts": "1234567891.000000",
"message": {
"text": fallback_text,
"blocks": _card("step 2 failed"),
"user": "U_USER",
"channel": "C123",
"ts": "1234567890.000001",
},
}
)
)
# The changed blocks pass the guard, so this one reaches the ingress.
await asyncio.wait_for(gate.second_entry.wait(), 5)

gate.release()
await asyncio.wait_for(asyncio.gather(original, update), 5)

assert adapter.handle_message.await_count == 2

@pytest.mark.asyncio
async def test_ignored_channel_body_is_not_remembered(self, adapter):
"""The baseline is not recorded for a channel the adapter ignores."""
adapter.config.extra = {"ignored_channels": ["C_IGN"]}

await adapter._handle_slack_message(
{
"text": "<@U_BOT> check the gateway logs",
"user": "U_USER",
"channel": "C_IGN",
"channel_type": "channel",
"team": "T123",
"ts": "1234567890.000001",
}
)

adapter.handle_message.assert_not_awaited()
assert adapter._seen_message_body_digest == {}


# ---------------------------------------------------------------------------
# TestSendTyping — assistant.threads.setStatus
Expand Down
4 changes: 4 additions & 0 deletions tests/gateway/test_slack_mention.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ def _make_adapter(require_mention=None, strict_mention=None, free_response_chann
adapter.config = PlatformConfig(enabled=True, extra=extra)
adapter._bot_user_id = BOT_USER_ID
adapter._team_bot_user_ids = {}
# Written in _handle_slack_message for the unchanged-body
# message_changed guard.
adapter._seen_message_body_digest = {}
adapter._SEEN_MESSAGE_BODY_DIGEST_MAX = 5000
return adapter


Expand Down
Loading