Skip to content

The agent that grows with you

fix(gateway): preflight task-card destination before transport fallback

Victor Kyriazakosa4e2a82a6d88
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index 43846ee2ae2..1f6db75667f 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -659,6 +659,30 @@ class RelayAdapter(BasePlatformAdapter):
except Exception as e:
return SendResult(success=False, error=f"{op} transport error: {e}")
+ @staticmethod
+ def _task_card_metadata(
+ reply_to: Optional[str], metadata: Optional[Dict[str, Any]],
+ ) -> Dict[str, Any]:
+ merged_meta = dict(metadata or {})
+ if reply_to and "thread_ts" not in merged_meta:
+ # Slack card streams are thread replies anchored on the trigger.
+ merged_meta["thread_ts"] = str(reply_to)
+ return merged_meta
+
+ def native_task_card_destination_supported(
+ self, chat_id: str, *, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> bool:
+ """Check the actual card-frame placement, not its per-turn card identity."""
+ if self._chat_platform(chat_id) != _SLACK:
+ return True
+ md = self._task_card_metadata(reply_to, metadata)
+ # Connector threadTs(): thread_id ?? thread_ts, and only strings thread.
+ thread = md.get("thread_id")
+ if thread is None:
+ thread = md.get("thread_ts")
+ return isinstance(thread, str)
+
async def send_native_task_card_progress(
self,
chat_id: str,
@@ -678,10 +702,7 @@ class RelayAdapter(BasePlatformAdapter):
See #85476.
"""
- merged_meta = dict(metadata or {})
- if reply_to and "thread_ts" not in merged_meta:
- # Slack card streams are thread replies anchored on the trigger.
- merged_meta["thread_ts"] = str(reply_to)
+ merged_meta = self._task_card_metadata(reply_to, metadata)
result = await self._card_frame(
chat_id, "task_card", reply_to, merged_meta, chunks=[dict(t) for t in tasks]
)
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index a1cfea73cfb..6f425138b1a 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -34,16 +34,13 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
-# Card-lane failures that describe the DESTINATION, not a transient outage. Native Slack
-# (`No Slack thread target`) and the relay connector (`slack task_card requires a thread anchor`)
-# both refuse cards for un-threaded chats; the refusal repeats on every event of the turn.
-_CARD_DESTINATION_UNSUPPORTED_MARKERS = ("thread anchor", "thread target")
-
-
-def _card_destination_unsupported(result: Any) -> bool:
- """True when a failed task-card send means this chat cannot host a card at all."""
- error = str(getattr(result, "error", "") or "").lower()
- return any(marker in error for marker in _CARD_DESTINATION_UNSUPPORTED_MARKERS)
+# Exact refusals retained for older adapters/connectors without destination preflight.
+# Substring matching would also silence transient thread-resolution errors.
+_CARD_DESTINATION_REFUSALS = {
+ "No Slack thread target",
+ "slack task_card requires a thread anchor",
+ "slack task_card requires a thread anchor (Slack streams are thread replies)",
+}
def _renders_exec_approval_buttons(adapter_cls: type) -> bool:
@@ -404,6 +401,15 @@ class TurnRunner:
# that cannot host a card); every later publication would re-deliver the
# same task text there.
return
+ # Resolve eligibility in the owning adapter BEFORE transport I/O: a first
+ # timeout/disconnect must not turn an un-cardable chat into text fallback.
+ # Optional for older adapters; only an explicit False refuses publication.
+ destination_supported = getattr(st.adapter, "native_task_card_destination_supported", None)
+ if callable(destination_supported) and destination_supported(
+ ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,
+ ) is False:
+ st.publication_suppressed = True
+ return
if not st.native_failed:
result = await st.adapter.send_native_task_card_progress(
chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title="Hermes is working",
@@ -432,7 +438,7 @@ class TurnRunner:
)
return
st.native_failed = True
- if _card_destination_unsupported(result):
+ if getattr(result, "error", None) in _CARD_DESTINATION_REFUSALS:
# The destination itself cannot host a card (flat DM: no thread anchor). This is
# a property of the chat, not a transient outage, and it repeats on every event.
# The text fallback exists to keep a WORKING card lane live through a transient
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index 9dea15ca998..41d1f70ae71 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -2009,6 +2009,13 @@ class SlackAdapter(BasePlatformAdapter):
return self._workspace_thread_key(
self._metadata_team_id(metadata), chat_id, str(thread_ts))
+ def native_task_card_destination_supported(
+ self, chat_id: str, *, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> bool:
+ """Placement eligibility independent of connection/stream availability."""
+ return self._native_task_card_key(chat_id, reply_to, metadata) is not None
+
async def send_native_task_card_progress(
self, chat_id: str, tasks: List[Dict[str, str]], *, title: str = "Hermes is working",
reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
diff --git a/tests/gateway/test_task_card_destination_preflight.py b/tests/gateway/test_task_card_destination_preflight.py
new file mode 100644
index 00000000000..bbb1bb688b5
--- /dev/null
+++ b/tests/gateway/test_task_card_destination_preflight.py
@@ -0,0 +1,141 @@
+"""Destination eligibility must precede transport failure and its text fallback."""
+
+import queue
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from gateway.config import PlatformConfig
+from gateway.relay.adapter import RelayAdapter
+from gateway.relay.descriptor import CONTRACT_VERSION, CapabilityDescriptor
+from gateway.run_turn_runner import TurnRunner
+from plugins.platforms.slack.adapter import SlackAdapter
+
+
+class CardTransport:
+ def __init__(self, error="relay outbound timed out"):
+ self.error = error
+ self.frames = []
+
+ async def send_outbound(self, payload, platform=None):
+ self.frames.append(payload)
+ if payload["op"] == "task_card":
+ return {"success": False, "error": self.error, "ambiguous": True}
+ return {"success": True, "message_id": "900.1"}
+
+
+def make_adapter(kind, monkeypatch, *, error="relay outbound timed out"):
+ if kind == "native":
+ adapter = SlackAdapter(PlatformConfig(extra={"reply_in_thread": False}))
+ client = SimpleNamespace(
+ api_call=AsyncMock(side_effect=lambda *a, **kw: {"ts": "900.1"}),
+ chat_postMessage=AsyncMock(return_value={"ts": "900.2"}),
+ chat_update=AsyncMock(return_value={"ts": "900.2"}),
+ )
+ monkeypatch.setattr(adapter, "_get_client", Mock(return_value=client))
+ adapter._app = None
+ return adapter, client
+ descriptor = CapabilityDescriptor(
+ contract_version=CONTRACT_VERSION, platform="slack", label="Slack",
+ max_message_length=39000, supports_draft_streaming=True, supports_edit=True,
+ supports_threads=True, markdown_dialect="slack", len_unit="chars",
+ emoji="", platform_hint="", pii_safe=False,
+ supported_ops=("send", "edit", "task_card", "task_card_stop"),
+ )
+ transport = CardTransport(error)
+ adapter = RelayAdapter(PlatformConfig(), descriptor, transport=transport)
+ adapter._platform_by_chat["D1"] = "slack"
+ adapter._chat_type_by_chat["D1"] = "dm"
+ return adapter, transport
+
+
+async def run_progress(adapter, metadata, reply_to, after_first=None):
+ class Events(queue.Queue):
+ def get_nowait(self):
+ event = super().get_nowait()
+ if event["type"] == "tool.completed" and after_first:
+ after_first()
+ return event
+
+ events = Events()
+ for event_type in ("tool.started", "tool.completed", "tool.completed"):
+ events.put({"type": event_type, "tool_call_id": "call-1", "tool_name": "terminal"})
+ ctx = SimpleNamespace(
+ source=SimpleNamespace(chat_id="D1"), _progress_reply_to=reply_to,
+ _progress_metadata=metadata, _cleanup_progress=False, progress_queue=events,
+ _run_still_current=lambda: not events.empty(), agent_holder=[None],
+ )
+ await TurnRunner(None, ctx)._send_native_task_card_progress(adapter)
+
+
[email protected]("kind,metadata,reply_to,eligible", [
+ ("native", {}, None, False),
+ ("native", {"thread_id": "100.1"}, "100.1", False),
+ ("native", {"thread_id": "100.1"}, "100.2", True),
+ ("native", {"thread_ts": "100.1"}, None, True),
+ ("relay", {}, None, False),
+ ("relay", {"message_id": "100.2", "reply_to_message_id": "100.2"}, None, False),
+ ("relay", {"thread_id": "100.1"}, "100.2", True),
+ ("relay", {"thread_ts": "100.1"}, None, True),
+ ("relay", {}, "100.1", True),
+])
+async def test_destination_preflight_survives_transport_recovery(
+ monkeypatch, kind, metadata, reply_to, eligible,
+):
+ adapter, io = make_adapter(kind, monkeypatch)
+ original_metadata = dict(metadata)
+ stop = AsyncMock(wraps=adapter.stop_native_task_card_progress)
+ monkeypatch.setattr(adapter, "stop_native_task_card_progress", stop)
+
+ await run_progress(adapter, metadata, reply_to, lambda: setattr(adapter, "_app", object()))
+
+ stop.assert_awaited_once_with("D1", reply_to=reply_to, metadata=metadata)
+ assert metadata == original_metadata
+ if kind == "native":
+ assert bool(io.chat_postMessage.await_count) is eligible
+ assert bool(io.chat_update.await_count) is eligible
+ io.api_call.assert_not_awaited() # Disconnected first attempt stays on fallback.
+ else:
+ ops = [frame["op"] for frame in io.frames]
+ assert ops == (["task_card", "send", "edit", "edit", "task_card_stop"]
+ if eligible else ["task_card_stop"])
+ if eligible:
+ card = io.frames[0]
+ anchor = card["metadata"].get("thread_id") or card["metadata"].get("thread_ts")
+ assert anchor == (metadata.get("thread_id") or metadata.get("thread_ts") or reply_to)
+
+ # Suppression belongs to this turn, not the adapter: the same chat can host
+ # a later real thread, which still gets native publication and finalization.
+ if not eligible:
+ if kind == "relay":
+ io.frames.clear()
+ await run_progress(adapter, {"thread_id": "200.1"}, "200.2")
+ if kind == "native":
+ methods = [call.args[0] for call in io.api_call.await_args_list]
+ assert methods == ["chat.startStream", "chat.appendStream", "chat.appendStream",
+ "chat.appendStream", "chat.stopStream"]
+ assert not adapter._native_task_card_streams
+ else:
+ assert [frame["op"] for frame in io.frames] == [
+ "task_card", "send", "edit", "edit", "task_card_stop",
+ ]
+
+
[email protected]("error,suppressed", [
+ ("slack task_card requires a thread anchor", True),
+ ("slack task_card requires a thread anchor (Slack streams are thread replies)", True),
+ ("thread anchor lookup timed out", False),
+ ("thread target temporarily unavailable", False),
+])
+async def test_only_explicit_destination_refusals_suppress_threaded_fallback(
+ monkeypatch, error, suppressed,
+):
+ adapter, io = make_adapter("relay", monkeypatch, error=error)
+ await run_progress(adapter, {"thread_id": "100.1"}, "100.2")
+ assert [frame["op"] for frame in io.frames] == (
+ ["task_card", "task_card_stop"] if suppressed
+ else ["task_card", "send", "edit", "edit", "task_card_stop"]
+ )