Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
206 changes: 206 additions & 0 deletions gateway/platforms/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,18 @@ class _ThreadContextCache:
parent_text: str = "" # Raw text of the thread parent (for reply_to_text injection)


@dataclass
class _SlackNativeStreamState:
"""Bookkeeping for one active Slack chat.*Stream message."""

channel: str
ts: str
thread_ts: Optional[str]
user_id: str
team_id: str
last_text: str = ""


def check_slack_requirements() -> bool:
"""Check if Slack dependencies are available.

Expand Down Expand Up @@ -373,6 +385,11 @@ def __init__(self, config: PlatformConfig):
# Socket Mode resilience: track runtime connection state so we can
# self-heal when Slack silently drops the websocket.
self._app_token: Optional[str] = None
# Active Slack-native chat.*Stream messages keyed by (chat_id, thread_ts).
# The generic gateway stream consumer calls send_draft() with cumulative
# preview text and later calls send() for the final answer; send() stops
# the matching stream instead of posting a duplicate final message.
self._native_streams: Dict[Tuple[str, str], _SlackNativeStreamState] = {}
self._proxy_url: Optional[str] = None
self._socket_watchdog_task: Optional[asyncio.Task] = None
self._socket_reconnect_lock = asyncio.Lock()
Expand Down Expand Up @@ -1127,6 +1144,187 @@ def _get_client(self, chat_id: str) -> Any:
return self._team_clients[team_id]
return self._app.client # fallback to primary

@staticmethod
def _native_stream_key(
chat_id: str,
thread_ts: Optional[str],
) -> Tuple[str, str]:
return (str(chat_id or ""), str(thread_ts or ""))

def _clean_native_stream_text(self, content: str) -> str:
"""Convert Hermes' cumulative preview text into Slack stream text."""
text = self.format_message(content or "")
# The generic stream consumer appends a visual cursor for edit-based
# transports. Slack's native stream UI has its own in-progress affordance,
# so strip the common cursor glyph if it is present at the tail.
return re.sub(r"\s*▉\s*$", "", text)

def _slack_stream_team_id(self, chat_id: str, metadata: Optional[Dict[str, Any]]) -> str:
md = metadata or {}
return str(md.get("team_id") or self._channel_team.get(chat_id, "") or "")

def supports_draft_streaming(
self,
chat_type: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""Use Slack's native chat.*Stream APIs when routing data is available.

The gateway's draft transport passes cumulative preview frames through
send_draft(). Slack's native stream API is append-only, but it provides
exactly the right UX. We only opt in when the SDK exposes the new methods
and the gateway supplied the Slack user id needed by chat.startStream.
send_draft() resolves team_id from the channel map, because the support
probe does not receive chat_id.
"""
if not self._app:
return False
if not hasattr(self._get_client(""), "chat_startStream"):
return False
md = metadata or {}
return bool(str(md.get("user_id") or ""))

async def send_draft(
self,
chat_id: str,
draft_id: int,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> SendResult:
"""Append a frame to Slack's native chat.*Stream message.

The generic gateway stream consumer calls send_draft() with cumulative
text. Slack wants incremental markdown chunks, so this method diffs the
new preview against the last accepted preview and appends only the tail.
The matching final send() later calls chat.stopStream.
"""
if not self._app:
return SendResult(success=False, error="Not connected")

md = metadata or {}
thread_ts = self._resolve_thread_ts(None, md)
user_id = str(md.get("user_id") or "")
team_id = self._slack_stream_team_id(chat_id, md)
if not thread_ts:
return SendResult(success=False, error="Slack stream requires thread_ts")
if not user_id or not team_id:
return SendResult(
success=False,
error="Slack stream requires recipient user_id and team_id",
)

key = self._native_stream_key(chat_id, thread_ts)
text = self._clean_native_stream_text(content)
if not text.strip():
return SendResult(success=True)

try:
client = self._get_client(chat_id)
state = self._native_streams.get(key)
if state is None:
result = await client.chat_startStream(
channel=chat_id,
thread_ts=thread_ts,
recipient_user_id=user_id,
recipient_team_id=team_id,
markdown_text=text,
)
stream_ts = str(result.get("ts") or "")
if not stream_ts:
return SendResult(success=False, error="chat.startStream did not return ts")
state = _SlackNativeStreamState(
channel=chat_id,
ts=stream_ts,
thread_ts=thread_ts,
user_id=user_id,
team_id=team_id,
last_text=text,
)
self._native_streams[key] = state
self._bot_message_ts.add(stream_ts)
self._bot_message_ts.add(thread_ts)
logger.debug(
"[Slack] Started native stream channel=%s thread=%s ts=%s",
chat_id,
thread_ts,
stream_ts,
)
return SendResult(success=True, message_id=stream_ts, raw_response=result)

if text == state.last_text:
return SendResult(success=True, message_id=state.ts)
if text.startswith(state.last_text):
delta = text[len(state.last_text):]
else:
# Slack streams are append-only. If markdown cleanup changed bytes
# already sent, append a separated current frame rather than
# raising and losing the rest of the response.
delta = "\n" + text
if delta:
result = await client.chat_appendStream(
channel=chat_id,
ts=state.ts,
markdown_text=delta,
)
state.last_text = text
logger.debug(
"[Slack] Appended native stream channel=%s thread=%s ts=%s chars=%d",
chat_id,
thread_ts,
state.ts,
len(delta),
)
return SendResult(success=True, message_id=state.ts, raw_response=result)
return SendResult(success=True, message_id=state.ts)
except Exception as e: # pragma: no cover - defensive logging
logger.error("[Slack] chat.*Stream append error: %s", e, exc_info=True)
self._native_streams.pop(key, None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If chat_appendStream fails after chat_startStream succeeded, dropping this state prevents the subsequent edit-path fallback from finding and stopping the live native stream. Best-effort chat_stopStream before clearing the entry, and add a regression test for an append failure after a successful start.

return SendResult(success=False, error=str(e))

async def _stop_native_stream_if_active(
self,
chat_id: str,
content: str,
metadata: Optional[Dict[str, Any]] = None,
) -> Optional[SendResult]:
"""Stop an active chat.*Stream instead of posting a duplicate final."""
md = metadata or {}
thread_ts = self._resolve_thread_ts(None, md)
if not thread_ts:
return None
key = self._native_stream_key(chat_id, thread_ts)
state = self._native_streams.pop(key, None)
if state is None:
return None

final_text = self._clean_native_stream_text(content)
try:
client = self._get_client(chat_id)
if final_text and final_text != state.last_text:
if final_text.startswith(state.last_text):
delta = final_text[len(state.last_text):]
else:
delta = "\n" + final_text
if delta:
await client.chat_appendStream(
channel=chat_id,
ts=state.ts,
markdown_text=delta,
)
state.last_text = final_text
result = await client.chat_stopStream(channel=chat_id, ts=state.ts)
await self.stop_typing(chat_id)
logger.debug(
"[Slack] Stopped native stream channel=%s thread=%s ts=%s",
chat_id,
thread_ts,
state.ts,
)
return SendResult(success=True, message_id=state.ts, raw_response=result)
except Exception as e: # pragma: no cover - defensive logging
logger.error("[Slack] chat.stopStream error: %s", e, exc_info=True)
return SendResult(success=False, error=str(e))

async def send(
self,
chat_id: str,
Expand All @@ -1139,6 +1337,14 @@ async def send(
return SendResult(success=False, error="Not connected")

try:
native_stream_result = await self._stop_native_stream_if_active(
chat_id,
content,
metadata,
)
if native_stream_result is not None:
return native_stream_result

# Check for a pending slash-command context. When the user ran a
# native slash command (e.g. /q, /stop, /model), the initial ack
# already showed an ephemeral "Running /cmd…" message. If we have
Expand Down
12 changes: 11 additions & 1 deletion gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -11499,13 +11499,23 @@ def _thread_metadata_for_source(
reply_to_message_id: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Build the metadata dict platforms need for thread-aware replies."""
return self._thread_metadata_for_target(
metadata = self._thread_metadata_for_target(
getattr(source, "platform", None),
getattr(source, "chat_id", None),
getattr(source, "thread_id", None),
chat_type=getattr(source, "chat_type", None),
reply_to_message_id=reply_to_message_id or getattr(source, "message_id", None),
)
if metadata is not None and getattr(source, "platform", None) == Platform.SLACK:
user_id = getattr(source, "user_id", None)
if user_id:
metadata["user_id"] = str(user_id)
chat_id = getattr(source, "chat_id", None)
adapter = self.adapters.get(Platform.SLACK)
team_id = getattr(adapter, "_channel_team", {}).get(chat_id) if adapter else None
if team_id:
metadata["team_id"] = str(team_id)
return metadata

def _thread_metadata_for_target(
self,
Expand Down
90 changes: 90 additions & 0 deletions tests/gateway/test_slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,6 +1974,96 @@ async def test_streaming_intermediate_edit_keeps_status(self, adapter):
assert adapter._active_status_threads["C123"] == "parent_ts"


# ---------------------------------------------------------------------------
# TestNativeSlackStreaming
# ---------------------------------------------------------------------------


class TestNativeSlackStreaming:
def test_requires_user_metadata_for_native_streaming(self, adapter):
adapter._app.client.chat_startStream = AsyncMock()

assert not adapter.supports_draft_streaming(metadata={"thread_id": "parent_ts"})
assert adapter.supports_draft_streaming(
metadata={"thread_id": "parent_ts", "user_id": "U123"}
)

@pytest.mark.asyncio
async def test_send_draft_start_append_and_final_send_stops_stream(self, adapter):
adapter._channel_team["C123"] = "T123"
adapter._app.client.chat_startStream = AsyncMock(return_value={"ts": "stream_ts"})
adapter._app.client.chat_appendStream = AsyncMock(return_value={"ok": True})
adapter._app.client.chat_stopStream = AsyncMock(return_value={"ok": True})
adapter._app.client.chat_postMessage = AsyncMock(return_value={"ts": "posted_ts"})
adapter._app.client.assistant_threads_setStatus = AsyncMock()
adapter._active_status_threads["C123"] = "parent_ts"
metadata = {"thread_id": "parent_ts", "user_id": "U123"}

first = await adapter.send_draft("C123", 1, "Hel ▉", metadata=metadata)
second = await adapter.send_draft("C123", 1, "Hello ▉", metadata=metadata)
final = await adapter.send("C123", "Hello", metadata=metadata)

assert first.success
assert second.success
assert final.success
assert final.message_id == "stream_ts"
adapter._app.client.chat_startStream.assert_awaited_once_with(
channel="C123",
thread_ts="parent_ts",
recipient_user_id="U123",
recipient_team_id="T123",
markdown_text="Hel",
)
adapter._app.client.chat_appendStream.assert_awaited_once_with(
channel="C123",
ts="stream_ts",
markdown_text="lo",
)
adapter._app.client.chat_stopStream.assert_awaited_once_with(
channel="C123",
ts="stream_ts",
)
adapter._app.client.chat_postMessage.assert_not_called()
adapter._app.client.assistant_threads_setStatus.assert_awaited_once_with(
channel_id="C123",
thread_ts="parent_ts",
status="",
)
assert not adapter._native_streams

@pytest.mark.asyncio
async def test_send_draft_rejects_missing_team_id_without_starting_stream(self, adapter):
adapter._app.client.chat_startStream = AsyncMock(return_value={"ts": "stream_ts"})

result = await adapter.send_draft(
"C123",
1,
"Hello ▉",
metadata={"thread_id": "parent_ts", "user_id": "U123"},
)

assert not result.success
assert "team_id" in result.error
adapter._app.client.chat_startStream.assert_not_called()
assert not adapter._native_streams

@pytest.mark.asyncio
async def test_send_draft_api_error_clears_active_stream_for_edit_fallback(self, adapter):
adapter._channel_team["C123"] = "T123"
adapter._app.client.chat_startStream = AsyncMock(side_effect=Exception("missing_scope"))

result = await adapter.send_draft(
"C123",
1,
"Hello ▉",
metadata={"thread_id": "parent_ts", "user_id": "U123"},
)

assert not result.success
assert "missing_scope" in result.error
assert not adapter._native_streams


# ---------------------------------------------------------------------------
# TestFormatMessage — Markdown → mrkdwn conversion
# ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion website/docs/user-guide/messaging/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Bots need both a model provider and tool providers (TTS, web). A [Nous Portal](/
| LINE | — | ✅ | ✅ | — | — | ✅ | — |
| ntfy | — | — | — | — | — | — | — |

**Voice** = TTS audio replies and/or voice message transcription. **Images** = send/receive images. **Files** = send/receive file attachments. **Threads** = threaded conversations. **Reactions** = emoji reactions on messages. **Typing** = typing indicator while processing. **Streaming** = progressive message updates via editing.
**Voice** = TTS audio replies and/or voice message transcription. **Images** = send/receive images. **Files** = send/receive file attachments. **Threads** = threaded conversations. **Reactions** = emoji reactions on messages. **Typing** = typing indicator while processing. **Streaming** = progressive message updates; most adapters use message editing, while adapters with native streaming APIs (for example Slack `chat.*Stream`) may use the platform-native streaming UI.

## Architecture

Expand Down
14 changes: 14 additions & 0 deletions website/docs/user-guide/messaging/slack.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ the steps below.
| **Auth tokens needed** | Bot Token (`xoxb-`) + App-Level Token (`xapp-`) |
| **User identification** | Slack Member IDs (e.g., `U01ABC2DEF3`) |

### Streaming replies

Hermes can progressively stream Slack replies. When `streaming.enabled: true`, the Slack adapter prefers Slack's native `chat.startStream` → `chat.appendStream` → `chat.stopStream` API when the installed `slack_sdk` exposes those methods and the incoming event has the recipient user/team metadata Slack requires. If native streaming is unavailable or Slack rejects the stream call (for example because of an older SDK, missing API support, or missing routing metadata), Hermes falls back to the older edit-based streaming path (`chat.postMessage` + `chat.update`).

Native Slack streaming uses the same gateway configuration as other platform streaming:

```yaml
streaming:
enabled: true
transport: auto # prefer native streaming where supported, fall back to edits
```

No extra OAuth scope is currently required beyond `chat:write`, but the app still needs the normal Slack setup below so Hermes can receive the user's message and resolve the channel, user, team, and thread IDs.

---

## Step 1: Create a Slack App
Expand Down