fix(slack): reopen a native task card when Slack seals the stream mid-turn
Slack seals a native stream server-side after a few minutes (live-observed at ~5m20s on three independent long turns, 2026-09-15/16; the lifetime is not documented). The next chat.appendStream on the card fails with message_not_in_streaming_state. The adapter returned a bare failure, the TurnRunner latched native_failed, and the rest of the turn rendered as an edited text bullet list. Long autonomous turns lost the card UX exactly when it mattered. On message_not_in_streaming_state from appendStream, drop the dead stream_ts and chat.startStream a fresh plan-mode card in the same thread, then append the current frame there. Every frame already carries the full visible task projection, so no task state is lost. One reopen per update; a second rejection surfaces as a real failure. The sealed card is a plain message now, so no stopStream is sent to it; the turn-final stop targets the reopened card. Error matching reads SlackApiError.response["error"], never the message text. Tests assert the wire sequence (start, append, rejected append, start, append on the new ts), the reopened frame's task states, the cache pointing at the new card, and the stop targeting it; plus the one-reopen bound. Mutation: forcing the expiry branch off turns both tests red.
This commit is contained in:
1 parent
9dda4332f8
commit
5648f81431
3 files changed
+140
-19
No files matched your search
@@ -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 logging
|
||||
logger.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")
|
||||
|
||||
@staticmethod
|
||||
def _task_update_chunk(task: Dict[str, str]) -> Dict[str, Any]:
|
||||
"""One ``task_update`` stream chunk; unknown statuses coerce to ``in_progress``."""
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TestSlackAuthoredTextDeduplication
|
||||
|
||||
@@ -599,6 +599,9 @@ platforms:
|
||||
recoverable reason (API error, rate limit), Hermes falls back to a single continuously edited text message so
|
||||
progress stays live for the turn. A relay egress refusal of the destination
|
||||
is 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, including
|
||||
on interrupt/disconnect, so no dangling live indicator is left behind.
|
||||
|
||||
|
||||
Reference in new issue
Block a user