Skip to content

The agent that grows with you

fix(relay): route force-on-unfurl streamed finals through fresh chat.postMessage

Victor Kyriazakoscef4c88f7163
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index b11abd33715..a53e4c12e6f 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -20,6 +20,7 @@ from __future__ import annotations
import asyncio
import logging
+import re
import secrets
import time
from collections import OrderedDict
@@ -42,6 +43,12 @@ logger = logging.getLogger(__name__)
_RELAY_GO_IDLE_ON_DISCONNECT_TIMEOUT_S = 2.0
_RELAY_REVOCATION_MONITOR_TEARDOWN_TIMEOUT_S = 1.0
+# Link detection for the fresh-final unfurl route: raw http(s) URLs, Slack
+# mrkdwn link syntax (<https://...|label>), and markdown links. Cheap and
+# permissive on purpose — a false positive costs one fresh (non-edited)
+# final message; a false negative silently loses the preview.
+_URL_RE = re.compile(r"https?://|<https?:|\]\(https?:")
+
# How many already-answered prompt ids to remember, so a duplicate answer for
# one of them (a double tap, or a connector redelivery of the same forward) is
# recognized as a repeat rather than mistaken for a stale prompt. One short
@@ -335,6 +342,55 @@ class RelayAdapter(BasePlatformAdapter):
return False
return True
+ def prefers_fresh_final_streaming(
+ self,
+ content: str,
+ metadata: Optional[Dict[str, Any]] = None,
+ chat_id: Optional[str] = None,
+ ) -> bool:
+ """Deliver streamed finals as a FRESH send when Slack unfurl is forced on.
+
+ Slack evaluates link previews exactly once, at ``chat.postMessage``
+ time (live-probed 2026-08-28: URL at post + ``unfurl_links: true``
+ unfurls; a ``chat.update`` that INTRODUCES the URL never does, stamps
+ or not). Edit-based streaming posts its first frame before the model
+ has produced any URL — a tool-progress card or an early text frame —
+ so a configured ``unfurl_links/media: true`` can never surface a
+ preview through the edit lane: the only post Slack evaluates has no
+ link in it.
+
+ Returning True routes the completed reply through the consumer's
+ fresh-final path: one new ``send`` carrying the full content, which
+ ``send()`` stamps with the unfurl hints — URL and flags present at
+ the single moment Slack looks.
+
+ Scope: ONLY when the hints contain an explicit True. False-only
+ hints (the enterprise fail-closed posture) keep the edit lane —
+ suppression rides the placeholder post and an edit can never add a
+ preview afterwards, so ``false`` inherits correctly with zero
+ streaming-UX cost.
+ """
+ platform = None
+ if chat_id is not None:
+ platform = self._platform_by_chat.get(str(chat_id))
+ # The stream consumer's hook call passes (content, metadata=...) only
+ # — no chat_id — so resolve through the turn metadata's platform when
+ # present before falling back to the primary descriptor.
+ if platform is None and isinstance(metadata, dict):
+ platform = metadata.get("platform")
+ if platform is None:
+ platform = getattr(self.descriptor, "platform", None)
+ hints = self._slack_unfurl_hints(platform)
+ if not hints:
+ return False
+ if not any(v is True for v in hints.values()):
+ return False
+ # Only link-bearing finals benefit: without a URL there is nothing to
+ # unfurl, and the relay has no delete op (connector contract v1), so
+ # the streamed preview stays behind the fresh final. Keep the edit
+ # lane for linkless replies to avoid a pointless duplicate message.
+ return bool(_URL_RE.search(content or ""))
+
def stream_is_message_for_chat(self, chat_id: str) -> bool:
"""Per-chat stream-is-the-message semantic (review r2, finding 2).
diff --git a/tests/gateway/relay/test_relay_slack_unfurl.py b/tests/gateway/relay/test_relay_slack_unfurl.py
index b6d43a1ca26..c730c84b98a 100644
--- a/tests/gateway/relay/test_relay_slack_unfurl.py
+++ b/tests/gateway/relay/test_relay_slack_unfurl.py
@@ -254,3 +254,159 @@ class TestUnfurlDisablesDraftStreaming:
transport=_CaptureTransport(),
)
assert a.supports_draft_streaming() is False
+
+
+class TestFreshFinalForForceOnUnfurl:
+ """Slack evaluates unfurls ONLY at chat.postMessage (live-probed
+ 2026-08-28: an edit that introduces a URL never previews, stamped or
+ not). Force-on hints must therefore route streamed finals through the
+ consumer's fresh-final path; false-only hints must NOT (suppression
+ rides the placeholder post and inherits through edits)."""
+
+ def _adapter(self, slack_extra):
+ return RelayAdapter(
+ PlatformConfig(extra={"slack": slack_extra}),
+ make_desc(
+ platform="slack",
+ supports_draft_streaming=True,
+ supported_ops=("send", "draft"),
+ ),
+ transport=_CaptureTransport(),
+ )
+
+ def test_force_on_with_link_prefers_fresh_final(self):
+ a = self._adapter({"unfurl_links": True, "unfurl_media": True})
+ assert (
+ a.prefers_fresh_final_streaming("see https://studiotwin.ai") is True
+ )
+
+ def test_force_on_string_true_prefers_fresh_final(self):
+ # hermes config set / Railway knobs persist YAML strings.
+ a = self._adapter({"unfurl_links": "true"})
+ assert a.prefers_fresh_final_streaming("see https://x.dev") is True
+
+ def test_force_on_mrkdwn_link_prefers_fresh_final(self):
+ a = self._adapter({"unfurl_links": True})
+ assert (
+ a.prefers_fresh_final_streaming("see <https://x.dev|x.dev>") is True
+ )
+
+ def test_force_on_without_link_keeps_edit_lane(self):
+ # No URL => nothing to unfurl; a fresh final would only duplicate
+ # the preview (relay contract v1 has no delete op).
+ a = self._adapter({"unfurl_links": True})
+ assert a.prefers_fresh_final_streaming("plain text answer") is False
+
+ def test_false_only_hints_keep_edit_lane(self):
+ # Enterprise fail-closed posture: suppression is decided at the
+ # placeholder post; the edit lane preserves it. No UX change.
+ a = self._adapter({"unfurl_links": False, "unfurl_media": False})
+ assert (
+ a.prefers_fresh_final_streaming("see https://studiotwin.ai") is False
+ )
+
+ def test_unconfigured_keeps_edit_lane(self):
+ a = self._adapter({})
+ assert (
+ a.prefers_fresh_final_streaming("see https://studiotwin.ai") is False
+ )
+
+ def test_non_slack_platform_keeps_edit_lane(self):
+ a = RelayAdapter(
+ PlatformConfig(extra={"slack": {"unfurl_links": True}}),
+ make_desc(
+ platform="telegram",
+ supports_draft_streaming=True,
+ supported_ops=("send", "draft"),
+ ),
+ transport=_CaptureTransport(),
+ )
+ assert (
+ a.prefers_fresh_final_streaming("see https://studiotwin.ai") is False
+ )
+
+
+class _RecordingTransport(_CaptureTransport):
+ """Capture EVERY outbound action in order, not just the last."""
+
+ def __init__(self):
+ super().__init__()
+ self.actions = []
+
+ async def send_outbound(self, action, *, platform=None):
+ self.actions.append(action)
+ self.sent = action
+ self.sent_platform = platform
+ return {"success": True, "message_id": f"m{len(self.actions)}"}
+
+
+class TestConsumerRoutesForceOnFinalAsFreshSend:
+ """End-to-end consumer contract (the lane the live regression hid in):
+ an edit-streamed turn whose URL only exists in the FINAL text must
+ finalize via a fresh `send` op carrying the unfurl stamps — not via an
+ `edit` op, which Slack never re-evaluates for previews."""
+
+ @pytest.mark.asyncio
+ async def test_url_arriving_late_finalizes_as_stamped_fresh_send(self):
+ from gateway.stream_consumer import (
+ GatewayStreamConsumer,
+ StreamConsumerConfig,
+ )
+
+ transport = _RecordingTransport()
+ a = RelayAdapter(
+ PlatformConfig(extra={"slack": {"unfurl_links": True, "unfurl_media": True}}),
+ make_desc(platform="slack", supports_edit=True),
+ transport=transport,
+ )
+ consumer = GatewayStreamConsumer(
+ adapter=a,
+ chat_id="D1",
+ config=StreamConsumerConfig(),
+ )
+ # Frame 1: placeholder posts WITHOUT any URL (the task-card /
+ # early-frame shape from the live regression).
+ await consumer._send_or_edit("Working on it…")
+ # Final: the URL exists only now.
+ await consumer._send_or_edit(
+ "see https://studiotwin.ai", finalize=True
+ )
+
+ ops = [x.get("op") for x in transport.actions]
+ # Placeholder went out as a send; the FINAL must be a fresh send
+ # too (not an edit) so Slack evaluates the preview with the URL
+ # present.
+ assert ops[0] == "send"
+ assert ops[-1] == "send", f"final left as {ops[-1]!r}; ops={ops}"
+ final = transport.actions[-1]
+ assert final["content"] == "see https://studiotwin.ai"
+ assert final["metadata"]["unfurl_links"] is True
+ assert final["metadata"]["unfurl_media"] is True
+
+ @pytest.mark.asyncio
+ async def test_false_only_hints_finalize_via_edit_unchanged(self):
+ from gateway.stream_consumer import (
+ GatewayStreamConsumer,
+ StreamConsumerConfig,
+ )
+
+ transport = _RecordingTransport()
+ a = RelayAdapter(
+ PlatformConfig(extra={"slack": {"unfurl_links": False, "unfurl_media": False}}),
+ make_desc(platform="slack", supports_edit=True),
+ transport=transport,
+ )
+ consumer = GatewayStreamConsumer(
+ adapter=a,
+ chat_id="D1",
+ config=StreamConsumerConfig(),
+ )
+ await consumer._send_or_edit("Working on it…")
+ await consumer._send_or_edit("see https://studiotwin.ai", finalize=True)
+
+ ops = [x.get("op") for x in transport.actions]
+ # Fail-closed posture keeps the edit lane: placeholder send (which
+ # carries the false stamps at post time) + finalize edit.
+ assert ops[0] == "send"
+ assert transport.actions[0]["metadata"]["unfurl_links"] is False
+ assert ops[-1] == "edit", f"ops={ops}"