The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(slack): reopen a native task card when Slack seals the stream mid-turn
Victor Kyriazakos5648f81431d8
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.pyindex fbbf58e118b..330099917ee 100644--- a/plugins/platforms/slack/adapter.py+++ b/plugins/platforms/slack/adapter.py@@ -428,6 +428,19 @@ def _first_truthy(mapping: Dict[str, Any], keys: Tuple[str, ...]) -> Any:return None+def _slack_error_is(exc: BaseException, code: str) -> bool:+ """True when a Slack API exception carries ``code`` as its structured ``error`` field.++ Reads ``exc.response["error"]`` (slack_sdk's SlackApiError shape); never matches on the+ message text, which embeds the whole response body and would match on unrelated codes.+ """+ response = getattr(exc, "response", None)+ try:+ return bool(response) and response.get("error") == code+ except Exception: # noqa: BLE001 - response is a foreign object+ return False++def _slack_str_field(el: dict, name: str) -> str:"""Read a string field of a Block Kit element; non-strings (text objects) would break ``str.join``."""value = el.get(name)@@ -2050,35 +2063,59 @@ class SlackAdapter(BasePlatformAdapter):try:client = self._get_client(chat_id, team_id=stream.team_id)if not stream.stream_ts:- start_payload: Dict[str, Any] = {- "channel": chat_id, "thread_ts": stream.thread_ts,- "task_display_mode": "plan"}- md = metadata or {}- recipients = (- ("recipient_team_id", ("recipient_team_id", "team_id", "slack_team_id")),- ("recipient_user_id", ("recipient_user_id", "user_id")))- for key, sources in recipients:- value = _first_truthy(md, sources)- if value:- start_payload[key] = value- result = await client.api_call("chat.startStream", json=start_payload)- if hasattr(result, "get"):- stream.stream_ts = str(result.get("ts") or result.get("message_ts") or "")- if not stream.stream_ts:- raise RuntimeError("Slack startStream returned no stream timestamp")+ await self._start_native_task_card_stream(client, stream, metadata)chunks: List[Dict[str, Any]] = [{"type": "plan_update", "title": str(title)[:256]}]chunks.extend(self._task_update_chunk(task) for task in tasks)- append_payload: Dict[str, Any] = {- "channel": chat_id, "ts": stream.stream_ts, "chunks": chunks}# chunks-only: Slack rejects markdown_text alongside chunks# (cannot_provide_both_markdown_text_and_chunks, #87743); the gateway owns# the editable-text fallback rail that fallback_text feeds when this call fails.- await client.api_call("chat.appendStream", json=append_payload)+ try:+ await client.api_call(+ "chat.appendStream", json={"channel": chat_id, "ts": stream.stream_ts, "chunks": chunks})+ except Exception as exc:+ if not _slack_error_is(exc, "message_not_in_streaming_state"):+ raise+ # Slack seals a native stream server-side after a few minutes of a long+ # turn (live-observed at ~5m20s, 2026-09-16; the lifetime is not+ # documented). The sealed message is a regular message now, so reopen a+ # fresh card in the same thread. Every frame already carries the FULL+ # visible projection, so nothing is lost; the user sees the card+ # continue instead of degrading to text bubbles. One reopen per update:+ # a second rejection is a real failure.+ logger.info(+ "[Slack] Native task-card stream %s expired (message_not_in_streaming_state); "+ "reopening a fresh card in thread %s", stream.stream_ts, stream.thread_ts)+ stream.stream_ts = ""+ await self._start_native_task_card_stream(client, stream, metadata)+ await client.api_call(+ "chat.appendStream", json={"channel": chat_id, "ts": stream.stream_ts, "chunks": chunks})return SendResult(success=True, message_id=stream.stream_ts)except Exception as exc: # pragma: no cover - defensive logginglogger.error("[Slack] Native task-card progress error: %s", exc, exc_info=True)return SendResult(success=False, error=str(exc), retryable=True)+ @staticmethod+ async def _start_native_task_card_stream(+ client, stream: "_NativeTaskCardStream", metadata: Optional[Dict[str, Any]]+ ) -> None:+ """chat.startStream a plan-mode card in ``stream``'s thread; sets ``stream.stream_ts``."""+ start_payload: Dict[str, Any] = {+ "channel": stream.channel, "thread_ts": stream.thread_ts,+ "task_display_mode": "plan"}+ md = metadata or {}+ recipients = (+ ("recipient_team_id", ("recipient_team_id", "team_id", "slack_team_id")),+ ("recipient_user_id", ("recipient_user_id", "user_id")))+ for key, sources in recipients:+ value = _first_truthy(md, sources)+ if value:+ start_payload[key] = value+ result = await client.api_call("chat.startStream", json=start_payload)+ if hasattr(result, "get"):+ stream.stream_ts = str(result.get("ts") or result.get("message_ts") or "")+ if not stream.stream_ts:+ raise RuntimeError("Slack startStream returned no stream timestamp")+@staticmethoddef _task_update_chunk(task: Dict[str, str]) -> Dict[str, Any]:"""One ``task_update`` stream chunk; unknown statuses coerce to ``in_progress``."""diff --git a/tests/gateway/test_slack.py b/tests/gateway/test_slack.pyindex 31f09038981..3d077a47076 100644--- a/tests/gateway/test_slack.py+++ b/tests/gateway/test_slack.py@@ -5241,6 +5241,87 @@ class TestNativeTaskCardProgress:"rejects the pair and the whole native card fails (#87743)")+ @pytest.mark.asyncio+ async def test_expired_stream_reopens_a_fresh_card_with_the_full_projection(+ self, adapter+ ):+ """Slack seals a native stream server-side after a few minutes of a long+ turn; the next chat.appendStream fails with message_not_in_streaming_state.+ The lane must not degrade to text: seal the dead stream, start a fresh+ card in the same thread carrying the whole current task projection, and+ report success so later updates continue on the new card."""+ from slack_sdk.errors import SlackApiError++ client = adapter._app.client+ starts = 0++ async def api_call(method, *, json):+ nonlocal starts+ if method == "chat.startStream":+ starts += 1+ return {"ts": f"stream-{starts}"}+ if method == "chat.appendStream" and json["ts"] == "stream-1" and starts == 1 and json["chunks"][1]["status"] == "complete":+ raise SlackApiError("expired", {"ok": False, "error": "message_not_in_streaming_state"})+ return {"ok": True}++ client.api_call.side_effect = api_call+ metadata = {"thread_id": "thread-1"}+ running = [{"id": "call-1", "title": "terminal", "status": "in_progress"}]+ done = [+ {"id": "call-1", "title": "terminal", "status": "complete"},+ {"id": "call-2", "title": "web_search", "status": "in_progress"},+ ]++ first = await adapter.send_native_task_card_progress("C1", running, metadata=metadata)+ second = await adapter.send_native_task_card_progress("C1", done, metadata=metadata)++ assert first.success is True and first.message_id == "stream-1"+ assert second.success is True and second.message_id == "stream-2"+ methods = [(c.args[0], c.kwargs["json"]["ts"] if "ts" in c.kwargs["json"] else None) for c in client.api_call.await_args_list]+ assert methods == [+ ("chat.startStream", None),+ ("chat.appendStream", "stream-1"),+ ("chat.appendStream", "stream-1"), # rejected: expired+ ("chat.startStream", None),+ ("chat.appendStream", "stream-2"),+ ]+ reopened = client.api_call.await_args_list[-1].kwargs["json"]["chunks"]+ assert [(c["id"], c["status"]) for c in reopened if c["type"] == "task_update"] == [+ ("call-1", "complete"), ("call-2", "in_progress"),+ ]+ # No stopStream on the dead ts (Slack already sealed it) and the cache now points at the new card.+ assert all(c.args[0] != "chat.stopStream" for c in client.api_call.await_args_list)+ (stream,) = adapter._native_task_card_streams.values()+ assert stream.stream_ts == "stream-2" and stream.stopped is False++ await adapter.stop_native_task_card_progress("C1", metadata=metadata)+ stop = client.api_call.await_args_list[-1]+ assert stop.args[0] == "chat.stopStream" and stop.kwargs["json"]["ts"] == "stream-2"+ assert adapter._native_task_card_streams == {}++ @pytest.mark.asyncio+ async def test_expired_stream_reopen_gives_up_after_one_retry(self, adapter):+ """A reopened card that is itself rejected as not-streaming is a real+ failure, not a loop: one reopen per update, then the failure surfaces."""+ from slack_sdk.errors import SlackApiError++ client = adapter._app.client++ async def api_call(method, *, json):+ if method == "chat.startStream":+ return {"ts": "stream-x"}+ raise SlackApiError("expired", {"ok": False, "error": "message_not_in_streaming_state"})++ client.api_call.side_effect = api_call+ result = await adapter.send_native_task_card_progress(+ "C1", [{"id": "call-1", "title": "terminal", "status": "in_progress"}], metadata={"thread_id": "thread-1"},+ )++ assert result.success is False+ assert [c.args[0] for c in client.api_call.await_args_list] == [+ "chat.startStream", "chat.appendStream", "chat.startStream", "chat.appendStream",+ ]+# ---------------------------------------------------------------------------# TestSlackAuthoredTextDeduplicationdiff --git a/website/docs/user-guide/messaging/slack.md b/website/docs/user-guide/messaging/slack.mdindex d07e4ad58e6..5c3c018acce 100644--- a/website/docs/user-guide/messaging/slack.md+++ b/website/docs/user-guide/messaging/slack.md@@ -599,6 +599,9 @@ platforms:recoverable reason (API error, rate limit), Hermes falls back to a single continuously edited text message soprogress stays live for the turn. A relay egress refusal of the destinationis not recoverable and suppresses progress for the turn.+- If Slack closes a stream during a long turn, Hermes opens a fresh card in+ the same thread with the current task list and keeps updating there. The+ previous card remains visible.- The card stream is stopped exactly once when the turn finalizes, includingon interrupt/disconnect, so no dangling live indicator is left behind.