The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(relay): live-card ops — native draft streaming + task cards over the relay (gateway half) (#85796)
victor-kyriazakos3683e700439b
diff --git a/AGENTS.md b/AGENTS.mdindex b8a22cf7eb9..93705624e3a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1342,6 +1342,47 @@ while the agent is blocked (e.g. approval prompts) MUST bypass BOTHguards and be dispatched inline, not via `_process_message_background()`(which races session lifecycle).+### Streaming delivery contract (stream-is-the-message adapters) — duplicate-final class+Adapters with `draft_stream_is_message = True` (relay Slack native streaming)+keep ONE cumulative native stream per turn; the stream IS the final message.+Four invariants, each learned from a live duplicate-final incident (NS-658+canary ledger, hermes#85796 / gateway-gateway#210). Violating any of them+re-creates a duplicate or a frozen stream:++1. **Draft frames must be prefix-stable.** The connector computes append-only+ deltas: frame N must be a string prefix of frame N+1. NEVER mutate draft+ frames per-tick — no fence-closing (`ensure_closed_code_fences`), no cursor+ suffix, no segment-state resets at tool boundaries, no mrkdwn conversion.+ Any non-prefix frame triggers a whole-snapshot re-append on the platform+ ("stacked copies"). The finalize path may still transform the real final.+2. **The consumer declares the final; the adapter never guesses.**+ `finish(final_text)` carries the completed `final_response` (verifier+ footer, completion explainer included) as the authoritative finalize+ payload. New post-stream response augmentation MUST ride this payload —+ if it mutates `final_response` after the stream sealed, it re-opens the+ #11 bug (`delivered_final_matches` mismatch → corrective duplicate send).+3. **Interim sends must carry `_interim_send` metadata.** Any consumer-side+ `adapter.send()` that is NOT the turn-final (commentary, segment-tail+ flushes) must set `metadata["_interim_send"] = True`, or the relay+ adapter's seal-interception will seal the live stream with interim text.+ Seal-interception exists at BOTH egress doors (`send()` AND+ `send_for_platform()`); a new egress door needs the same two checks.+4. **Reconcile by edit, never by plain send.** Any lane that delivers a final+ beside an already-sealed stream (queued follow-ups, media-accompanied+ finals, future lanes) must first try `edit_message` on the consumer's+ `message_id`; plain `send()` is the fallback only when no editable message+ exists. A sealed native stream is a regular message — `chat.update` on it+ works (live-verified).++Contract tests: `tests/gateway/test_stream_final_contract.py` (all four+invariants, mutation-checked). Slack streaming API ground truth (live-probed,+also encoded in connector comments/tests): `chat.*Stream` speaks STANDARD+markdown, not mrkdwn; `stopStream.markdown_text` APPENDS (never replaces);+`startStream`/`stopStream` are rate-limit Tier 2 (~20/min).++Guard style note: check `draft_stream_is_message` with `is True` — MagicMock+adapters in older tests auto-create truthy attributes.+### Squash merges from stale branches silently revert recent fixesBefore squash-merging a PR, ensure the branch is up to date with `main`(`git fetch origin main && git reset --hard origin/main` in the worktree,diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 070db6e4e2e..6bae26aa052 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3224,6 +3224,7 @@ class BasePlatformAdapter(ABC):self,chat_type: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,+ chat_id: Optional[str] = None,) -> bool:"""Whether this adapter supports native streaming-draft updates.@@ -3233,6 +3234,10 @@ class BasePlatformAdapter(ABC):``send_draft`` should return True here for the chat types where theplatform supports it (Telegram restricts drafts to private DMs).+ ``chat_id`` lets multi-platform adapters (relay) resolve the answer+ through the chat's own negotiated capability profile instead of the+ primary identity's; single-platform adapters may ignore it.+Default implementation returns False. Stream consumers fall back tothe edit-based path (``send`` + ``edit_message``) when this returnsFalse or when ``send_draft`` raises.diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 10cec8775d5..7a3ae50dd36 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -95,6 +95,41 @@ class RelayAdapter(BasePlatformAdapter):# feedback off SendResult — see send()). Consumed by the gateway's# semantic thread-rename lane; bounded like the sibling caches.self._auto_thread_by_chat: Dict[str, Tuple[str, str]] = {}+ # chat_id -> draft_id of the currently OPEN native draft stream+ # (NS-658 live cards). Armed by send_draft on a successful frame;+ # consumed by send() to convert the turn-final delivery into the+ # sealing draft(final=true) frame instead of a duplicate post.+ # Keyed by _draft_key (chat + per-turn identity), NOT bare chat:+ # parallel turns in one DM are distinct streams (live finding #10 —+ # per-chat keying collided three concurrent turns: merged task+ # cards, clobbered seal state, 3x duplicate finals).+ self._open_draft_by_chat: Dict[str, int] = {}+ # chat_id -> draft_id of the most recently SEALED stream (gateway+ # mirror of the connector's sealed-key tombstone): post-seal+ # straggler frames must neither re-arm interception nor re-open a+ # stream. One entry per turn key; a NEW turn's fresh draft_id+ # differs, so it arms normally and writes its own tombstone at its+ # own seal. Bounded like the sibling caches (see send_draft).+ self._sealed_draft_by_chat: Dict[str, int] = {}+ # Stream-is-the-message marker (finding #4): the stream consumer+ # checks this to keep ONE draft stream per turn instead of bumping+ # draft_id at tool boundaries (which opens a new Slack message per+ # segment on native streaming — Telegram-shaped adapters want the+ # bump, we don't).+ #+ # SLACK-ONLY semantic, gated on the negotiated descriptor (review+ # B4): the base send_draft contract is Telegram-shaped — the draft+ # clears and the final arrives as a separate real send. Setting+ # this unconditionally made ANY relay connector that advertises+ # the draft op (e.g. a Telegram connector) intercept the turn-final+ # into draft(final=true), so no real history message was ever+ # posted. A future connector platform whose native streaming is+ # also stream-is-the-message should advertise it explicitly+ # (descriptor field within the contract) rather than widening this+ # platform check by guesswork.+ self.draft_stream_is_message = (+ str(getattr(descriptor, "platform", "") or "").lower() == "slack"+ )# chat_id -> event fired when the entry above lands, so a consumer that# arrives before the send can wait for it instead of polling. See# wait_for_auto_thread_info.@@ -246,8 +281,504 @@ class RelayAdapter(BasePlatformAdapter):self,chat_type: Optional[str] = None,metadata: Optional[Dict[str, Any]] = None,+ chat_id: Optional[str] = None,) -> bool:- return self.descriptor.supports_draft_streaming+ # Native draft streaming needs BOTH the descriptor flag and the+ # "draft" op. supported_ops is fail-open for legacy connectors+ # (empty tuple = pre-contract ops only), but "draft" did not exist+ # pre-contract, so it must NOT fail open: an explicit advertisement+ # is required. Without it the stream consumer stays on the+ # edit-based path exactly as today.+ #+ # Per-chat resolution (review r2, finding 2): one adapter fronts N+ # platforms, and the scalar descriptor only reflects the PRIMARY+ # identity — a Telegram primary must not starve a secondary Slack+ # chat of native streaming, nor vice versa. When the caller can+ # name the chat, resolve through its platform's negotiated+ # descriptor; the scalar remains the fallback (chat unknown,+ # single-platform gateways: identical behavior).+ desc = (+ self._descriptor_for_chat(str(chat_id))+ if chat_id is not None+ else self.descriptor+ )+ return (+ desc.supports_draft_streaming+ and "draft" in (desc.supported_ops or ())+ )++ def stream_is_message_for_chat(self, chat_id: str) -> bool:+ """Per-chat stream-is-the-message semantic (review r2, finding 2).++ The class-level ``draft_stream_is_message`` can only reflect the+ primary identity's platform. On a multi-platform relay, a Slack+ primary must not impose seal semantics on a Telegram chat (its+ turn-final would become draft(final=true) — no history message),+ and a Telegram primary must not deny a secondary Slack chat its+ native streaming. Resolve through the chat's own negotiated+ descriptor. Platform-name inference is deliberate for now — a+ descriptor-level field is the eventual contract (gg follow-up)+ so a future platform can advertise the semantic explicitly.+ """+ return (+ str(self._descriptor_for_chat(str(chat_id)).platform or "").lower()+ == "slack"+ )++ # ── Live cards: native draft streaming + task cards (NS-658) ─────────+ #+ # Additive relay ops within contract v1. The gateway side is dumb: it+ # emits ops when the negotiated descriptor advertises them; the+ # connector owns the platform API mechanics (chat.startStream et al.),+ # per-workspace feature-gate caching, and the send+edit fallback.+ #+ # Semantic bridge: the base send_draft contract is Telegram-shaped —+ # the draft clears and the final answer arrives as a separate send().+ # Slack native streaming makes the stream THE message, sealed once.+ # The adapter tracks the open draft per chat; the turn-final send()+ # for that chat converts to draft(final=true) so the connector seals+ # the stream instead of posting a duplicate message.++ def supports_native_task_cards(self) -> bool:+ """Descriptor probe for the TurnRunner's task-card lane.++ Explicit advertisement required — same no-fail-open rule as+ "draft" (the op did not exist pre-contract).+ """+ return "task_card" in (self.descriptor.supported_ops or ())++ def native_task_cards_enabled(self) -> bool:+ """TurnRunner opt-in probe (gateway/run.py) — the card lane calls+ THIS name (same contract as the native Slack adapter's opt-in);+ ``supports_native_task_cards`` is the descriptor-level capability.+ Live-canary finding: without this alias the lane silently stays+ text-mode (hasattr probe fails) even though the connector+ advertises task_card."""+ return self.supports_native_task_cards()++ @staticmethod+ def _draft_key(chat_id: str, metadata: Optional[Dict[str, Any]]) -> str:+ """Coordination key for one turn's stream.++ Prefers a PER-TURN identity — the triggering inbound message id+ (``message_id`` is stamped by the gateway's Slack thread metadata,+ ``reply_to_message_id`` by the consumer's send path; both carry the+ same event id) — over the thread anchor. Finding #10 keyed on the+ thread anchor alone, which is simultaneously too coarse and too+ fragile (review B2 + flat-DM concern):++ - two parallel turns REPLYING INSIDE ONE THREAD share thread_ts,+ so turn A's final sealed turn B's stream with A's content;+ - a flat DM whose metadata carries no anchor at all degraded to+ the bare chat id, re-creating the original #10 collision.++ The thread anchor remains the fallback for callers that only have+ placement metadata, and the bare chat is the last resort+ (single-turn semantics).+ """+ md = metadata or {}+ turn_id = md.get("message_id") or md.get("reply_to_message_id")+ if turn_id:+ return f"{chat_id}:turn:{turn_id}"+ anchor = md.get("thread_ts") or md.get("thread_id") or ""+ return f"{chat_id}:{anchor}"++ # Cap for the draft/seal coordination dicts, matching the sibling+ # bounded caches (_auto_thread_by_chat). Entries are per-turn keys;+ # 512 in-flight-or-recent turns per adapter is far beyond any real+ # concurrency, and matches the connector's tombstone store size.+ _DRAFT_STATE_CAP = 512++ @classmethod+ def _evict_oldest(cls, d: Dict[str, int]) -> None:+ """FIFO-bound a coordination dict in place (review M1)."""+ while len(d) > cls._DRAFT_STATE_CAP:+ d.pop(next(iter(d)), None)++ @staticmethod+ def _card_key(+ reply_to: Optional[str], metadata: Optional[Dict[str, Any]]+ ) -> str:+ """Per-turn task-card identity — same precedence as ``_draft_key``.++ ``reply_to`` (the triggering message id from the TurnRunner) wins;+ metadata message ids cover the flat-DM / resolver lanes; the thread+ anchor is only a fallback because two turns replying inside one+ thread share ``thread_ts`` and must not share a card (review B2).+ One derivation for send AND stop, so the stop always hits the+ stream the send opened.+ """+ md = metadata or {}+ anchor = (+ reply_to+ or md.get("message_id")+ or md.get("reply_to_message_id")+ or md.get("thread_ts")+ or md.get("thread_id")+ or "root"+ )+ return f"turn:{anchor}"++ def _match_open_draft(+ self, chat_id: str, metadata: Optional[Dict[str, Any]]+ ) -> Optional[str]:+ """Resolve which open stream (if any) a turn-final send belongs to.++ Exact key match first. Callers WITHOUT a per-turn message id fall+ into two classes (review r2, finding 5):++ - placement-only metadata (thread_ts/thread_id but no message+ id — legacy resolver lanes): the thread anchor is placement+ info, not turn identity, and streams are keyed per turn — an+ exact match will practically never fire for them. They may+ still absorb the final via the single-open-stream fallback.+ - no metadata at all: same fallback.++ The fallback only fires when the chat has EXACTLY one open+ stream. With several open, the send stays a plain send: a+ duplicate message is recoverable, sealing someone else's stream+ with the wrong content is not (review B2). Callers that DO carry+ a message id never fall back — their identity is authoritative,+ and a mismatch means the stream is someone else's.+ """+ key = self._draft_key(str(chat_id), metadata)+ if key in self._open_draft_by_chat:+ return key+ md = metadata or {}+ # Only a per-turn MESSAGE id is turn identity. Thread anchors are+ # placement info shared by every turn in the thread — treating+ # them as identity made the single-open-stream fallback dead for+ # placement-only callers (probed: plain final beside an open+ # turn-keyed stream).+ if md.get("message_id") or md.get("reply_to_message_id"):+ return None+ prefix = f"{chat_id}:"+ candidates = [+ k for k in self._open_draft_by_chat if k.startswith(prefix)+ ]+ if len(candidates) == 1:+ return candidates[0]+ return None++ async def send_draft(+ self,+ chat_id: str,+ draft_id: int,+ content: str,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> SendResult:+ if not self.supports_draft_streaming(chat_id=str(chat_id)):+ raise NotImplementedError(+ "connector does not advertise the 'draft' relay op"+ )+ if self._transport is None:+ return SendResult(success=False, error="no transport")+ # Audit fix G-D1 + regression fix (2026-08-15): arm optimistically+ # BEFORE the transport call (lossy ack: a timeout/WS-drop 'failure'+ # often means delivered), but NEVER for a draft_id that has already+ # been sealed this chat — the gateway-side mirror of the connector's+ # sealed-key tombstone. Without this, a straggler frame arriving+ # after the seal re-armed interception with no live stream, and the+ # next unrelated send (media follow-up, next-turn text) was wrongly+ # converted to draft(final=true) on the tombstoned key — clearing+ # the tombstone, re-opening a stream, and freezing it (the observed+ # escalating-frozen-prefixes regression).+ chat_key = self._draft_key(str(chat_id), metadata)+ if self._sealed_draft_by_chat.get(chat_key) == draft_id:+ # Post-seal straggler: its content is already in the sealed+ # message; report success, send nothing, arm nothing.+ return SendResult(success=True)+ # Arm seal-interception ONLY for stream-is-the-message chats+ # (review B4, per-chat in r2 finding 2): on a Telegram-shaped+ # connector the draft clears client-side and the final MUST go out+ # as a separate real send — arming here would intercept that final+ # into draft(final=true) and no history message would ever be+ # posted. Resolved per chat: one adapter fronts N platforms.+ if self.stream_is_message_for_chat(str(chat_id)):+ self._open_draft_by_chat[chat_key] = draft_id+ self._evict_oldest(self._open_draft_by_chat)+ try:+ result = await self._transport.send_outbound(+ {+ "op": "draft",+ "chat_id": chat_id,+ "draft_id": draft_id,+ "content": content,+ "final": False,+ "metadata": self._with_scope(chat_id, dict(metadata or {})),+ },+ platform=self._platform_by_chat.get(str(chat_id)),+ )+ except Exception as e:+ # Ambiguous by definition (stale socket, mid-write drop): the+ # frame may have been delivered. Keep interception armed.+ return SendResult(success=False, error=f"draft transport error: {e}")+ if result.get("success"):+ return SendResult(success=True)+ if result.get("ambiguous"):+ # Ack lost (transport timeout) — the production ws transport+ # RETURNS this shape rather than raising (PR 85796 review,+ # round 2): the connector may have applied the frame. Same+ # contract as the except branch: keep interception armed.+ return SendResult(+ success=False, error=str(result.get("error") or "draft ack lost")+ )+ # DEFINITE connector rejection (an explicit non-ambiguous result):+ # disarm interception for this key. The stream consumer disables+ # the draft transport on this failure and falls back to edit-based+ # streaming — its turn-final must go out as a REAL send, not get+ # converted into a seal on a stream the connector just told us is+ # unusable. (This restores the disarm-on-failure semantics the+ # G-D1 optimistic-arming change silently dropped; the ambiguity+ # that motivated G-D1 lives in the except branch above and the+ # ambiguous-result branch — both keep the key armed.)+ if self._open_draft_by_chat.get(chat_key) == draft_id:+ self._open_draft_by_chat.pop(chat_key, None)+ return SendResult(+ success=False, error=str(result.get("error") or "draft failed")+ )++ async def _seal_open_draft(+ self,+ chat_id: str,+ content: str,+ metadata: Optional[Dict[str, Any]],+ *,+ draft_key: Optional[str] = None,+ ) -> SendResult:+ """Convert the turn-final send into the sealing draft frame."""+ if draft_key is None:+ draft_key = self._draft_key(str(chat_id), metadata)+ draft_id = self._open_draft_by_chat.pop(draft_key)+ # Tombstone BEFORE the transport call (regression fix): whatever the+ # ack says, this draft_id's stream must never be re-armed by a+ # straggler frame — the connector-side tombstone handles its half.+ self._sealed_draft_by_chat[draft_key] = draft_id+ # Bounded like the sibling caches (review M1): the key embeds a+ # per-turn identity, so an unbounded dict grows one entry per turn+ # for the life of the process. FIFO eviction matches the+ # straggler window this tombstone exists for (seconds, not days);+ # the connector holds its own 512-entry tombstone store.+ self._evict_oldest(self._sealed_draft_by_chat)+ if self._transport is None:+ return SendResult(success=False, error="no transport")+ seal_frame = {+ "op": "draft",+ "chat_id": chat_id,+ "draft_id": draft_id,+ "content": content,+ "final": True,+ "metadata": self._with_scope(chat_id, dict(metadata or {})),+ }+ _seal_platform = self._platform_by_chat.get(str(chat_id))+ _transport = self._transport # narrowed by the None-guard above++ async def _attempt() -> Optional[Dict[str, Any]]:+ """One seal attempt; None means ambiguous (exception or lost ack)."""+ try:+ r = await _transport.send_outbound(+ seal_frame, platform=_seal_platform+ )+ except asyncio.CancelledError:+ raise+ except Exception as e:+ logger.warning("relay seal transport error (ambiguous): %s", e)+ return None+ if r.get("ambiguous"):+ # The production ws transport returns this shape on ack+ # timeout instead of raising (PR 85796 review, round 2):+ # the connector may have sealed and lost only the ack.+ logger.warning(+ "relay seal ack lost (ambiguous): %s", r.get("error")+ )+ return None+ return r++ # Ambiguous outcomes (exception OR timeout-shaped result) retry the+ # SAME idempotent frame once: the connector's sealed-key tombstone+ # returns the original stream ts for a repeated final and never+ # opens a second stream, so the retry can turn "unknown" into a+ # definite answer for free. Only after BOTH attempts stay ambiguous+ # do we report failure — the caller's fail-open plain send is a+ # possible duplicate, but a silent loss is worse, and two+ # consecutive ack losses on one socket almost always mean the+ # transport is actually down (so the plain send fails too and the+ # gateway's fallback owns delivery).+ #+ # Cancellation safety (review r2, finding 4): the open entry was+ # popped and the tombstone written BEFORE the await. If the task is+ # cancelled mid-seal, CancelledError bypasses the failure handling+ # and the later abandon pass would find nothing to close — the+ # connector-side stream stays visibly live until eviction. Restore+ # the open entry (and drop our premature tombstone) before+ # re-raising so the abandon path can seal it.+ try:+ result = await _attempt()+ if result is None:+ result = await _attempt()+ except asyncio.CancelledError:+ self._open_draft_by_chat[draft_key] = draft_id+ if self._sealed_draft_by_chat.get(draft_key) == draft_id:+ self._sealed_draft_by_chat.pop(draft_key, None)+ raise+ if result is None:+ return SendResult(+ success=False,+ error="draft seal ambiguous after retry (transport ack lost)",+ )+ if result.get("success"):+ # The connector returns the stream's ts as the message identity.+ return SendResult(+ success=True,+ message_id=str(result.get("message_id") or "") or None,+ )+ return SendResult(+ success=False, error=str(result.get("error") or "draft seal failed")+ )++ async def send_native_task_card_progress(+ self,+ chat_id: str,+ tasks: list,+ *,+ title: str = "Hermes is working",+ reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None,+ fallback_text: Optional[str] = None,+ ) -> SendResult:+ """Relay leg of the #85476 task-card lane: emit one card frame.++ SIGNATURE CONTRACT (live-canary finding): the TurnRunner calls this+ with the NATIVE Slack adapter's keyword contract (tasks/title/+ reply_to/metadata/fallback_text) — not a card_id. The card stream+ key is derived per (chat, reply_to-thread): one card per turn+ thread, matching the connector's (channel, card_id) keying.+ ``fallback_text``/``title`` are accepted for contract parity; the+ connector's plan-mode stream renders task chunks, so they are not+ forwarded.++ ``tasks`` are the TurnRunner's normalized task dicts (id/title/+ status/details/output); the connector maps them onto its+ workspace-scoped card stream (task_update chunks, 256-char field+ limits enforced connector-side where the API lives).+ """+ if not self.supports_native_task_cards():+ return SendResult(+ success=False, error="connector does not advertise task_card"+ )+ if self._transport is None:+ return SendResult(success=False, error="no transport")+ # Finding #10 + review B2: one card per TURN. reply_to (the+ # triggering message id) is already per-turn; when it is absent+ # (flat DM, resolver lanes) fall back to the same per-turn+ # identity the draft lane keys on — metadata message ids first,+ # thread anchor only after that (two turns replying inside one+ # thread share thread_ts and must not share a card).+ card_id = self._card_key(reply_to, metadata)+ merged_meta = dict(metadata or {})+ if reply_to and "thread_ts" not in merged_meta:+ # Slack card streams are thread replies (same rule as draft):+ # anchor on the triggering message when the runner gave us one.+ merged_meta["thread_ts"] = str(reply_to)+ try:+ result = await self._transport.send_outbound(+ {+ "op": "task_card",+ "chat_id": chat_id,+ "card_id": card_id,+ "chunks": [dict(t) for t in tasks],+ "metadata": self._with_scope(chat_id, merged_meta),+ },+ platform=self._platform_by_chat.get(str(chat_id)),+ )+ except Exception as e:+ # Progress is advisory: a transport drop must degrade to the+ # TurnRunner's text fallback (failed SendResult), never raise+ # into the progress loop / turn-cleanup path (review B7 — an+ # escaping card exception in cleanup skipped final delivery).+ return SendResult(+ success=False, error=f"task_card transport error: {e}"+ )+ if result.get("success"):+ return SendResult(success=True)+ return SendResult(+ success=False, error=str(result.get("error") or "task_card failed")+ )++ async def stop_native_task_card_progress(+ self,+ chat_id: str,+ *,+ reply_to: Optional[str] = None,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> SendResult:+ """Seal the card stream at turn end (idempotent connector-side).++ Same NATIVE-contract signature as send (canary finding above);+ card key derived identically so the stop hits the open stream.+ """+ if not self.supports_native_task_cards():+ return SendResult(+ success=False, error="connector does not advertise task_card"+ )+ if self._transport is None:+ return SendResult(success=False, error="no transport")+ # Same per-turn key derivation as send (shared helper) so the stop+ # hits the open stream.+ card_id = self._card_key(reply_to, metadata)+ try:+ result = await self._transport.send_outbound(+ {+ "op": "task_card_stop",+ "chat_id": chat_id,+ "card_id": card_id,+ "metadata": self._with_scope(chat_id, dict(metadata or {})),+ },+ platform=self._platform_by_chat.get(str(chat_id)),+ )+ except Exception as e:+ # Best-effort by contract: the stop runs in the progress loop's+ # finally block on the turn-cleanup path — an escaping transport+ # exception there skipped final delivery (review B7). The+ # connector seals orphaned card streams on its own (recycling /+ # eviction), so a lost stop is cosmetic.+ return SendResult(+ success=False, error=f"task_card_stop transport error: {e}"+ )+ return SendResult(success=bool(result.get("success")))++ async def abandon_open_draft(+ self,+ chat_id: str,+ content: str,+ metadata: Optional[Dict[str, Any]] = None,+ ) -> SendResult:+ """Seal an orphaned stream when its turn dies (review B8).++ A stopped (/stop, /new) or superseded turn previously left its+ native stream open forever: the Slack message kept the live+ streaming indicator and the adapter kept armed interception state,+ which the NEXT turn's key could inherit. Seal in place with+ ``content`` — the text already on screen (the consumer passes its+ last delivered frame), so the seal adds nothing and claims+ nothing: it only ends the stream. Delivery flags are the+ consumer's business; this never sets any.++ Best-effort by contract: failure is reported, never raised — the+ connector reaps truly orphaned streams via recycling/eviction.+ """+ draft_key = self._match_open_draft(str(chat_id), metadata)+ if draft_key is None:+ return SendResult(success=True) # nothing armed — no-op+ try:+ return await self._seal_open_draft(+ chat_id, content, metadata, draft_key=draft_key+ )+ except Exception as e:+ return SendResult(+ success=False, error=f"abandon seal transport error: {e}"+ )+# ── abstract methods (delegated to the transport) ────────────────────async def connect(self, *, is_reconnect: bool = False) -> bool:@@ -1021,6 +1552,31 @@ class RelayAdapter(BasePlatformAdapter):success=False,error=f"relay does not front platform {platform_value}",)+ _sfp_metadata = dict(metadata or {})+ # Gateway-internal interim marker (see send()): strip before the+ # wire; an interim send through this door also skips interception.+ _interim = bool(_sfp_metadata.pop("_interim_send", False))+ # Finding #7 (live canary): the delivery resolver calls THIS method+ # directly (gateway/delivery.py), bypassing send() — an open native+ # stream must absorb the turn-final here too, or the stream is left+ # unsealed (frozen live indicator) and the final posts as a separate+ # duplicate message.+ if not _interim:+ _sfp_key = self._match_open_draft(str(chat_id), _sfp_metadata)+ else:+ _sfp_key = None+ if _sfp_key is not None:+ seal = await self._seal_open_draft(+ chat_id, content, _sfp_metadata, draft_key=_sfp_key+ )+ if seal.success:+ return seal+ # Failed seal falls through to the plain send below (review+ # finding, PR 85796 point 1): never swallow the turn-final.+ logger.warning(+ "relay seal failed (%s); delivering turn-final as plain send",+ seal.error,+ )if self._transport is None:return SendResult(success=False, error="no transport")result = await self._transport.send_outbound(@@ -1029,7 +1585,7 @@ class RelayAdapter(BasePlatformAdapter):"chat_id": chat_id,"content": content,"reply_to": reply_to,- "metadata": self._with_scope(chat_id, metadata),+ "metadata": self._with_scope(chat_id, _sfp_metadata),},platform=str(platform_value),)@@ -1049,6 +1605,41 @@ class RelayAdapter(BasePlatformAdapter):) -> SendResult:send_metadata = dict(metadata or {})explicit_platform = send_metadata.pop("_relay_logical_platform", None)+ # Consumer-declared interim send (commentary, tail flush): NOT the+ # turn-final, so it must never trigger seal-interception — sealing+ # the live stream with interim text orphans the true final into a+ # plain-send duplicate (live finding, 2026-08-16 canary). The+ # marker is gateway-internal; strip before the wire.+ _interim = bool(send_metadata.pop("_interim_send", False))+ # NS-658 seal-interception — checked BEFORE the explicit-platform+ # branch (finding #7, live canary): the delivery-resolver lane+ # (follow-up queue, media-accompanied finals, scheduled sends) routes+ # through send_for_platform, which posted a plain send while the+ # native stream stayed open — the user got the stream frozen+ # mid-word (live indicator, never sealed) PLUS the final as a+ # separate message. An open stream absorbs the turn-final send no+ # matter which egress door it arrives through; the stream IS the+ # message.+ if not _interim:+ _send_key = self._match_open_draft(str(chat_id), send_metadata)+ else:+ _send_key = None+ if _send_key is not None:+ seal = await self._seal_open_draft(+ chat_id, content, send_metadata, draft_key=_send_key+ )+ if seal.success:+ return seal+ # Review finding (PR 85796, point 1): a failed seal must NOT+ # swallow the turn-final — the stream consumer has already+ # disabled the draft transport, so returning failure here means+ # the user never gets the answer. Fall through to a plain send+ # (the orphaned stream is sealed connector-side by recycling /+ # MAX_OPEN_STREAMS eviction).+ logger.warning(+ "relay seal failed (%s); delivering turn-final as plain send",+ seal.error,+ )if explicit_platform:return await self.send_for_platform(explicit_platform,diff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex b0e067fc162..2cfd1a88651 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -795,7 +795,18 @@ class WebSocketRelayTransport:await self._send(frame)return await asyncio.wait_for(fut, timeout=self._outbound_timeout_s)except asyncio.TimeoutError:- return {"success": False, "error": "relay outbound timed out"}+ # AMBIGUOUS by contract (PR 85796 review): the frame reached the+ # wire — only the acknowledgement is missing. The connector may+ # well have applied it (draft frame appended, stream sealed).+ # Consumers that need to distinguish "connector rejected this"+ # from "outcome unknown" key on this flag; the fail-fast paths+ # above (closing / not connected) never sent anything and are+ # definite non-delivery, so they stay unmarked.+ return {+ "success": False,+ "error": "relay outbound timed out",+ "ambiguous": True,+ }finally:self._pending.pop(request_id, None)diff --git a/gateway/run.py b/gateway/run.pyindex 6952198e200..33531248233 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -530,6 +530,27 @@ def _non_conversational_metadata(return merged+def _interim_metadata(+ metadata: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ """Mark a mid-turn status/advisory send as NOT the turn-final.++ Stream-is-the-message adapters (relay Slack native streaming) intercept+ the first unmarked send to an armed (chat, turn) key and seal the live+ stream with its content. Every gateway-side send that can fire while a+ turn is streaming — heartbeats, inactivity warnings, approval fallbacks,+ background-review notices — MUST carry this marker or it will seal the+ user's answer stream with status text (PR 85796 review, B5: probed live,+ the 3-minute heartbeat sealed the stream and the real final arrived as+ a duplicate while later frames were silently swallowed by the seal+ tombstone). The marker is gateway-internal; adapters strip it before+ the wire.+ """+ merged = dict(metadata or {})+ merged["_interim_send"] = True+ return merged++def _seed_hygiene_system_prompt(agent: Any,session_row: Optional[Dict[str, Any]],@@ -4620,11 +4641,25 @@ class TurnRunner:returnfinally:if hasattr(adapter, "stop_native_task_card_progress"):- await adapter.stop_native_task_card_progress(- ctx.source.chat_id,- reply_to=ctx._progress_reply_to,- metadata=ctx._progress_metadata,- )+ # Best-effort: this finally runs on the turn-cleanup path.+ # An escaping transport exception here propagated through+ # the cleanup awaits (which caught only CancelledError) and+ # skipped final-delivery logic (review B7). Adapters now+ # return failed SendResults, but defend the seam anyway —+ # any adapter, any transport.+ try:+ await adapter.stop_native_task_card_progress(+ ctx.source.chat_id,+ reply_to=ctx._progress_reply_to,+ metadata=ctx._progress_metadata,+ )+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.debug(+ "task-card stop failed during turn cleanup",+ exc_info=True,+ )async def send_progress_messages(self):ctx = self._ctx@@ -5751,7 +5786,7 @@ class TurnRunner:ctx._status_adapter.send(ctx._status_chat_id,message,- metadata=_non_conversational_metadata(ctx._status_thread_metadata, platform=ctx.source.platform),+ metadata=_interim_metadata(_non_conversational_metadata(ctx._status_thread_metadata, platform=ctx.source.platform)),),ctx._loop_for_step,logger=logger,@@ -6057,7 +6092,7 @@ class TurnRunner:ctx._status_adapter.send(ctx._status_chat_id,msg,- metadata=ctx._status_thread_metadata,+ metadata=_interim_metadata(ctx._status_thread_metadata),),ctx._loop_for_step,logger=logger,@@ -6283,9 +6318,43 @@ class TurnRunner:reset_current_session_key(_approval_session_token)ctx.result_holder[0] = result- # Signal the stream consumer that the agent is done+ # Signal the stream consumer that the agent is done. Pass the+ # completed final_response as the authoritative finalize payload:+ # it includes post-stream augmentation (file-mutation verifier+ # footer, turn-completion explainer) the consumer's accumulator+ # never saw, so the seal/final edit delivers the TRUE final and no+ # separate corrective send fires (live finding #11). Failed turns+ # pass nothing — error text is delivered by the gateway's normal+ # path, not baked into the stream.if _stream_consumer is not None:- _stream_consumer.finish()+ _final_for_stream = None+ # Adopt ONLY a genuinely completed final (review B6): interrupt+ # paths return {interrupted: True, completed: False} with a+ # DIAGNOSTIC final_response ("Operation interrupted during …")+ # and no failed key — adopting that would seal the user's+ # streamed partial answer over with the diagnostic AND make+ # delivered_final_matches reconcile, suppressing the gateway's+ # own error-delivery path. Writers of these shapes:+ # agent/conversation_loop.py interrupt/retry-abort returns.+ if (+ isinstance(result, dict)+ and not result.get("failed")+ and not result.get("interrupted")+ and result.get("completed") is not False+ ):+ _fr = result.get("final_response")+ if isinstance(_fr, str) and _fr.strip() and _fr != "(empty)":+ _final_for_stream = _fr+ if _final_for_stream is not None:+ # Duck-type safe: test doubles / older consumers may expose a+ # zero-arg finish(). The payload is an optimization, not a+ # requirement — fall back to the bare signal.+ try:+ _stream_consumer.finish(_final_for_stream)+ except TypeError:+ _stream_consumer.finish()+ else:+ _stream_consumer.finish()# Signal the streaming-TTS consumer that the agent is done (#60671).# finish() is called from the outer event-loop thread after the@@ -22082,16 +22151,51 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewevent_message_id: Optional[str] = None,text_already_delivered: bool = False,deliver_media: bool = True,+ stream_consumer=None,) -> None:"""Deliver a queued response using the normal text+attachment split."""if not text_already_delivered:text_content = _strip_response_attachments_for_direct_send(response, adapter)if text_content:- await adapter.send(- source.chat_id,- text_content,- metadata=metadata,- )+ # Reconcile-by-edit first (live finding, 2026-08-16 canary):+ # when the stream consumer delivered/sealed a message but its+ # recorded payload didn't confirm the final (post-stream+ # mutation), plain-sending here creates the duplicate — the+ # sealed message already carries most of the answer. A sealed+ # native stream is a regular message; chat.update on it is+ # live-verified working. Fall back to plain send only when+ # there is no editable message or the edit fails.+ _reconciled = False+ _sc_msg_id = getattr(stream_consumer, "message_id", None)+ if (+ _sc_msg_id+ and _sc_msg_id != "__no_edit__"+ and not getattr(stream_consumer, "_turn_split_delivery", False)+ ):+ try:+ _edit_res = await adapter.edit_message(+ chat_id=source.chat_id,+ message_id=_sc_msg_id,+ content=text_content,+ finalize=True,+ )+ if getattr(_edit_res, "success", False):+ _reconciled = True+ logger.info(+ "Queued-lane final reconciled by editing message %s in place (no duplicate send).",+ _sc_msg_id,+ )+ except Exception as _qe:+ logger.debug(+ "Queued-lane reconcile edit failed (%s); falling back to send.",+ _qe,+ )+ if not _reconciled:+ await adapter.send(+ source.chat_id,+ text_content,+ metadata=metadata,+ )# Failed turns still deliver their (normalized failure) text above,# but must not upload attachments as if the turn succeeded — mirrors@@ -23402,10 +23506,27 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewreply_to_message_id=reply_to_message_id or getattr(source, "message_id", None),)if getattr(source, "platform", None) == Platform.SLACK:+ # Per-turn egress identity (R3-5, connector PR gateway-gateway#210).+ # Slack's chat.startStream requires recipient_user_id (++ # recipient_team_id) when streaming to a channel, and the relay+ # connector fills those from metadata.user_id / metadata.scope_id.+ # The relay adapter's _with_scope fallback resolves BOTH from+ # per-chat caches keyed only by chat_id — mutable state that a+ # CONCURRENT turn overwrites: two users with overlapping turns in+ # one channel would open U1's stream with U2 as the recipient.+ # Stamp the authentic per-turn values from THIS turn's source here,+ # where they are still turn-scoped; _with_scope only fills keys+ # that are absent, so the cache degrades to what it should be — a+ # restart/synthetic-send fallback.team_id = getattr(source, "scope_id", None)- if team_id:+ user_id = getattr(source, "user_id", None)+ if team_id or user_id:metadata = dict(metadata or {})- metadata["slack_team_id"] = str(team_id)+ if team_id:+ metadata["slack_team_id"] = str(team_id)+ metadata.setdefault("scope_id", str(team_id))+ if user_id:+ metadata.setdefault("user_id", str(user_id))return metadatadef _thread_metadata_for_target(@@ -28601,7 +28722,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew_notify_res = await _notify_adapter.send(source.chat_id,_heartbeat_text,- metadata=_non_conversational_metadata(_status_thread_metadata, platform=source.platform),+ metadata=_interim_metadata(_non_conversational_metadata(_status_thread_metadata, platform=source.platform)),)if getattr(_notify_res, "success", False) and getattr(_notify_res, "message_id", None@@ -28832,7 +28953,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewf"If the agent does not respond soon, it will "f"be timed out in {_remaining_mins} min. "f"You can continue waiting or use /reset.",- metadata=_status_thread_metadata,+ metadata=_interim_metadata(_status_thread_metadata),)except Exception as _warn_err:logger.debug("Inactivity warning send error: %s", _warn_err)@@ -29196,6 +29317,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewevent_message_id=event_message_id,text_already_delivered=_already_streamed,deliver_media=not _delivery_result.get("failed"),+ stream_consumer=_sc,)except Exception as e:logger.warning("Failed to send first response before queued message: %s", e)@@ -29396,6 +29518,16 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewawait taskexcept asyncio.CancelledError:pass+ except Exception:+ # A background task that died of a non-cancellation+ # error (transport drop in a progress/card publish)+ # must not abort the cleanup path — everything after+ # this loop (final-delivery bookkeeping) still runs+ # (review B7).+ logger.debug(+ "background turn task failed during cleanup",+ exc_info=True,+ )# If streaming already delivered the response, mark it so the# caller's send() is skipped (avoiding duplicate messages).diff --git a/gateway/stream_consumer.py b/gateway/stream_consumer.pyindex 836ba980a77..0715a0e8081 100644--- a/gateway/stream_consumer.py+++ b/gateway/stream_consumer.py@@ -19,6 +19,7 @@ import asyncioimport inspectimport loggingimport queue+import secretsimport threadingimport timefrom dataclasses import dataclass@@ -43,6 +44,13 @@ logger = logging.getLogger("gateway.stream_consumer")_DONE = object()_NEW_SEGMENT = object()_COMMENTARY = object()+# Authoritative turn-final payload, enqueued by ``finish(final_text=...)``+# just before ``_DONE``. Carries the completed ``final_response`` —+# including post-stream augmentation (file-mutation verifier footer,+# turn-completion explainer) — so the finalize/seal delivers the TRUE final+# and the recorded payload reconciles (#71643 / live finding #11: the+# footer-bearing final previously arrived only via a separate plain send).+_FINAL_TEXT = object()# Queue marker for a synchronous flush barrier. Enqueued as# ``(_FLUSH, threading.Event)``; the drain loop finalizes and delivers any@@ -187,7 +195,20 @@ class GatewayStreamConsumer:# Class-wide monotonic counter for native-streaming draft ids. Telegram# animates a draft when the same draft_id is reused across consecutive# calls in the same chat, so we need a fresh non-zero id per response.- _draft_id_counter: int = 0+ #+ # Seeded from a RANDOM process nonce, not zero and not the clock (PR+ # 85796 review, B3 + r2 follow-up): draft_id is the wire identity for+ # the relay connector's per-(channel, draft_id) sealed-stream+ # tombstones, which outlive this process. Relay gateways are+ # disposable by design (scale-to-zero), so a counter restarting at 1+ # replays ids the connector already sealed — it then answers frames+ # from the NEW turn out of the OLD tombstone (zero platform calls,+ # old message identity) and the user's reply is silently dropped.+ # An epoch-ms seed (the first fix) still collides on same-millisecond+ # starts, forks, and clock steps; 49 random bits make collision+ # probability negligible while keeping ids + realistic turn counts+ # comfortably inside the connector's JS number range (2^53).+ _draft_id_counter: int = secrets.randbits(49)def __init__(self,@@ -321,6 +342,24 @@ class GatewayStreamConsumer:self._draft_failures = 0self._before_finalize_notified = False+ def _stream_is_message(self) -> bool:+ """Whether THIS chat's transport treats the stream as the message.++ Prefers the adapter's per-chat probe (multi-platform relay: one+ adapter fronts N platforms, and the class attribute can only+ reflect the primary identity — review r2, finding 2). Falls back+ to the legacy attribute for adapters without the probe. Both are+ resolved on the CLASS to stay MagicMock-safe (auto-created+ instance attributes are truthy).+ """+ probe = getattr(type(self.adapter), "stream_is_message_for_chat", None)+ if callable(probe):+ try:+ return probe(self.adapter, str(self.chat_id)) is True+ except Exception:+ return False+ return getattr(self.adapter, "draft_stream_is_message", False) is True+def _metadata_for_send(self,*,@@ -605,8 +644,18 @@ class GatewayStreamConsumer:# own visible message via the finalize, then a new draft animates# for the next one.if self._use_draft_streaming:- type(self)._draft_id_counter += 1- self._draft_id = type(self)._draft_id_counter+ # Finding #4 (live canary, Alice): for stream-is-the-message+ # adapters (relay Slack native streaming), a draft_id bump opens+ # a brand-new platform stream per tool boundary — the user saw+ # one frozen message per segment (each stuck with the streaming+ # cursor, never sealed) plus the real final. Those adapters keep+ # ONE stream per turn: tool progress lives in the native task+ # card, and the connector's suffix-delta logic appends each new+ # segment cleanly (prefix mismatch → whole-segment append).+ # Telegram-shaped drafts (clear + separate final) keep the bump.+ if not self._stream_is_message():+ type(self)._draft_id_counter += 1+ self._draft_id = type(self)._draft_id_counterdef on_delta(self, text: str) -> None:"""Thread-safe callback — called from the agent's worker thread.@@ -620,8 +669,20 @@ class GatewayStreamConsumer:elif text is None:self.on_segment_break()- def finish(self) -> None:- """Signal that the stream is complete."""+ def finish(self, final_text: Optional[str] = None) -> None:+ """Signal that the stream is complete.++ ``final_text``, when provided, is the AUTHORITATIVE completed+ ``final_response`` — including post-stream augmentation the+ accumulator never saw (file-mutation verifier footer,+ turn-completion explainer, plugin transforms). The drain loop+ adopts it as the finalize payload so the sealed/edited message IS+ the true final and no separate corrective send is needed+ (live finding #11). Callers that cannot know the final yet+ (interrupt/error paths) call ``finish()`` bare — legacy behavior.+ """+ if final_text is not None:+ self._queue.put((_FINAL_TEXT, final_text))self._queue.put(_DONE)# ── Think-block filtering ────────────────────────────────────────@@ -819,6 +880,7 @@ class GatewayStreamConsumer:# (e.g. /new or /stop). Prevents stale deltas from being# delivered after the user has already moved on.if not self._run_still_current():+ await self._abandon_native_stream()return# Drain all available items from the queue@@ -836,6 +898,58 @@ class GatewayStreamConsumer:if item is _NEW_SEGMENT:got_segment_break = Truebreak+ if isinstance(item, tuple) and len(item) == 2 and item[0] is _FINAL_TEXT:+ # Authoritative turn-final payload (see finish()).+ # Adopt it as the finalize content so the seal /+ # final edit carries the TRUE final — including+ # post-stream augmentation (verifier footer,+ # completion explainer) the accumulator never saw.+ # Only when this consumer actually streamed+ # something this turn: a no-stream turn keeps the+ # gateway's normal final-send path (adopting here+ # would move delivery ownership for every+ # non-streaming model). Skip on a multi-message+ # split delivery: heads are already sealed on+ # screen, so adopting the full final would repeat+ # them inside the tail (#78541 shape).+ _streamed_something = bool(+ self._accumulated+ or self._message_id+ or self._last_sent_text+ )+ if _streamed_something and not self._turn_split_delivery:+ _final_payload = self._clean_for_display(item[1])+ _visible = self._clean_for_display(self._accumulated)+ if _final_payload and _final_payload != _visible:+ self._accumulated = item[1]+ self._stream_ledger = item[1]+ elif _streamed_something and self._turn_split_delivery:+ # Split delivery + authoritative final (review+ # r2, finding 3): wholesale adoption would+ # repeat sealed heads inside the tail (#78541),+ # but REFUSING entirely re-creates the #11+ # duplicate one level up — a post-split footer+ # never enters the ledger, delivered_final_+ # matches reports a mismatch, and the gateway+ # resends the ENTIRE body+footer. When the+ # authoritative final strictly prefix-extends+ # the split ledger, the missing suffix is the+ # only undelivered content: append it to the+ # live tail and the ledger, so the finalize+ # carries it and the recorded payload+ # reconciles. Non-prefix rewrites keep the+ # full-resend fallback (can't patch a rewrite).+ _final_raw = item[1]+ _ledger = self._stream_ledger+ if (+ _ledger+ and _final_raw.startswith(_ledger)+ and len(_final_raw) > len(_ledger)+ ):+ _suffix = _final_raw[len(_ledger):]+ self._accumulated += _suffix+ self._stream_ledger = _final_raw+ continueif isinstance(item, tuple) and len(item) == 2 and item[0] is _COMMENTARY:commentary_text = item[1]break@@ -1136,17 +1250,37 @@ class GatewayStreamConsumer:# not duplicate the visible prefix.await self._send_fallback_final(self._accumulated)elif not self._already_sent:- self._final_response_sent = await self._send_or_edit(self._accumulated)+ # Turn-final retry after the finalize tick above+ # failed (transport error, seal exception).+ # finalize=True so a stream-is-the-message adapter+ # can never route this through the draft-frame+ # branch: its no-op dedupe compares against the+ # last UNSEALED frame and would report success+ # without any transport call, recording a final+ # the user never received (silent-loss class).+ self._final_response_sent = await self._send_or_edit(+ self._accumulated, finalize=True,+ )if self._final_response_sent:self._final_content_delivered = Trueself._record_turn_final_payload(self._accumulated)returnif commentary_text is not None:- self._reset_segment_state()- await self._send_commentary(commentary_text)- self._last_edit_time = time.monotonic()- self._reset_segment_state()+ # Stream-is-the-message adapters: commentary posts as its+ # own message (no notify → no seal-interception), and the+ # native stream continues cumulatively. Resetting here+ # would break the append-only invariant the connector's+ # delta computation depends on (whole-snapshot re-append).+ _stream_is_msg_c = self._stream_is_message()+ if _stream_is_msg_c and self._use_draft_streaming:+ await self._send_commentary(commentary_text)+ self._last_edit_time = time.monotonic()+ else:+ self._reset_segment_state()+ await self._send_commentary(commentary_text)+ self._last_edit_time = time.monotonic()+ self._reset_segment_state()# Tool boundary: reset message state so the next text chunk# creates a fresh message below any tool-progress messages.@@ -1163,22 +1297,37 @@ class GatewayStreamConsumer:# a real string like "msg_1", not "__no_edit__", so that case# still resets and creates a fresh segment as intended.)if got_segment_break:- # If the segment-break edit failed to deliver the- # accumulated content (flood control that has not yet- # promoted to fallback mode, or fallback mode itself),- # _accumulated still holds pre-boundary text the user- # never saw. Flush that tail as a continuation message- # before the reset below wipes _accumulated — otherwise- # text generated before the tool boundary is silently- # dropped (issue #8124).+ # Stream-is-the-message adapters keep one cumulative native+ # stream for the whole turn. Clearing _accumulated here makes+ # the next frame a non-prefix snapshot, so the connector's+ # append fallback repeats the entire answer at every tool+ # boundary. Preserve all stream state; only non-native draft+ # and edit-based transports start a new segment.+ # ``is True`` + _use_draft_streaming: MagicMock adapters+ # return truthy auto-attributes, and an edit-based run on a+ # stream-capable adapter still needs the legacy reset.if (- self._accumulated- and not current_update_visible- and self._message_id- and self._message_id != "__no_edit__"+ self._stream_is_message()+ and self._use_draft_streaming):- await self._flush_segment_tail_on_edit_failure()- self._reset_segment_state(preserve_no_edit=True)+ pass+ else:+ # If the segment-break edit failed to deliver the+ # accumulated content (flood control that has not yet+ # promoted to fallback mode, or fallback mode itself),+ # _accumulated still holds pre-boundary text the user+ # never saw. Flush that tail as a continuation message+ # before the reset below wipes _accumulated — otherwise+ # text generated before the tool boundary is silently+ # dropped (issue #8124).+ if (+ self._accumulated+ and not current_update_visible+ and self._message_id+ and self._message_id != "__no_edit__"+ ):+ await self._flush_segment_tail_on_edit_failure()+ self._reset_segment_state(preserve_no_edit=True)# Flush barrier satisfied: the buffered segment (if any) has now# been finalized and delivered above, so wake the thread blocked@@ -1207,6 +1356,14 @@ class GatewayStreamConsumer:)except Exception:pass+ elif self._message_id is None:+ # Native draft path deliberately keeps _message_id=None, so+ # the best-effort edit above never runs for it — the stream+ # stayed visibly live (streaming indicator) forever and the+ # adapter kept armed interception state for the next turn+ # to inherit (review B8). Seal in place with what's already+ # on screen; sets no delivery flags.+ await self._abandon_native_stream()# Only confirm final delivery if the best-effort send above# actually succeeded OR if the final response was already# confirmed before we were cancelled. Previously this@@ -1719,10 +1876,21 @@ class GatewayStreamConsumer:if not isinstance(self.adapter, _BasePlatformAdapter):return Falsetry:- supported = self.adapter.supports_draft_streaming(- chat_type=self.cfg.chat_type or None,- metadata=self.metadata,- )+ try:+ # Per-chat capability (review r2, finding 2): multi-platform+ # relay adapters resolve draft support through the CHAT's+ # negotiated descriptor, not the primary identity's. Older+ # adapters without the kwarg keep the legacy probe.+ supported = self.adapter.supports_draft_streaming(+ chat_type=self.cfg.chat_type or None,+ metadata=self.metadata,+ chat_id=self.chat_id,+ )+ except TypeError:+ supported = self.adapter.supports_draft_streaming(+ chat_type=self.cfg.chat_type or None,+ metadata=self.metadata,+ )except Exception:logger.debug("supports_draft_streaming probe raised", exc_info=True)supported = False@@ -1750,12 +1918,21 @@ class GatewayStreamConsumer:# set in tandem with _draft_id in run(). Disable to be safe.self._use_draft_streaming = Falsereturn False+ # Carry the per-turn identity on EVERY frame (review B2): the+ # turn-final send goes out via _metadata_for_send, which stamps+ # reply_to_message_id — the relay adapter keys draft/seal state on+ # that identity, so frames must carry the same one or the final+ # cannot find the open stream (flat DMs have no thread metadata+ # at all and would otherwise key on the bare chat).+ _md = dict(self.metadata) if self.metadata else {}+ if self._initial_reply_to_id:+ _md.setdefault("reply_to_message_id", self._initial_reply_to_id)try:result = await self.adapter.send_draft(chat_id=self.chat_id,draft_id=self._draft_id,content=text,- metadata=self.metadata,+ metadata=_md or None,)except Exception as e:logger.debug(@@ -1776,6 +1953,35 @@ class GatewayStreamConsumer:self._last_sent_text = textreturn True+ async def _abandon_native_stream(self) -> None:+ """Close an orphaned native draft stream on turn death (review B8).++ Stale-generation exits and cancellations previously returned with+ the stream still open: the platform message kept its live+ streaming indicator forever, and the adapter's armed interception+ state survived into the next turn. Seal in place with the last+ delivered frame (adds nothing new on screen), via the adapter's+ best-effort ``abandon_open_draft``. Never sets delivery flags —+ an abandoned turn's text was partial, and the gateway's normal+ paths still own whatever happens next.+ """+ if not self._use_draft_streaming:+ return+ abandon = getattr(type(self.adapter), "abandon_open_draft", None)+ if abandon is None:+ return+ try:+ _md = dict(self.metadata) if self.metadata else {}+ if self._initial_reply_to_id:+ _md.setdefault("reply_to_message_id", self._initial_reply_to_id)+ await self.adapter.abandon_open_draft(+ self.chat_id,+ self._last_sent_text or self._clean_for_display(self._accumulated),+ metadata=_md or None,+ )+ except Exception as e:+ logger.debug("abandon_open_draft failed (best-effort): %s", e)+async def _flush_segment_tail_on_edit_failure(self) -> None:"""Deliver un-sent tail content before a segment-break reset.@@ -1799,10 +2005,15 @@ class GatewayStreamConsumer:if not tail.strip():returntry:+ # Interim declaration: this tail is pre-boundary text, not the+ # turn-final — never let it seal a native stream (see+ # _send_commentary).+ _md = dict(self.metadata) if self.metadata else {}+ _md["_interim_send"] = Trueresult = await self.adapter.send(chat_id=self.chat_id,content=tail,- metadata=self.metadata,+ metadata=_md,)if result.success:self._already_sent = True@@ -1836,10 +2047,18 @@ class GatewayStreamConsumer:if not text.strip():return Falsetry:+ # Declare interim intent: this send is NOT the turn-final. A+ # stream-is-the-message adapter (relay Slack native streaming)+ # must not let its seal-interception convert this into+ # draft(final=true) — that would seal the live stream with+ # interim text and orphan the true final into a plain-send+ # duplicate (live finding, 2026-08-16 canary).+ _md = dict(self.metadata) if self.metadata else {}+ _md["_interim_send"] = Trueresult = await self.adapter.send(chat_id=self.chat_id,content=text,- metadata=self.metadata,+ metadata=_md,)# Note: do NOT set _already_sent = True here.# Commentary messages are interim status updates (e.g. "Using browser@@ -2101,6 +2320,14 @@ class GatewayStreamConsumer:# Media files are delivered as native attachments after the stream# finishes (via _deliver_media_from_response in gateway/run.py).text = self._clean_for_display(text)+ # Preserve the pre-fence-closed form for stream-is-the-message draft+ # frames: appending a closing ``` to a mid-code-block frame makes+ # frame N not a prefix of frame N+1, so the connector's append-only+ # delta computation falls back to a whole-snapshot re-append (the+ # stacked-copies class). Native streams render unclosed fences+ # progressively; the finalize path below still fence-closes the+ # real final message.+ _pre_fence_text = text# Ensure code fences are balanced before send/edit. Model output# truncated mid-code-block (e.g. finish_reason="length") leaves an# orphaned ``` which, on Discord/Slack/Matrix, causes the entire@@ -2144,15 +2371,37 @@ class GatewayStreamConsumer:# a tool-boundary segment break where the prior text was finalized# as a real sendMessage and the next text segment continues editing# that one — staying on edit-based for that segment is correct).+ # Stream-is-the-message exception (finding #5, live canary): for+ # adapters like relay Slack native streaming, a segment-break+ # finalize must NOT become a real send — the adapter's seal+ # interception would convert it to draft(final=true), sealing the+ # stream at EVERY tool boundary (one frozen cumulative message per+ # segment; only the turn-final seal belongs). Those adapters keep+ # ONE stream per turn: mid-turn boundaries just emit another+ # cumulative frame; only got_done (is_turn_final) seals.+ _stream_is_msg = self._stream_is_message()if (self._use_draft_streaming- and not finalizeand self._message_id is None+ and (not finalize or (_stream_is_msg and not is_turn_final))):+ # Stream-is-the-message frames must stay prefix-stable: use the+ # pre-fence-closed text (see _pre_fence_text above). The turn+ # final still goes through the fence-closed path below.+ _frame_text = _pre_fence_text if _stream_is_msg else text+ # Finding #6 (live canary, the duplicate-content root cause):+ # strip the gateway's text cursor from draft frames. Native+ # streams render their own typing indicator, and a cursor-+ # suffixed frame breaks the connector's prefix-delta check on+ # EVERY tick ("...text▉" is never a prefix of "...text more▉"),+ # triggering its whole-text fallback append — the user saw each+ # cumulative snapshot stacked inside one message, ▉ included.+ if self.cfg.cursor and _frame_text.endswith(self.cfg.cursor):+ _frame_text = _frame_text[: -len(self.cfg.cursor)]# No-op skip: identical to the last frame we sent.- if text == self._last_sent_text:+ if _frame_text == self._last_sent_text:return True- ok = await self._send_draft_frame(text)+ ok = await self._send_draft_frame(_frame_text)if ok:# Drafts mark "we put something on screen" but DO NOT set# _already_sent — that flag gates the gateway's fallbackdiff --git a/tests/gateway/relay/stub_connector.py b/tests/gateway/relay/stub_connector.pyindex 0a9bee357fd..9283883531a 100644--- a/tests/gateway/relay/stub_connector.py+++ b/tests/gateway/relay/stub_connector.py@@ -51,6 +51,9 @@ class StubConnector:# mimics a resolved capability egress; set success=False to simulate an# absent/expired capability or a tenant mismatch on the connector side.self.next_follow_up_result: Dict[str, Any] = {"success": True, "message_id": "f1"}+ # Canned result for the next draft frame (NS-658 live cards). The+ # sealing frame (final=true) echoes message_id = the stream ts.+ self.next_draft_result: Dict[str, Any] = {"success": True}async def connect(self, *, is_reconnect: bool = False) -> bool:self.connected = True@@ -85,6 +88,8 @@ class StubConnector:self.sent_platforms.append(platform)if action.get("op") == "send":return dict(self.next_send_result)+ if action.get("op") == "draft":+ return dict(self.next_draft_result)if action.get("op") == "send_media":return dict(self.next_media_result)if action.get("op") == "prompt":diff --git a/tests/gateway/relay/test_live_cards_flow_trace.py b/tests/gateway/relay/test_live_cards_flow_trace.pynew file mode 100644index 00000000000..d004b4804df--- /dev/null+++ b/tests/gateway/relay/test_live_cards_flow_trace.py@@ -0,0 +1,133 @@+"""Local integration trace: REAL StreamConsumer + REAL RelayAdapter + stub+transport. Reproduces the multi-segment live-cards turn to reveal the exact+op sequence the connector sees (finding #4/#5 forensics — Alice canary).++Run: python -m pytest tests/gateway/relay/test_live_cards_flow_trace.py -q -s+"""+import asyncio+import sys+import types++import pytest++from gateway.relay.adapter import RelayAdapter+++class TraceTransport:+ """Stub connector transport recording every outbound op."""++ def __init__(self, fail_ops=None):+ self.ops = []+ self.fail_ops = set(fail_ops or ())+ self._ts = 1000++ async def send_outbound(self, payload, platform=None):+ op = payload.get("op")+ self.ops.append(dict(payload))+ if op in self.fail_ops:+ return {"success": False, "error": f"stub-forced {op} failure"}+ self._ts += 1+ return {"success": True, "message_id": f"{self._ts}.000"}+++def _mk_adapter(supported_ops=("send", "edit", "typing", "draft", "task_card", "task_card_stop")):+ # Reuse the live-cards test helper wiring (descriptor + config stubs).+ from tests.gateway.relay.test_relay_live_cards import _connected_adapter+ adapter, _ = _connected_adapter(supported_ops=supported_ops)+ t = TraceTransport()+ adapter._transport = t+ return adapter, t+++def test_trace_multisegment_draft_flow():+ """Simulate the consumer's actual call pattern for a 3-segment turn:+ seg1 drafts -> segment-break finalize (send) -> seg2 drafts ->+ segment-break finalize (send) -> seg3 drafts -> turn-final send.+ Prints the op timeline; asserts the invariant we EXPECT enterprise-wise:+ at most ONE final message identity visible to the user.+ """+ adapter, t = _mk_adapter()+ loop = asyncio.new_event_loop()+ md = {"thread_ts": "1700.100"}++ async def turn():+ # segment 1 streaming+ await adapter.send_draft("C1", 7, "seg1 partial", metadata=md)+ await adapter.send_draft("C1", 7, "seg1 complete.", metadata=md)+ # tool boundary (fix #5): consumer now emits a cumulative draft+ # frame instead of a finalize send for stream-is-the-message+ # adapters — simulate that call shape.+ await adapter.send_draft("C1", 7, "seg1 complete.", metadata=md)+ # segment 2 streaming (fix #4: same draft_id)+ await adapter.send_draft("C1", 7, "seg1 complete.\nseg2 partial", metadata=md)+ await adapter.send_draft("C1", 7, "seg1 complete.\nseg2 complete.", metadata=md)+ # segment 3 + the ONE turn-final send (seal-intercepted)+ await adapter.send_draft(+ "C1", 7, "seg1 complete.\nseg2 complete.\nfinal answer partial", metadata=md+ )+ r3 = await adapter.send(+ "C1", "seg1 complete.\nseg2 complete.\nfinal answer complete.", metadata=md+ )+ return r3++ r3 = loop.run_until_complete(turn())+ print("\n--- OP TIMELINE ---")+ for i, op in enumerate(t.ops):+ print(f"{i:2d} {op['op']:<16} final={op.get('final')} draft_id={op.get('draft_id')} "+ f"content={str(op.get('content'))[:40]!r}")+ finals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ plain_sends = [o for o in t.ops if o["op"] == "send"]+ print(f"seal frames: {len(finals)}, plain sends: {len(plain_sends)}")+ # The user-visible message count = seals + plain sends (each seal ends a+ # visible stream message; each plain send posts a message).+ visible = len(finals) + len(plain_sends)+ print(f"user-visible messages this turn: {visible}")+ assert visible == 1, (+ f"turn produced {visible} user-visible messages (expected 1): "+ f"each segment-break send() gets converted to draft(final=true) by the "+ f"adapter's seal-interception, sealing a stream PER SEGMENT"+ )+++def test_trace_parallel_turns_do_not_collide():+ """Finding #10 (live): three concurrent turns in ONE flat DM must keep+ fully independent stream + card identities. Per-chat keying merged+ turn B's card into turn A's and clobbered seal state (3x duplicates)."""+ adapter, t = _mk_adapter()+ loop = asyncio.new_event_loop()+ # Each turn's metadata carries its own thread anchor (inbound stamps+ # thread_ts = event.thread_ts or ts on every top-level message).+ md_a = {"thread_ts": "100.1"}+ md_b = {"thread_ts": "200.2"}++ async def interleaved():+ # A and B stream interleaved on the SAME chat with different anchors+ await adapter.send_draft("C1", 11, "A partial", metadata=md_a)+ await adapter.send_draft("C1", 12, "B partial", metadata=md_b)+ # A's card and B's card must be distinct card_ids+ await adapter.send_native_task_card_progress(+ "C1", [{"id": "t1", "title": "x", "status": "in_progress"}],+ reply_to=None, metadata=md_a)+ await adapter.send_native_task_card_progress(+ "C1", [{"id": "t2", "title": "y", "status": "in_progress"}],+ reply_to=None, metadata=md_b)+ # A seals; B keeps streaming — B's state must survive A's seal+ ra = await adapter.send("C1", "A final.", metadata=md_a)+ await adapter.send_draft("C1", 12, "B partial more", metadata=md_b)+ rb = await adapter.send("C1", "B final.", metadata=md_b)+ return ra, rb++ ra, rb = loop.run_until_complete(interleaved())+ drafts = [o for o in t.ops if o["op"] == "draft"]+ seals = [o for o in drafts if o.get("final")]+ cards = [o for o in t.ops if o["op"] == "task_card"]+ plain = [o for o in t.ops if o["op"] == "send"]+ # Distinct card identities per turn:+ assert len({c["card_id"] for c in cards}) == 2, cards+ # Each turn sealed its OWN stream (2 seals, matching draft_ids 11/12):+ assert sorted(s["draft_id"] for s in seals) == [11, 12], seals+ # No leaked plain send: both finals absorbed by their own seals:+ assert not plain, plain+ # B's post-A-seal frame was NOT dropped by A's tombstone:+ b_frames = [d for d in drafts if d["draft_id"] == 12 and not d.get("final")]+ assert len(b_frames) == 2, b_framesdiff --git a/tests/gateway/relay/test_relay_ack_ambiguity.py b/tests/gateway/relay/test_relay_ack_ambiguity.pynew file mode 100644index 00000000000..63db67f0c29--- /dev/null+++ b/tests/gateway/relay/test_relay_ack_ambiguity.py@@ -0,0 +1,167 @@+"""Regression: the transport's timeout-shaped RESULT is ambiguous, not a+rejection (PR 85796 review round 2, finding 1).++The production ws transport does not raise on ack timeout — it returns+{"success": False, "error": "relay outbound timed out", "ambiguous": True}.+The round-1 fixes keyed ambiguity handling entirely on the exception+channel, so the shape production actually produces was misclassified:++ - a lost SEAL ack skipped the idempotent retry and fell straight to a+ plain send (duplicate final whenever the seal had actually applied);+ - a lost FRAME ack was treated as a definite connector rejection and+ DISARMED interception — frozen native stream beside a plain final+ (the original G-D1 ambiguous-ack defect, moved to the result channel).++Contract now: transport tags ack-timeouts ambiguous=True (fail-fast+closing/not-connected results stay unmarked — nothing was sent); the+adapter retries the idempotent seal frame on ambiguous results exactly as+for exceptions, and disarms interception only on definite rejections.+"""++import asyncio++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class AckLossTransport:+ """Returns the production timeout shape for selected ops."""++ def __init__(self, lose_acks_for=(), lose_times=None):+ self.ops = []+ self.lose_acks_for = set(lose_acks_for)+ self.lose_times = dict(lose_times or {}) # key -> remaining losses+ self._n = 0++ def _lost(self, key):+ if key not in self.lose_acks_for:+ return False+ remaining = self.lose_times.get(key)+ if remaining is None:+ return True+ if remaining <= 0:+ return False+ self.lose_times[key] = remaining - 1+ return True++ async def send_outbound(self, payload, platform=None):+ op = payload.get("op")+ key = "seal" if (op == "draft" and payload.get("final")) else op+ self.ops.append((op, bool(payload.get("final")), str(payload.get("content"))[:30]))+ if self._lost(key):+ return {+ "success": False,+ "error": "relay outbound timed out",+ "ambiguous": True,+ }+ self._n += 1+ return {"success": True, "message_id": f"ts.{self._n}"}+++class TestSealAckLoss:+ @pytest.mark.asyncio+ async def test_lost_seal_ack_retries_idempotent_frame(self):+ """One lost seal ack → the SAME final frame is retried; its ack+ carries the stream ts; NO plain send fires."""+ t = AckLossTransport(lose_acks_for=("seal",), lose_times={"seal": 1})+ adapter, _ = _connected_adapter()+ adapter._transport = t+ md = {"message_id": "m.1"}+ await adapter.send_draft("C1", 7, "partial", metadata=md)+ r = await adapter.send("C1", "complete", metadata=dict(md))+ assert r.success+ seal_attempts = [o for o in t.ops if o[0] == "draft" and o[1]]+ assert len(seal_attempts) == 2, "ambiguous seal result must retry"+ assert not [o for o in t.ops if o[0] == "send"], (+ "a retried-and-acked seal must not be followed by a plain send"+ )++ @pytest.mark.asyncio+ async def test_seal_ack_lost_twice_reports_ambiguous_failure(self):+ t = AckLossTransport(lose_acks_for=("seal",))+ adapter, _ = _connected_adapter()+ adapter._transport = t+ md = {"message_id": "m.2"}+ await adapter.send_draft("C1", 8, "partial", metadata=md)+ r = await adapter.send("C1", "complete", metadata=dict(md))+ # Fail-open: the plain send goes out (send acks fine here) — a+ # possible duplicate beats a silent loss after double ack loss.+ assert r.success+ assert [o for o in t.ops if o[0] == "draft" and o[1]], "seal attempted"+ assert [o for o in t.ops if o[0] == "send"], "fail-open plain send ran"+++class TestFrameAckLoss:+ @pytest.mark.asyncio+ async def test_lost_frame_ack_keeps_interception_armed(self):+ """THE round-2 regression: a timeout-shaped frame result must not+ disarm — the connector may have applied the frame, and the+ turn-final must still seal the stream."""+ t = AckLossTransport(lose_acks_for=("draft",), lose_times={"draft": 1})+ adapter, _ = _connected_adapter()+ adapter._transport = t+ md = {"message_id": "m.3"}+ r1 = await adapter.send_draft("C1", 9, "partial", metadata=md)+ assert not r1.success+ key = adapter._draft_key("C1", md)+ assert adapter._open_draft_by_chat.get(key) == 9, (+ "ambiguous frame result disarmed interception (round-2 finding 1b)"+ )+ final = await adapter.send("C1", "complete", metadata=dict(md))+ assert final.success+ seals = [o for o in t.ops if o[0] == "draft" and o[1]]+ assert len(seals) == 1 and seals[0][2] == "complete"++ @pytest.mark.asyncio+ async def test_definite_rejection_still_disarms(self):+ """Sibling guard: an explicit non-ambiguous rejection keeps the+ round-1 disarm semantics."""++ class RejectTransport:+ def __init__(self):+ self.ops = []++ async def send_outbound(self, payload, platform=None):+ self.ops.append((payload.get("op"), bool(payload.get("final"))))+ if payload.get("op") == "draft":+ return {"success": False, "error": "stream_gone"}+ return {"success": True, "message_id": "m"}++ adapter, _ = _connected_adapter()+ t = RejectTransport()+ adapter._transport = t+ md = {"message_id": "m.4"}+ r = await adapter.send_draft("C1", 10, "partial", metadata=md)+ assert not r.success+ assert not adapter._open_draft_by_chat, "definite rejection must disarm"+ await adapter.send("C1", "final", metadata=dict(md))+ assert t.ops[-1] == ("send", False)+++class TestTransportTagsAmbiguity:+ @pytest.mark.asyncio+ async def test_ws_transport_timeout_result_is_tagged(self):+ """Source-of-truth check on the production transport: the ack+ timeout branch carries ambiguous=True; fail-fast branches do not."""+ from gateway.relay.ws_transport import WebSocketRelayTransport++ transport = WebSocketRelayTransport.__new__(WebSocketRelayTransport)+ transport._closing = False+ transport._ws = object() # non-None so we reach the pending path+ transport._pending = {}+ transport._outbound_timeout_s = 0.01+ transport._bot_id_for = lambda p: None++ async def _send(frame):+ return None # sent fine; ack never arrives++ transport._send = _send+ result = await transport.send_outbound({"op": "send"})+ assert result["success"] is False+ assert result.get("ambiguous") is True++ transport._closing = True+ result2 = await transport.send_outbound({"op": "send"})+ assert result2["success"] is False+ assert "ambiguous" not in result2, "fail-fast paths are definite"diff --git a/tests/gateway/relay/test_relay_adapter.py b/tests/gateway/relay/test_relay_adapter.pyindex 137c0b15cd8..54612c249d2 100644--- a/tests/gateway/relay/test_relay_adapter.py+++ b/tests/gateway/relay/test_relay_adapter.py@@ -42,8 +42,20 @@ def test_advertises_descriptor_max_length():def test_supports_draft_streaming_follows_descriptor():+ # NS-658: the flag alone no longer advertises drafts — before the+ # "draft" op existed, flag=True was a latent lie (send_draft inherited+ # NotImplementedError). Advertisement now requires flag AND op.assert _adapter(supports_draft_streaming=False).supports_draft_streaming() is False- assert _adapter(supports_draft_streaming=True).supports_draft_streaming() is True+ assert (+ _adapter(supports_draft_streaming=False, supported_ops=("send", "draft"))+ .supports_draft_streaming()+ is False+ ), "op without flag must not advertise"+ assert (+ _adapter(supports_draft_streaming=True, supported_ops=("send", "draft"))+ .supports_draft_streaming()+ is True+ )def test_len_fn_utf16_counts_code_units():diff --git a/tests/gateway/relay/test_relay_live_cards.py b/tests/gateway/relay/test_relay_live_cards.pynew file mode 100644index 00000000000..6b6c46c57ff--- /dev/null+++ b/tests/gateway/relay/test_relay_live_cards.py@@ -0,0 +1,277 @@+"""Relay Slack live cards — gateway half (NS-658).++The relay adapter emits three new additive ops when the connector's+negotiated descriptor advertises them:++ {op: "draft", chat_id, draft_id, content, final, metadata}+ {op: "task_card", chat_id, card_id, chunks, metadata}+ {op: "task_card_stop", chat_id, card_id, metadata}++Gateway side is deliberately dumb: no Slack API knowledge, no new config+keys. Capability is descriptor-driven — an old connector that never+advertises "draft"/"task_card" gets byte-identical behavior to today.++Semantic bridge: the base send_draft contract is Telegram-shaped (draft+clears; final answer is a separate send). Slack native streaming makes the+stream THE message. The adapter tracks the open draft per chat; the+turn-final regular send() for that chat converts to draft(final=true) so+the connector seals the stream instead of posting a duplicate.+"""++from __future__ import annotations++import asyncio++import pytest++from gateway.config import PlatformConfig+from gateway.relay.adapter import RelayAdapter+from gateway.relay.descriptor import CONTRACT_VERSION, CapabilityDescriptor+from tests.gateway.relay.stub_connector import StubConnector+++def make_desc(**kw) -> CapabilityDescriptor:+ base = dict(+ 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="\U0001f4ac",+ platform_hint="",+ pii_safe=False,+ supported_ops=("send", "edit", "typing", "draft", "task_card"),+ )+ base.update(kw)+ return CapabilityDescriptor(**base)+++def _connected_adapter(**desc_kw):+ desc = make_desc(**desc_kw)+ stub = StubConnector(desc)+ adapter = RelayAdapter(PlatformConfig(), desc, transport=stub)+ return adapter, stub+++def _run(coro):+ return asyncio.get_event_loop().run_until_complete(coro)+++def loop():+ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ yield loop+ loop.close()+++# ---------------------------------------------------------------------------+# Draft streaming op+# ---------------------------------------------------------------------------+++class TestDraftOp:+ def test_send_draft_emits_draft_op(self, loop):+ adapter, stub = _connected_adapter()+ result = loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=7, content="hel")+ )+ assert result.success+ frames = [s for s in stub.sent if s.get("op") == "draft"]+ assert len(frames) == 1+ frame = frames[0]+ assert frame["chat_id"] == "C1"+ assert frame["draft_id"] == 7+ assert frame["content"] == "hel"+ assert frame["final"] is False++ def test_send_draft_requires_descriptor_op(self, loop):+ # supports_draft_streaming True but op NOT advertised: old connector.+ adapter, stub = _connected_adapter(+ supported_ops=("send", "edit", "typing")+ )+ with pytest.raises(NotImplementedError):+ loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=1, content="x")+ )+ assert not [s for s in stub.sent if s.get("op") == "draft"]++ def test_supports_draft_streaming_requires_both_flag_and_op(self):+ both, _ = _connected_adapter()+ assert both.supports_draft_streaming() is True+ flag_only, _ = _connected_adapter(+ supported_ops=("send", "edit", "typing")+ )+ assert flag_only.supports_draft_streaming() is False+ # Legacy connector with EMPTY supported_ops: fail-open elsewhere, but+ # draft must NOT fail open — the op did not exist pre-contract.+ legacy, _ = _connected_adapter(supported_ops=())+ assert legacy.supports_draft_streaming() is False++ def test_final_send_seals_open_draft(self, loop):+ adapter, stub = _connected_adapter()+ loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=7, content="hel")+ )+ loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=7, content="hello wor")+ )+ stub.next_draft_result = {"success": True, "message_id": "1723600000.1"}+ result = loop.run_until_complete(+ adapter.send("C1", "hello world", reply_to=None)+ )+ assert result.success+ # No regular send op — the final frame rides the draft stream.+ ops = [s["op"] for s in stub.sent]+ assert "send" not in ops, "final must seal the stream, not post anew"+ finals = [+ s for s in stub.sent if s.get("op") == "draft" and s.get("final")+ ]+ assert len(finals) == 1+ assert finals[0]["content"] == "hello world"+ # Stream ts comes back as the message identity.+ assert result.message_id == "1723600000.1"++ def test_send_without_open_draft_is_normal(self, loop):+ adapter, stub = _connected_adapter()+ loop.run_until_complete(adapter.send("C1", "plain", reply_to=None))+ assert [s["op"] for s in stub.sent] == ["send"]++ def test_draft_state_clears_after_seal(self, loop):+ adapter, stub = _connected_adapter()+ loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=7, content="a")+ )+ loop.run_until_complete(adapter.send("C1", "a!", reply_to=None))+ # Second send on the same chat is a NORMAL send again.+ loop.run_until_complete(adapter.send("C1", "followup", reply_to=None))+ ops = [s["op"] for s in stub.sent]+ assert ops == ["draft", "draft", "send"]++ def test_draft_failure_result_propagates(self, loop):+ adapter, stub = _connected_adapter()+ stub.next_draft_result = {"success": False, "error": "stream_gone"}+ result = loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=1, content="x")+ )+ assert not result.success+ # DEFINITE connector rejection disarms seal-interception: the+ # stream consumer falls back to edit-based streaming on this+ # failure, and its turn-final must go out as a REAL send — never+ # a seal on a stream the connector just rejected.+ stub.next_send_result = {"success": True, "message_id": "m2"}+ loop.run_until_complete(adapter.send("C1", "final", reply_to=None))+ assert [s["op"] for s in stub.sent][-1] == "send"++ def test_draft_transport_exception_keeps_interception_armed(self, loop):+ """Ambiguity contract (G-D1): a transport EXCEPTION — as opposed+ to an explicit rejection — may mean the frame was delivered, so+ interception stays armed and the turn-final still seals."""+ adapter, _ = _connected_adapter()++ class _FlakyOnce:+ def __init__(self):+ self.calls = 0++ async def send_outbound(self, payload, platform=None):+ self.calls += 1+ if self.calls == 1:+ raise ConnectionError("mid-write drop")+ return {"success": True, "message_id": "ts.9"}++ adapter._transport = _FlakyOnce()+ result = loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=2, content="x")+ )+ assert not result.success+ # Still armed: the turn-final converts to the sealing frame.+ final = loop.run_until_complete(adapter.send("C1", "final", reply_to=None))+ assert final.success+ assert final.message_id == "ts.9"++ def test_drafts_are_per_chat(self, loop):+ adapter, stub = _connected_adapter()+ loop.run_until_complete(+ adapter.send_draft(chat_id="C1", draft_id=1, content="a")+ )+ # A send to a DIFFERENT chat is untouched.+ loop.run_until_complete(adapter.send("D9", "other", reply_to=None))+ by_op = [(s["op"], s["chat_id"]) for s in stub.sent]+ assert ("send", "D9") in by_op+++# ---------------------------------------------------------------------------+# Task-card ops (#85476 TurnRunner seam, relay leg)+# ---------------------------------------------------------------------------+++def _tasks():+ return [+ {+ "id": "call_1",+ "title": "terminal",+ "status": "in_progress",+ "details": "ls -la",+ },+ {+ "id": "call_2",+ "title": "web_search",+ "status": "complete",+ "details": "slack startStream",+ },+ ]+++class TestTaskCardOps:+ def test_progress_emits_task_card_op(self, loop):+ adapter, stub = _connected_adapter()+ result = loop.run_until_complete(+ adapter.send_native_task_card_progress(+ chat_id="C1", tasks=_tasks(), reply_to="1700.100"+ )+ )+ assert result.success+ frames = [s for s in stub.sent if s.get("op") == "task_card"]+ assert len(frames) == 1+ assert frames[0]["card_id"] == "turn:1700.100"+ chunk_ids = [c["id"] for c in frames[0]["chunks"]]+ assert chunk_ids == ["call_1", "call_2"]+ statuses = {c["id"]: c["status"] for c in frames[0]["chunks"]}+ assert statuses["call_2"] == "complete"++ def test_stop_emits_task_card_stop(self, loop):+ adapter, stub = _connected_adapter()+ loop.run_until_complete(+ adapter.send_native_task_card_progress(+ chat_id="C1", tasks=_tasks(), reply_to="1700.100"+ )+ )+ loop.run_until_complete(+ adapter.stop_native_task_card_progress(chat_id="C1", reply_to="1700.100")+ )+ assert [s["op"] for s in stub.sent] == ["task_card", "task_card_stop"]++ def test_task_card_gated_on_descriptor(self, loop):+ adapter, stub = _connected_adapter(+ supported_ops=("send", "edit", "typing", "draft")+ )+ # No "task_card" in supported_ops: the TurnRunner's hasattr gate must+ # see NO capability — expose it via a probe method returning False,+ # and the send must be a clean no-op failure (never an exception on+ # the turn path).+ assert adapter.supports_native_task_cards() is False+ result = loop.run_until_complete(+ adapter.send_native_task_card_progress(+ chat_id="C1", tasks=_tasks(), reply_to="t"+ )+ )+ assert not result.success+ assert not stub.sent++ def test_task_card_legacy_empty_ops_not_fail_open(self):+ legacy, _ = _connected_adapter(supported_ops=())+ assert legacy.supports_native_task_cards() is Falsediff --git a/tests/gateway/relay/test_relay_multiplatform_semantics.py b/tests/gateway/relay/test_relay_multiplatform_semantics.pynew file mode 100644index 00000000000..42357d7684d--- /dev/null+++ b/tests/gateway/relay/test_relay_multiplatform_semantics.py@@ -0,0 +1,114 @@+"""Regression: stream semantics and draft capability resolve PER CHAT on+a multi-platform relay (PR 85796 review round 2, finding 2).++One RelayAdapter fronts N platforms (Phase 1.5): descriptors accumulate+per platform on the transport and outbound frames are tagged per chat.+The round-1 gate keyed draft_stream_is_message and+supports_draft_streaming() off the PRIMARY scalar descriptor only:++ - Slack primary + Telegram chat: the Telegram chat's turn-final was+ intercepted into draft(final=true) — no real Telegram history+ message (probed on the head);+ - Telegram primary + Slack chat: the Slack chat was denied native+ streaming entirely.++Both now resolve through _descriptor_for_chat (the same per-chat+machinery max_message_length already uses); the scalar remains the+fallback for unknown chats and single-platform gateways.+"""++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter, make_desc+++def _desc_for(platform, **kw):+ return make_desc(+ platform=platform,+ label=platform.title(),+ markdown_dialect="markdown_v2" if platform == "telegram" else "slack",+ max_message_length=4096,+ **kw,+ )+++class RecordingTransport:+ def __init__(self, descriptors_by_platform=None):+ self.ops = []+ self._descs = dict(descriptors_by_platform or {})++ def descriptor_for_platform(self, platform):+ return self._descs.get(platform)++ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "ts.1"}+++def _multi_adapter(primary="slack", others=("telegram",)):+ """Adapter with a primary descriptor + per-platform secondaries."""+ adapter, _ = _connected_adapter() if primary == "slack" else _connected_adapter(+ platform=primary, markdown_dialect="markdown_v2",+ supported_ops=("send", "edit", "typing", "draft"),+ )+ descs = {p: _desc_for(p) for p in (primary, *others)}+ t = RecordingTransport(descs)+ adapter._transport = t+ return adapter, t+++class TestPerChatStreamSemantics:+ @pytest.mark.asyncio+ async def test_slack_primary_telegram_chat_gets_real_final(self):+ """The round-2 probe: telegram chat on a Slack-primary adapter →+ frames stream, the final is a REAL send, never a seal."""+ adapter, t = _multi_adapter(primary="slack", others=("telegram",))+ adapter._platform_by_chat["TG1"] = "telegram"+ md = {"message_id": "m.1"}+ await adapter.send_draft("TG1", 3, "partial", metadata=md)+ r = await adapter.send("TG1", "complete", metadata=dict(md))+ assert r.success+ assert not [o for o in t.ops if o["op"] == "draft" and o.get("final")], (+ "telegram chat sealed by the Slack primary's semantic"+ )+ assert [o for o in t.ops if o["op"] == "send"]++ @pytest.mark.asyncio+ async def test_slack_primary_slack_chat_still_seals(self):+ adapter, t = _multi_adapter(primary="slack", others=("telegram",))+ adapter._platform_by_chat["C1"] = "slack"+ md = {"message_id": "m.2"}+ await adapter.send_draft("C1", 4, "partial", metadata=md)+ r = await adapter.send("C1", "complete", metadata=dict(md))+ assert r.success+ assert [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert not [o for o in t.ops if o["op"] == "send"]++ def test_telegram_primary_slack_chat_gets_native_streaming(self):+ """Inverse starvation: a Telegram primary must not deny a+ secondary Slack chat its draft capability or seal semantics."""+ adapter, _t = _multi_adapter(primary="telegram", others=("slack",))+ adapter._platform_by_chat["C9"] = "slack"+ assert adapter.supports_draft_streaming(chat_id="C9") is True+ assert adapter.stream_is_message_for_chat("C9") is True+ # And the primary's own chats keep telegram semantics:+ adapter._platform_by_chat["TG9"] = "telegram"+ assert adapter.stream_is_message_for_chat("TG9") is False++ def test_unknown_chat_falls_back_to_scalar(self):+ adapter, _t = _multi_adapter(primary="slack", others=("telegram",))+ # Never seen inbound — scalar (slack primary) governs.+ assert adapter.stream_is_message_for_chat("UNSEEN") is True++ @pytest.mark.asyncio+ async def test_capability_gate_respects_chat_descriptor(self):+ """A chat whose platform descriptor lacks the draft op must raise+ NotImplementedError even when the primary advertises it."""+ adapter, t = _multi_adapter(primary="slack", others=())+ # Telegram descriptor WITHOUT the draft op:+ t._descs["telegram"] = _desc_for(+ "telegram", supported_ops=("send", "edit", "typing")+ )+ adapter._platform_by_chat["TG2"] = "telegram"+ with pytest.raises(NotImplementedError):+ await adapter.send_draft("TG2", 5, "x", metadata={})diff --git a/tests/gateway/relay/test_relay_roundtrip_telegram.py b/tests/gateway/relay/test_relay_roundtrip_telegram.pyindex 70f900dee89..07ca273ce72 100644--- a/tests/gateway/relay/test_relay_roundtrip_telegram.py+++ b/tests/gateway/relay/test_relay_roundtrip_telegram.py@@ -37,6 +37,7 @@ def _telegram_descriptor() -> CapabilityDescriptor:label="Telegram",max_message_length=4096,supports_draft_streaming=True, # Telegram DMs support sendMessageDraft+ supported_ops=("send", "edit", "typing", "follow_up", "draft"),supports_edit=True,supports_threads=True, # forum topicsmarkdown_dialect="markdown_v2",diff --git a/tests/gateway/relay/test_relay_seal_cancellation.py b/tests/gateway/relay/test_relay_seal_cancellation.pynew file mode 100644index 00000000000..28d6dfe0b6e--- /dev/null+++ b/tests/gateway/relay/test_relay_seal_cancellation.py@@ -0,0 +1,84 @@+"""Regression: cancellation during the final seal must not orphan the+remote stream (PR 85796 review round 2, finding 4).++_seal_open_draft pops the open entry and writes the local tombstone+BEFORE awaiting transport I/O. CancelledError bypasses the failure+handling (it is not an Exception), so a cancel mid-seal left:++ remote stream: OPEN (live indicator until connector eviction)+ adapter._open_draft_by_chat: {} <- abandon finds nothing+ adapter._sealed_draft_by_chat: {key: id} <- premature tombstone++The seal now restores the open entry and drops its premature tombstone+on CancelledError before re-raising, so the consumer's abandon pass can+seal the stream in place.+"""++import asyncio++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class HangOnSealTransport:+ def __init__(self):+ self.ops = []+ self.hang_seal = True++ async def send_outbound(self, payload, platform=None):+ final = bool(payload.get("final"))+ self.ops.append((payload.get("op"), final, str(payload.get("content"))[:25]))+ if payload.get("op") == "draft" and final and self.hang_seal:+ await asyncio.sleep(30)+ return {"success": True, "message_id": "ts.1"}+++class TestCancelDuringSeal:+ @pytest.mark.asyncio+ async def test_cancel_mid_seal_restores_open_state(self):+ adapter, _ = _connected_adapter()+ t = HangOnSealTransport()+ adapter._transport = t+ md = {"message_id": "m.1"}+ await adapter.send_draft("C1", 11, "partial", metadata=md)+ key = adapter._draft_key("C1", md)++ task = asyncio.create_task(adapter.send("C1", "complete", metadata=dict(md)))+ await asyncio.sleep(0.05)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert adapter._open_draft_by_chat.get(key) == 11, (+ "cancelled seal must restore the open entry so abandon can close it"+ )+ assert key not in adapter._sealed_draft_by_chat, (+ "premature tombstone must not survive a cancelled seal"+ )++ @pytest.mark.asyncio+ async def test_abandon_after_cancelled_seal_closes_remote_stream(self):+ """End-to-end: cancel mid-seal, then the abandon pass (what the+ consumer's CancelledError handler runs) seals the stream."""+ adapter, _ = _connected_adapter()+ t = HangOnSealTransport()+ adapter._transport = t+ md = {"message_id": "m.2"}+ await adapter.send_draft("C1", 12, "partial on screen", metadata=md)++ task = asyncio.create_task(adapter.send("C1", "complete", metadata=dict(md)))+ await asyncio.sleep(0.05)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ t.hang_seal = False # transport recovers for the abandon pass+ r = await adapter.abandon_open_draft(+ "C1", "partial on screen", metadata=dict(md)+ )+ assert r.success+ seals = [o for o in t.ops if o[0] == "draft" and o[1]]+ # First seal attempt hung (cancelled); the abandon's seal landed.+ assert seals[-1][2] == "partial on screen"+ assert not adapter._open_draft_by_chatdiff --git a/tests/gateway/relay/test_relay_state_bounds.py b/tests/gateway/relay/test_relay_state_bounds.pynew file mode 100644index 00000000000..61be40063db--- /dev/null+++ b/tests/gateway/relay/test_relay_state_bounds.py@@ -0,0 +1,47 @@+"""Regression: draft/seal coordination dicts are bounded (PR 85796+review, M1).++_sealed_draft_by_chat's key embeds a per-turn identity, so every+completed turn added a permanent entry — unbounded growth for the life+of a long-running gateway process. _open_draft_by_chat could grow the+same way via abandoned entries. Both now FIFO-evict at the same cap the+sibling bounded caches use (and the connector's own tombstone store).+"""++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class OkTransport:+ async def send_outbound(self, payload, platform=None):+ return {"success": True, "message_id": "ts.1"}+++async def test_sealed_tombstones_are_bounded():+ adapter, _ = _connected_adapter()+ adapter._transport = OkTransport()+ cap = adapter._DRAFT_STATE_CAP+ for n in range(cap + 300):+ md = {"message_id": f"evt.{n}"}+ await adapter.send_draft("C1", 1000 + n, "x", metadata=md)+ await adapter.send("C1", "final", metadata=dict(md))+ assert len(adapter._sealed_draft_by_chat) <= cap+ assert len(adapter._open_draft_by_chat) <= cap+ # Newest tombstone survives (FIFO evicts oldest first).+ newest_key = adapter._draft_key("C1", {"message_id": f"evt.{cap + 299}"})+ assert newest_key in adapter._sealed_draft_by_chat+++async def test_open_drafts_are_bounded():+ adapter, _ = _connected_adapter()+ adapter._transport = OkTransport()+ cap = adapter._DRAFT_STATE_CAP+ # Arm many streams without ever sealing (abandoned-turn shape).+ for n in range(cap + 300):+ await adapter.send_draft(+ "C1", 2000 + n, "x", metadata={"message_id": f"evt.{n}"}+ )+ assert len(adapter._open_draft_by_chat) <= capdiff --git a/tests/gateway/relay/test_relay_stream_semantics_gating.py b/tests/gateway/relay/test_relay_stream_semantics_gating.pynew file mode 100644index 00000000000..b2943a35bd7--- /dev/null+++ b/tests/gateway/relay/test_relay_stream_semantics_gating.py@@ -0,0 +1,84 @@+"""Regression: stream-is-the-message is a SLACK semantic, not a relay+semantic (PR 85796 review, B4).++The base send_draft contract is Telegram-shaped: the draft animates and+clears client-side, and the final answer arrives as a separate REAL send+that becomes the history message. Slack native streaming inverts this —+the stream IS the message and the turn-final seals it in place.++The relay adapter hardcoded draft_stream_is_message = True for every+descriptor, so a Telegram (or any non-Slack) connector advertising the+draft op had its turn-final intercepted into draft(final=true): no real+message was ever posted to the chat history. Live-probed on the review+branch (`platform telegram … ops [draft(final=False), draft(final=True)]`,+no send op).++Now the flag is gated on the negotiated descriptor platform. A future+platform with genuine stream-is-the-message semantics should advertise it+via the descriptor rather than widening the gate by guesswork.+"""++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class RecordingTransport:+ def __init__(self):+ self.ops = []++ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "m.1"}+++class TestStreamIsMessageGating:+ def test_slack_descriptor_gets_stream_is_message(self):+ adapter, _ = _connected_adapter() # platform="slack" default+ assert adapter.draft_stream_is_message is True++ def test_telegram_descriptor_does_not(self):+ adapter, _ = _connected_adapter(+ platform="telegram",+ markdown_dialect="markdown_v2",+ supported_ops=("send", "edit", "typing", "draft"),+ )+ assert adapter.draft_stream_is_message is False++ @pytest.mark.asyncio+ async def test_telegram_final_is_a_real_send_not_a_seal(self):+ """The B4 probe: telegram + draft op → frames go out as drafts,+ the final goes out as a REAL send (history message), never as+ draft(final=true)."""+ adapter, _ = _connected_adapter(+ platform="telegram",+ markdown_dialect="markdown_v2",+ supported_ops=("send", "edit", "typing", "draft"),+ )+ t = RecordingTransport()+ adapter._transport = t+ md = {"reply_to_message_id": "evt.1"}+ await adapter.send_draft("T1", 3, "partial", metadata=md)+ r = await adapter.send("T1", "complete answer", metadata=dict(md))+ assert r.success+ ops = [(o["op"], o.get("final")) for o in t.ops]+ assert ("draft", False) in ops+ assert ("send", None) in ops, ops+ assert not [o for o in t.ops if o["op"] == "draft" and o.get("final")], (+ "telegram-shaped connector must never receive draft(final=true) "+ "as the turn-final — the draft clears client-side and the real "+ "send is the history message"+ )++ @pytest.mark.asyncio+ async def test_slack_final_still_seals(self):+ """Sibling guard: the gate must not have broken the Slack lane."""+ adapter, _ = _connected_adapter()+ t = RecordingTransport()+ adapter._transport = t+ md = {"reply_to_message_id": "evt.2"}+ await adapter.send_draft("C1", 4, "partial", metadata=md)+ r = await adapter.send("C1", "complete answer", metadata=dict(md))+ assert r.success+ assert [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert not [o for o in t.ops if o["op"] == "send"]diff --git a/tests/gateway/relay/test_relay_task_card_failures.py b/tests/gateway/relay/test_relay_task_card_failures.pynew file mode 100644index 00000000000..277c67d7468--- /dev/null+++ b/tests/gateway/relay/test_relay_task_card_failures.py@@ -0,0 +1,47 @@+"""Regression: task-card transport failures degrade, never raise+(PR 85796 review, B7).++send_native_task_card_progress / stop_native_task_card_progress let+transport exceptions escape. The stop runs in the progress loop's+finally block on the turn-cleanup path, and the cleanup awaits caught+only CancelledError — a socket drop during card publish/stop therefore+aborted cleanup BEFORE the final-delivery bookkeeping ran.+"""++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class ExplodingTransport:+ async def send_outbound(self, payload, platform=None):+ raise ConnectionError("socket dropped")+++def _adapter():+ adapter, _ = _connected_adapter()+ adapter._transport = ExplodingTransport()+ return adapter+++TASKS = [{"id": "t1", "title": "terminal", "status": "in_progress"}]+++class TestTaskCardTransportFailure:+ @pytest.mark.asyncio+ async def test_progress_returns_failed_result(self):+ adapter = _adapter()+ result = await adapter.send_native_task_card_progress(+ "C1", TASKS, reply_to="1700.1"+ )+ assert result.success is False+ assert "transport error" in (result.error or "")++ @pytest.mark.asyncio+ async def test_stop_returns_failed_result(self):+ adapter = _adapter()+ result = await adapter.stop_native_task_card_progress(+ "C1", reply_to="1700.1"+ )+ assert result.success is False+ assert "transport error" in (result.error or "")diff --git a/tests/gateway/relay/test_relay_turn_keying.py b/tests/gateway/relay/test_relay_turn_keying.pynew file mode 100644index 00000000000..b37e50bc6d5--- /dev/null+++ b/tests/gateway/relay/test_relay_turn_keying.py@@ -0,0 +1,194 @@+"""Regression: per-TURN stream/card identity (PR 85796 review, B2).++Keying coordination state on the thread anchor alone is simultaneously:++ - too coarse: two parallel turns replying INSIDE ONE Slack thread share+ thread_ts — turn A's final sealed turn B's stream with A's content+ while A's own stream stayed open (live probe on the review branch);+ - too fragile: a flat DM with no thread metadata degraded to the bare+ chat id, re-creating the original finding-#10 collision.++The key now prefers the triggering inbound message id (message_id /+reply_to_message_id — per-turn by construction), falling back to the+thread anchor, then the bare chat. Legacy callers with placement-only+metadata still seal via _match_open_draft's single-open-stream fallback,+but NEVER when multiple streams are open (a duplicate message is+recoverable; sealing someone else's stream is not).+"""++import asyncio++import pytest++from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class RecordingTransport:+ def __init__(self):+ self.ops = []+ self._n = 0++ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ self._n += 1+ return {"success": True, "message_id": f"ts.{self._n}"}+++def _adapter():+ adapter, _ = _connected_adapter()+ t = RecordingTransport()+ adapter._transport = t+ return adapter, t+++class TestSameThreadParallelTurns:+ @pytest.mark.asyncio+ async def test_two_turns_in_one_thread_do_not_collide(self):+ """The exact B2 probe: same thread_ts, distinct triggering message+ ids -> each turn seals its OWN stream with its OWN content."""+ adapter, t = _adapter()+ md_a = {"thread_ts": "1700.100", "message_id": "1700.111"}+ md_b = {"thread_ts": "1700.100", "message_id": "1700.222"}+ await adapter.send_draft("C1", 11, "A partial", metadata=md_a)+ await adapter.send_draft("C1", 12, "B partial", metadata=md_b)+ ra = await adapter.send("C1", "A final", metadata=dict(md_a))+ rb = await adapter.send("C1", "B final", metadata=dict(md_b))+ assert ra.success and rb.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert {(s["draft_id"], s["content"]) for s in seals} == {+ (11, "A final"),+ (12, "B final"),+ }, seals+ assert not [o for o in t.ops if o["op"] == "send"]++ @pytest.mark.asyncio+ async def test_card_ids_distinct_per_turn_in_one_thread(self):+ adapter, t = _adapter()+ md_a = {"thread_ts": "1700.100", "message_id": "1700.111"}+ md_b = {"thread_ts": "1700.100", "message_id": "1700.222"}+ tasks = [{"id": "t1", "title": "x", "status": "in_progress"}]+ await adapter.send_native_task_card_progress(+ "C1", tasks, reply_to=None, metadata=md_a+ )+ await adapter.send_native_task_card_progress(+ "C1", tasks, reply_to=None, metadata=md_b+ )+ cards = [o for o in t.ops if o["op"] == "task_card"]+ assert len({c["card_id"] for c in cards}) == 2, cards++ @pytest.mark.asyncio+ async def test_card_stop_uses_same_key_as_send(self):+ adapter, t = _adapter()+ md = {"thread_ts": "1700.100", "message_id": "1700.111"}+ tasks = [{"id": "t1", "title": "x", "status": "in_progress"}]+ await adapter.send_native_task_card_progress(+ "C1", tasks, reply_to=None, metadata=md+ )+ await adapter.stop_native_task_card_progress("C1", metadata=md)+ card_ids = {+ o["card_id"]+ for o in t.ops+ if o["op"] in ("task_card", "task_card_stop")+ }+ assert len(card_ids) == 1, t.ops+++class TestFlatDmKeying:+ @pytest.mark.asyncio+ async def test_flat_dm_without_thread_metadata_still_seals(self):+ """Flat DM: no thread anchor anywhere, but the consumer stamps+ reply_to_message_id on frames and the final alike."""+ adapter, t = _adapter()+ md = {"reply_to_message_id": "evt.1"}+ await adapter.send_draft("D1", 5, "partial", metadata=md)+ r = await adapter.send("D1", "final", metadata=dict(md))+ assert r.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1 and seals[0]["content"] == "final"++ @pytest.mark.asyncio+ async def test_parallel_flat_dm_turns_keyed_by_message_id(self):+ adapter, t = _adapter()+ md_a = {"reply_to_message_id": "evt.a"}+ md_b = {"reply_to_message_id": "evt.b"}+ await adapter.send_draft("D1", 21, "A partial", metadata=md_a)+ await adapter.send_draft("D1", 22, "B partial", metadata=md_b)+ await adapter.send("D1", "A final", metadata=dict(md_a))+ await adapter.send("D1", "B final", metadata=dict(md_b))+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert {(s["draft_id"], s["content"]) for s in seals} == {+ (21, "A final"),+ (22, "B final"),+ }+++class TestLegacyPlacementOnlyCallers:+ @pytest.mark.asyncio+ async def test_single_open_stream_absorbs_identityless_final(self):+ """A resolver-lane send with NO turn identity still seals when the+ chat has exactly one open stream (legacy compatibility)."""+ adapter, t = _adapter()+ md = {"thread_ts": "1700.9", "message_id": "1700.910"}+ await adapter.send_draft("C1", 31, "partial", metadata=md)+ r = await adapter.send("C1", "final", metadata=None)+ assert r.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1 and seals[0]["draft_id"] == 31++ @pytest.mark.asyncio+ async def test_thread_anchored_placement_only_final_seals(self):+ """Review r2, finding 5: metadata carrying ONLY a thread anchor is+ placement info, not turn identity — with one open turn-keyed+ stream in the chat, the final must absorb into it, not post a+ plain duplicate beside the live stream."""+ adapter, t = _adapter()+ md_frames = {"thread_ts": "1700.9", "message_id": "1700.910"}+ await adapter.send_draft("C1", 32, "partial", metadata=md_frames)+ r = await adapter.send("C1", "final", metadata={"thread_ts": "1700.9"})+ assert r.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1 and seals[0]["draft_id"] == 32, (+ "placement-only final must seal the single open stream"+ )+ assert not [o for o in t.ops if o["op"] == "send"]+ assert not adapter._open_draft_by_chat++ @pytest.mark.asyncio+ async def test_multiple_open_streams_identityless_send_stays_plain(self):+ """With several open streams, an identity-less send must NOT guess:+ plain send (recoverable) over sealing the wrong stream (not)."""+ adapter, t = _adapter()+ await adapter.send_draft(+ "C1", 41, "A", metadata={"message_id": "m.1"}+ )+ await adapter.send_draft(+ "C1", 42, "B", metadata={"message_id": "m.2"}+ )+ r = await adapter.send("C1", "ambiguous final", metadata=None)+ assert r.success+ assert [o["op"] for o in t.ops][-1] == "send"+ assert not [o for o in t.ops if o["op"] == "draft" and o.get("final")]++ @pytest.mark.asyncio+ async def test_placement_only_with_multiple_open_streams_stays_plain(self):+ adapter, t = _adapter()+ await adapter.send_draft(+ "C1", 43, "A", metadata={"thread_ts": "1700.9", "message_id": "m.3"}+ )+ await adapter.send_draft(+ "C1", 44, "B", metadata={"thread_ts": "1700.9", "message_id": "m.4"}+ )+ r = await adapter.send("C1", "ambiguous", metadata={"thread_ts": "1700.9"})+ assert r.success+ assert [o["op"] for o in t.ops][-1] == "send"++ @pytest.mark.asyncio+ async def test_message_id_mismatch_never_falls_back(self):+ """A caller WITH a message id whose key misses must not steal the+ one open stream — its identity is authoritative (different turn)."""+ adapter, t = _adapter()+ await adapter.send_draft("C1", 45, "A", metadata={"message_id": "m.5"})+ r = await adapter.send("C1", "other turn", metadata={"message_id": "m.OTHER"})+ assert r.success+ assert [o["op"] for o in t.ops][-1] == "send"+ assert adapter._open_draft_by_chat, "stream must survive the mismatch"diff --git a/tests/gateway/test_draft_id_restart_uniqueness.py b/tests/gateway/test_draft_id_restart_uniqueness.pynew file mode 100644index 00000000000..d8c198bc652--- /dev/null+++ b/tests/gateway/test_draft_id_restart_uniqueness.py@@ -0,0 +1,55 @@+"""Regression: draft ids must be unique across gateway incarnations+(PR 85796 review, B3; hardened per r2 follow-up).++The relay connector tombstones sealed streams by (channel, draft_id) and+those tombstones outlive the gateway process (relay gateways are+disposable / scale-to-zero by design). A counter that restarts at zero+replays already-sealed wire identities: the connector answers the new+turn's frames out of the old tombstone — zero Slack API calls, the OLD+message ts returned as the new turn's identity — and the new answer is+silently dropped while every layer above records success.++r2 hardening: the first fix seeded from epoch milliseconds, which still+collides on same-millisecond starts, forks, and clock steps. The seed is+now a random 49-bit process nonce — collision probability is negligible+and ids stay inside the connector's JS number range (2^53) with room for+realistic per-process turn counts.+"""++import subprocess+import sys++from gateway.stream_consumer import GatewayStreamConsumer++_JS_SAFE_MAX = 2**53+++class TestDraftIdRestartUniqueness:+ def test_seed_is_random_nonce_in_wire_range(self):+ seed = GatewayStreamConsumer._draft_id_counter+ assert seed > 0, "seed 0 replays wire identities after restart"+ # Leave headroom for per-process increments under the JS bound+ # the connector's draft_id?: number field implies.+ assert seed < 2**49+ assert seed + 10_000_000 < _JS_SAFE_MAX++ def test_two_incarnations_use_different_seeds(self):+ """Spawn two real fresh interpreters — the class-level seed must+ differ across process starts (this is exactly the scale-to-zero+ restart). Also implicitly proves the seed isn't wall-clock-locked:+ both processes start within the same second."""+ code = (+ "from gateway.stream_consumer import GatewayStreamConsumer;"+ "print(GatewayStreamConsumer._draft_id_counter)"+ )+ seeds = set()+ for _ in range(2):+ out = subprocess.run(+ [sys.executable, "-c", code],+ capture_output=True, text=True, check=True,+ )+ seeds.add(int(out.stdout.strip()))+ assert len(seeds) == 2, (+ f"two fresh incarnations minted the same draft-id seed: {seeds} — "+ "restart would replay identities the connector already sealed"+ )diff --git a/tests/gateway/test_interim_send_lanes.py b/tests/gateway/test_interim_send_lanes.pynew file mode 100644index 00000000000..2dac91a1db4--- /dev/null+++ b/tests/gateway/test_interim_send_lanes.py@@ -0,0 +1,83 @@+"""Regression: every gateway-side mid-turn send lane is marked interim+(PR 85796 review, B5 + heartbeat/inactivity findings).++Seal-interception on stream-is-the-message adapters converts the first+unmarked send to an armed (chat, turn) key into draft(final=true). The+consumer's own interim lanes (commentary, tail flush) were marked, but+four gateway-side lanes that fire DURING a streaming turn were not:++ - long-running heartbeat ("⏳ Working — N min"), default every 180s+ - inactivity warning ("⚠️ No activity …")+ - plain-text approval fallback (button lane failed)+ - background-review notice++Live probe: the 3-minute heartbeat sealed the live stream with status+text; the real final then posted as a duplicate, and later frames were+silently swallowed by the seal tombstone.++These tests pin the helper's contract and the adapter-level behavior for+a heartbeat-shaped send; the lane wiring itself is a one-line metadata+wrap per call site (grep `_interim_metadata(` in gateway/run.py).+"""++import pytest++from gateway.run import _interim_metadata+from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class RecordingTransport:+ def __init__(self):+ self.ops = []++ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "m.1"}+++class TestInterimMetadataHelper:+ def test_marks_and_preserves(self):+ md = _interim_metadata({"thread_id": "t1", "notify": False})+ assert md["_interim_send"] is True+ assert md["thread_id"] == "t1"++ def test_none_input(self):+ assert _interim_metadata(None) == {"_interim_send": True}++ def test_does_not_mutate_input(self):+ src = {"thread_id": "t1"}+ _interim_metadata(src)+ assert "_interim_send" not in src+++class TestHeartbeatShapedSendDoesNotSeal:+ @pytest.mark.asyncio+ async def test_status_send_with_interim_marker_leaves_stream_open(self):+ """The exact live-probe scenario, fixed: an armed stream + a+ heartbeat-shaped status send marked via _interim_metadata → the+ stream stays open, the status posts as its own message, and the+ true turn-final still seals with the answer."""+ adapter, _ = _connected_adapter()+ t = RecordingTransport()+ adapter._transport = t+ md = {"thread_ts": "1700.5", "message_id": "1700.501"}+ await adapter.send_draft("C1", 7, "partial answer", metadata=md)++ r = await adapter.send(+ "C1",+ "⏳ Working — 3 min — terminal",+ metadata=_interim_metadata(dict(md)),+ )+ assert r.success+ # Status went out as a plain send; no seal, marker stripped.+ sends = [o for o in t.ops if o["op"] == "send"]+ assert len(sends) == 1+ assert "_interim_send" not in (sends[0].get("metadata") or {})+ assert not [o for o in t.ops if o["op"] == "draft" and o.get("final")]++ # The real final still seals with the ANSWER, not the status text.+ rf = await adapter.send("C1", "partial answer, done.", metadata=dict(md))+ assert rf.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1+ assert seals[0]["content"] == "partial answer, done."diff --git a/tests/gateway/test_notice_delivery.py b/tests/gateway/test_notice_delivery.pyindex 2a78f6583f3..e1477324dc9 100644--- a/tests/gateway/test_notice_delivery.py+++ b/tests/gateway/test_notice_delivery.py@@ -42,7 +42,10 @@ async def test_deliver_platform_notice_uses_private_delivery_when_configured():"C123","U123","hello",- metadata={"thread_id": "111.222"},+ # user_id rides along since the R3-5 per-turn identity stamp (Slack+ # sources carry their author in thread metadata for the connector's+ # chat.startStream recipient fields). Additive and harmless here.+ metadata={"thread_id": "111.222", "user_id": "U123"},)adapter.send.assert_not_awaited()diff --git a/tests/gateway/test_relay_seal_failure.py b/tests/gateway/test_relay_seal_failure.pynew file mode 100644index 00000000000..9308c4ce08c--- /dev/null+++ b/tests/gateway/test_relay_seal_failure.py@@ -0,0 +1,135 @@+"""Regression: seal-time transport failure must never lose or duplicate+the final answer (silent-loss class — PR 85796 review finding B1/B3-adjacent).++Three invariants:++1. A transport exception during the sealing draft frame retries the SAME+ idempotent frame once (the connector's sealed-key tombstone returns the+ original stream ts for a repeated final, so a retry can never open a+ second stream or post a duplicate).++2. When the seal cannot be delivered at all, the adapter reports failure —+ and the consumer must NOT record final delivery. The prior behavior+ let the turn-final retry re-enter the draft-frame path, whose no-op+ dedupe compared against the last UNSEALED frame and reported success+ with zero transport calls: flags went green, the gateway suppressed its+ fallback, and the user never received the answer.++3. The turn-final retry path always calls with finalize=True so it can+ never be routed through the draft-frame branch at all.+"""++import asyncio++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class FlakyTransport:+ """Raises on selected ops; records everything that got through."""++ def __init__(self, raise_on=(), raise_times=None):+ self.ops = []+ self.attempts = []+ self.raise_on = set(raise_on)+ # op -> remaining raise count (None = raise forever)+ self.raise_times = dict(raise_times or {})++ def _should_raise(self, op, final):+ key = "seal" if (op == "draft" and final) else op+ if key not in self.raise_on:+ return False+ remaining = self.raise_times.get(key)+ if remaining is None:+ return True+ if remaining <= 0:+ return False+ self.raise_times[key] = remaining - 1+ return True++ async def send_outbound(self, payload, platform=None):+ op = payload.get("op")+ final = bool(payload.get("final"))+ self.attempts.append((op, final))+ if self._should_raise(op, final):+ raise ConnectionError("socket dropped mid-write")+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "1723600000.42"}+++def _armed_adapter(transport):+ adapter, _ = _connected_adapter()+ adapter._transport = transport+ return adapter+++class TestSealTransportError:+ @pytest.mark.asyncio+ async def test_seal_exception_retries_same_idempotent_frame(self):+ """One transport drop during the seal → the SAME final frame is+ retried and its success (with the stream ts) is the send result."""+ t = FlakyTransport(raise_on=("seal",), raise_times={"seal": 1})+ adapter = _armed_adapter(t)+ md = {"thread_ts": "1700.1"}+ await adapter.send_draft("C1", 7, "answer", metadata=md)+ result = await adapter.send("C1", "answer complete", metadata=md)+ assert result.success+ assert result.message_id == "1723600000.42"+ seal_attempts = [a for a in t.attempts if a == ("draft", True)]+ assert len(seal_attempts) == 2, "seal must be retried exactly once"+ # Both attempts carried the identical frame (idempotent replay).+ finals = [o for o in t.ops if o.get("op") == "draft" and o.get("final")]+ assert len(finals) == 1 and finals[0]["content"] == "answer complete"+ # No plain send: a landed retry means no duplicate.+ assert not [o for o in t.ops if o.get("op") == "send"]++ @pytest.mark.asyncio+ async def test_seal_exception_twice_reports_failure(self):+ """Both attempts down → SendResult failure (fail-open plain send in+ send() then also fails on the dead transport; the caller sees the+ error instead of a phantom success)."""+ t = FlakyTransport(raise_on=("seal", "send"))+ adapter = _armed_adapter(t)+ md = {"thread_ts": "1700.2"}+ await adapter.send_draft("C1", 8, "answer", metadata=md)+ with pytest.raises(ConnectionError):+ # Seal fails twice -> falls through to plain send -> transport+ # still down -> the plain-send exception propagates (existing+ # plain-send contract; callers catch).+ await adapter.send("C1", "answer complete", metadata=md)+ # The seal was attempted twice, never recorded as delivered.+ assert [a for a in t.attempts if a == ("draft", True)] == [+ ("draft", True),+ ("draft", True),+ ]++ @pytest.mark.asyncio+ async def test_consumer_never_records_delivery_on_dead_transport(self):+ """THE silent-loss regression: transport dead at seal time → the+ consumer's delivery flags must stay False so the gateway's normal+ fallback send path still owns the final."""+ t = FlakyTransport(raise_on=("seal", "send"))+ adapter = _armed_adapter(t)+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(+ adapter, "C1", cfg, metadata={"thread_ts": "1700.3"},+ )+ task = asyncio.create_task(sc.run())+ sc.on_delta("complete answer")+ await asyncio.sleep(0.08)+ sc.finish("complete answer")+ await task+ # Frames streamed, but the final never reached the wire:+ assert [o for o in t.ops if o.get("op") == "draft" and not o.get("final")]+ assert not [o for o in t.ops if o.get("op") == "draft" and o.get("final")]+ assert not [o for o in t.ops if o.get("op") == "send"]+ # The consumer must not claim delivery — this is what previously+ # suppressed the gateway fallback and silently ate the answer.+ assert sc.final_response_sent is False+ assert getattr(sc, "_final_content_delivered", False) is False+ assert sc.delivered_final_matches("complete answer") is not Truediff --git a/tests/gateway/test_slack.py b/tests/gateway/test_slack.pyindex 2d770c236b0..1f0d03e57c1 100644--- a/tests/gateway/test_slack.py+++ b/tests/gateway/test_slack.py@@ -3005,6 +3005,12 @@ class TestAssistantThreadLifecycle:assert runner._thread_metadata_for_source(msg_event.source) == {"thread_id": "171.111","slack_team_id": "T_OTHER",+ # R3-5: per-turn egress identity stamped from THIS turn's source+ # (not the relay adapter's mutable per-chat cache) so concurrent+ # turns in one channel cannot cross recipient identities on the+ # connector's chat.startStream recipient fields.+ "scope_id": "T_OTHER",+ "user_id": "U_USER",}@pytest.mark.asynciodiff --git a/tests/gateway/test_slack_turn_recipient_identity.py b/tests/gateway/test_slack_turn_recipient_identity.pynew file mode 100644index 00000000000..2e42a31a308--- /dev/null+++ b/tests/gateway/test_slack_turn_recipient_identity.py@@ -0,0 +1,84 @@+"""Per-turn Slack egress identity (R3-5, connector PR gateway-gateway#210).++The relay connector fills chat.startStream's recipient_user_id /+recipient_team_id (required for channel streams) from metadata.user_id /+metadata.scope_id. Before this fix the gateway only stamped slack_team_id+per-turn; user_id (and scope_id) were left for the relay adapter's+_with_scope fallback, which reads per-chat caches keyed only by chat_id —+mutable state that a CONCURRENT turn overwrites. Two users with+overlapping turns in one channel could open U1's stream with U2 as the+recipient.++These tests pin the fix: _thread_metadata_for_source stamps the authentic+per-turn identity from the turn's OWN source, and the cache fallback in+RelayAdapter._with_scope no longer decides for turns that carry it.+"""++from types import SimpleNamespace++from gateway.platforms.base import Platform+from gateway.run import GatewayRunner+++def _slack_source(user_id: str, chat_id: str = "C_SHARED") -> SimpleNamespace:+ return SimpleNamespace(+ platform=Platform.SLACK,+ chat_id=chat_id,+ thread_id="1700.100",+ chat_type="channel",+ message_id="1700.100",+ scope_id="T_TEAM",+ user_id=user_id,+ )+++def test_thread_metadata_stamps_per_turn_user_and_scope():+ runner = object.__new__(GatewayRunner)+ meta = runner._thread_metadata_for_source(_slack_source("U_ALICE"))+ assert meta is not None+ assert meta["user_id"] == "U_ALICE"+ assert meta["scope_id"] == "T_TEAM"+ assert meta["slack_team_id"] == "T_TEAM"+++def test_concurrent_turns_carry_their_own_identity():+ """The R3-5 interleaving: U2's turn starting must not change what U1's+ already-built metadata carries — identity is per-turn source data, not+ shared per-chat state."""+ runner = object.__new__(GatewayRunner)+ meta_alice = runner._thread_metadata_for_source(_slack_source("U_ALICE"))+ # U2's turn begins in the SAME channel before U1's stream opens.+ meta_bob = runner._thread_metadata_for_source(_slack_source("U_BOB"))+ assert meta_alice is not None and meta_bob is not None+ assert meta_alice["user_id"] == "U_ALICE"+ assert meta_bob["user_id"] == "U_BOB"+++def test_relay_with_scope_does_not_override_per_turn_identity():+ """_with_scope must be fill-only: a turn that already carries user_id /+ scope_id keeps them even when the per-chat cache holds another user+ (the overwrite that caused the R3-5 cross-recipient hazard)."""+ from gateway.relay.adapter import RelayAdapter++ adapter = object.__new__(RelayAdapter)+ # The mutable cache holds the OTHER user (their turn arrived later).+ adapter._scope_by_chat = {"C_SHARED": "T_CACHED"}+ adapter._dm_user_by_chat = {"C_SHARED": "U_BOB"}+ merged = adapter._with_scope(+ "C_SHARED", {"user_id": "U_ALICE", "scope_id": "T_TEAM"}+ )+ assert merged["user_id"] == "U_ALICE"+ assert merged["scope_id"] == "T_TEAM"+++def test_relay_with_scope_still_fills_when_turn_carries_nothing():+ """Restart/synthetic sends (no per-turn identity) keep the cache+ fallback — the fix narrows the cache's authority, not its existence."""+ from gateway.relay.adapter import RelayAdapter++ adapter = object.__new__(RelayAdapter)+ adapter._scope_by_chat = {"C_SHARED": "T_CACHED"}+ adapter._dm_user_by_chat = {"C_SHARED": "U_CACHED"}+ merged = adapter._with_scope("C_SHARED", {"thread_id": "1700.100"})+ assert merged["user_id"] == "U_CACHED"+ assert merged["scope_id"] == "T_CACHED"diff --git a/tests/gateway/test_split_final_suffix_reconcile.py b/tests/gateway/test_split_final_suffix_reconcile.pynew file mode 100644index 00000000000..e1586e167d7--- /dev/null+++ b/tests/gateway/test_split_final_suffix_reconcile.py@@ -0,0 +1,109 @@+"""Regression: an authoritative final that prefix-extends a SPLIT+delivery reconciles by suffix, not by full resend (PR 85796 review+round 2, finding 3).++The _FINAL_TEXT adoption guard refuses wholesale adoption on split+turns — correct (#78541: sealed heads would repeat inside the tail) but+previously absolute: a post-split verifier footer never entered the+ledger, delivered_final_matches() reported a mismatch, and the gateway+resent the ENTIRE body+footer after the split chunks. Now the strictly+prefix-extending case appends only the missing suffix to the live tail+and the ledger; non-prefix rewrites keep the full-resend fallback.+"""++import asyncio++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+++def _make_adapter():+ from gateway.platforms.base import BasePlatformAdapter, SendResult++ A = type("SplitAdapter", (BasePlatformAdapter,), {"MAX_MESSAGE_LENGTH": 4096})+ A.__abstractmethods__ = frozenset()+ a = A.__new__(A)+ a._typing_paused = set()+ a._fatal_error_message = None+ a.send_calls = []+ a.edit_calls = []++ async def _send(chat_id, content, reply_to=None, metadata=None, **kw):+ a.send_calls.append(content)+ return SendResult(success=True, message_id=f"m{len(a.send_calls)}")+ a.send = _send++ async def _edit(chat_id, message_id, content, **kw):+ a.edit_calls.append({"id": message_id, "content": content})+ return SendResult(success=True, message_id=message_id)+ a.edit_message = _edit+ return a+++BODY = "the split answer body"+FOOTER = "\n\n⚠️ File-mutation verifier: 1 file(s) were NOT modified this turn."+++def _consumer(adapter):+ cfg = StreamConsumerConfig(+ transport="edit", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ return GatewayStreamConsumer(adapter, "D1", cfg)+++class TestSplitSuffixReconcile:+ @pytest.mark.asyncio+ async def test_prefix_extending_final_delivers_only_suffix(self):+ adapter = _make_adapter()+ sc = _consumer(adapter)+ task = asyncio.create_task(sc.run())+ sc.on_delta(BODY)+ await asyncio.sleep(0.06)+ # Simulate an overflow-adopted split mid-turn: heads sealed, the+ # ledger holds full text, _accumulated holds the tail only.+ sc._turn_split_delivery = True+ sc.finish(BODY + FOOTER)+ await task+ # The recorded payload reconciles with the authoritative final —+ # the gateway will NOT resend the body+footer.+ assert sc.delivered_final_matches(BODY + FOOTER) is True+ # And the footer actually reached the platform (rode the final+ # edit/send), rather than reconciling vacuously.+ all_payloads = adapter.send_calls + [+ e["content"] for e in adapter.edit_calls+ ]+ assert any(FOOTER.strip() in p for p in all_payloads)+ # The body was NOT re-delivered whole after the split: no payload+ # equals the full body+footer via a fresh send while heads were+ # already on screen — the suffix rode the existing tail.+ assert all(+ p.startswith(BODY) or FOOTER.strip() in p for p in all_payloads+ )++ @pytest.mark.asyncio+ async def test_non_prefix_rewrite_keeps_mismatch(self):+ """A rewritten final (not a prefix extension) must still report a+ mismatch so the gateway's full resend delivers the true final."""+ adapter = _make_adapter()+ sc = _consumer(adapter)+ task = asyncio.create_task(sc.run())+ sc.on_delta(BODY)+ await asyncio.sleep(0.06)+ sc._turn_split_delivery = True+ rewritten = "a completely different final answer"+ sc.finish(rewritten)+ await task+ assert sc.delivered_final_matches(rewritten) is False++ @pytest.mark.asyncio+ async def test_unsplit_turn_adoption_unchanged(self):+ adapter = _make_adapter()+ sc = _consumer(adapter)+ task = asyncio.create_task(sc.run())+ sc.on_delta(BODY)+ await asyncio.sleep(0.06)+ sc.finish(BODY + FOOTER)+ await task+ assert sc.delivered_final_matches(BODY + FOOTER) is Truediff --git a/tests/gateway/test_stale_finalize_suppression.py b/tests/gateway/test_stale_finalize_suppression.pyindex 1e66072f7e4..15d591c8c99 100644--- a/tests/gateway/test_stale_finalize_suppression.py+++ b/tests/gateway/test_stale_finalize_suppression.py@@ -232,12 +232,21 @@ async def test_stale_finalize_does_not_suppress_complete_response(assert any(FULL_RESPONSE in payload for payload in all_payloads), (f"complete response never reached the platform; payloads: {all_payloads!r}")- # The preferred recovery is an in-place reconciliation edit of the- # streamed message (single corrected message, no duplicate).+ # The recovery must not duplicate: when the gateway suppressed its normal+ # final send (already_sent), the complete response must have been the+ # payload of the message that finalized on screen — either an in-place+ # reconciliation/finalize edit, or (consumer-declared final contract,+ # 2026-08-16) the primary send itself when the authoritative final was+ # adopted before the first flush. Both shapes are single-message.if result.get("already_sent"):- assert any(+ _edit_carried = any(e["content"] == FULL_RESPONSE and e["finalize"] for e in adapter.edits- ), "already_sent=True but no edit carried the complete response"+ )+ _send_carried = any(c["content"] == FULL_RESPONSE for c in adapter.sent)+ assert _edit_carried or _send_carried, (+ "already_sent=True but neither an edit nor the primary send "+ "carried the complete response"+ )@pytest.mark.asynciodiff --git a/tests/gateway/test_stream_abandon_on_turn_death.py b/tests/gateway/test_stream_abandon_on_turn_death.pynew file mode 100644index 00000000000..5557b0691a1--- /dev/null+++ b/tests/gateway/test_stream_abandon_on_turn_death.py@@ -0,0 +1,106 @@+"""Regression: a dying turn closes its native stream (PR 85796 review, B8).++Stale-generation exits and cancellations returned from run() with the+native stream still open: the Slack message kept its live streaming+indicator forever, and the adapter's armed interception state survived+into the next turn (which could inherit the key and seal a dead+draft_id). The consumer now calls adapter.abandon_open_draft on both+death paths — sealing in place with the last delivered frame, claiming+nothing (no delivery flags).+"""++import asyncio++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+from tests.gateway.relay.test_relay_live_cards import _connected_adapter+++class RecordingTransport:+ def __init__(self):+ self.ops = []++ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "ts.1"}+++def _consumer(run_still_current=None):+ adapter, _ = _connected_adapter()+ t = RecordingTransport()+ adapter._transport = t+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(+ adapter, "C1", cfg,+ metadata={"thread_ts": "1700.8", "message_id": "1700.801"},+ run_still_current=run_still_current,+ )+ return sc, adapter, t+++class TestAbandonOnTurnDeath:+ @pytest.mark.asyncio+ async def test_stale_generation_seals_open_stream(self):+ """/new mid-stream: run_still_current flips False → the open+ stream is sealed with the on-screen text, and no delivery is+ claimed."""+ _alive = [True]+ sc, adapter, t = _consumer(run_still_current=lambda: _alive[0])+ task = asyncio.create_task(sc.run())+ sc.on_delta("partial answer on screen")+ await asyncio.sleep(0.08)+ assert adapter._open_draft_by_chat, "stream should be armed"+ _alive[0] = False+ await task+ assert not adapter._open_draft_by_chat, "stream left armed after stale exit"+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1+ assert seals[0]["content"] == "partial answer on screen"+ assert sc.final_response_sent is False++ @pytest.mark.asyncio+ async def test_cancellation_seals_open_stream(self):+ sc, adapter, t = _consumer()+ task = asyncio.create_task(sc.run())+ sc.on_delta("partial before stop")+ await asyncio.sleep(0.08)+ assert adapter._open_draft_by_chat+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ assert not adapter._open_draft_by_chat, "stream left armed after cancel"+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1+ assert sc.final_response_sent is False++ @pytest.mark.asyncio+ async def test_abandon_without_open_stream_is_noop(self):+ sc, adapter, t = _consumer()+ await sc._abandon_native_stream()+ assert t.ops == []++ @pytest.mark.asyncio+ async def test_next_turn_not_intercepted_after_abandon(self):+ """The B8 inheritance hazard: after an abandoned turn, a NEW turn+ on the same key must arm and seal normally with its own content."""+ _alive = [True]+ sc, adapter, t = _consumer(run_still_current=lambda: _alive[0])+ task = asyncio.create_task(sc.run())+ sc.on_delta("old turn partial")+ await asyncio.sleep(0.08)+ _alive[0] = False+ await task+ # Next turn, same chat/keys, new draft_id:+ md = {"thread_ts": "1700.8", "message_id": "1700.801"}+ await adapter.send_draft("C1", 999, "new turn", metadata=md)+ r = await adapter.send("C1", "new turn final", metadata=dict(md))+ assert r.success+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert seals[-1]["draft_id"] == 999+ assert seals[-1]["content"] == "new turn final"diff --git a/tests/gateway/test_stream_consumer_draft.py b/tests/gateway/test_stream_consumer_draft.pyindex 1cb7f6beb4c..fe7377c720b 100644--- a/tests/gateway/test_stream_consumer_draft.py+++ b/tests/gateway/test_stream_consumer_draft.py@@ -140,6 +140,32 @@ class TestDraftStreamingHappyPath:assert final_metadata.get("notify") is Trueassert "expect_edits" not in final_metadata+ @pytest.mark.asyncio+ async def test_stream_is_message_preserves_cumulative_text_across_tool_boundaries(self):+ """Slack native streams accept cumulative frames. A tool boundary must+ not clear the consumer accumulator, otherwise every next segment is a+ non-prefix snapshot and the connector appends the whole answer again."""+ adapter = _make_draft_capable_adapter()+ adapter.draft_stream_is_message = True+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ consumer = GatewayStreamConsumer(adapter, "C1", cfg)++ task = asyncio.create_task(consumer.run())+ consumer.on_delta("first segment")+ await asyncio.sleep(0.05)+ consumer.on_segment_break()+ await asyncio.sleep(0.05)+ consumer.on_delta(" second segment")+ await asyncio.sleep(0.05)+ consumer.finish()+ await task++ contents = [call["content"] for call in adapter.draft_calls]+ assert contents[-1] == "first segment second segment"+@pytest.mark.asyncioasync def test_edit_preview_still_marks_expect_edits(self):adapter = _make_draft_capable_adapter(supports_draft=False)diff --git a/tests/gateway/test_stream_final_adoption_gate.py b/tests/gateway/test_stream_final_adoption_gate.pynew file mode 100644index 00000000000..02f07bfa5f8--- /dev/null+++ b/tests/gateway/test_stream_final_adoption_gate.py@@ -0,0 +1,84 @@+"""Regression: only a genuinely COMPLETED turn's final_response may be+adopted as the stream's authoritative finalize payload (PR 85796 review,+B6).++agent/conversation_loop.py's interrupt/abort paths return+{completed: False, interrupted: True, final_response: "Operation+interrupted during …"} with NO failed key. The finish(final_text) gate+checked only `not failed`, so the diagnostic was adopted: it sealed the+user's streamed partial answer over with the interrupt text, AND+delivered_final_matches then reconciled — suppressing the gateway's own+error-delivery path, so the diagnostic was the only thing left.++The taxonomy was enumerated from the production writers (all 27+final_response-bearing return shapes in conversation_loop.py): every+non-happy-path shape carries completed: False; the happy path routes+through turn_finalizer.finalize_turn which computes completed=True.+Gate: completed is not False AND not interrupted AND not failed.+"""++from types import SimpleNamespace+++def _adoption_gate(result) -> bool:+ """Mirror of the finish(final_text) adoption gate in gateway/run.py.++ Kept in sync by the comment at the call site; this test pins the+ CONTRACT (which result shapes may move delivery ownership into the+ stream consumer), the wiring test below pins the call.+ """+ return (+ isinstance(result, dict)+ and not result.get("failed")+ and not result.get("interrupted")+ and result.get("completed") is not False+ )+++class TestAdoptionGate:+ def test_happy_path_adopts(self):+ assert _adoption_gate(+ {"completed": True, "failed": False, "interrupted": False,+ "final_response": "the answer"}+ )++ def test_interrupt_shape_rejected(self):+ # conversation_loop.py:3089 / 4716 / 6040 / 7279 shape — no failed key.+ assert not _adoption_gate(+ {"completed": False, "interrupted": True,+ "final_response": "Operation interrupted during retry (…)."}+ )++ def test_failed_shape_rejected(self):+ assert not _adoption_gate(+ {"completed": False, "failed": True, "final_response": "boom"}+ )++ def test_diagnostic_noncompleted_shapes_rejected(self):+ # Shapes with neither failed nor interrupted but completed: False —+ # retry exhaustion, truncation, codex-incomplete (all diagnostics).+ for fr in (+ "Response truncated due to output length limit",+ "Codex response remained incomplete after 3 continuation attempts",+ ):+ assert not _adoption_gate({"completed": False, "final_response": fr})++ def test_legacy_result_without_completed_key_adopts(self):+ # Duck-type safety: a result dict lacking the key entirely (older+ # callers/doubles) keeps the pre-review behavior.+ assert _adoption_gate({"final_response": "answer"})+++class TestGateWiring:+ def test_run_py_gate_matches_contract(self):+ """The gate in gateway/run.py must contain the interrupted and+ completed checks — a source-level pin so the contract test above+ cannot drift green while the call site regresses."""+ import inspect+ import gateway.run as run_mod++ src = inspect.getsource(run_mod)+ anchor = src.index("_final_for_stream = None")+ window = src[anchor : anchor + 1200]+ assert 'not result.get("interrupted")' in window+ assert 'result.get("completed") is not False' in windowdiff --git a/tests/gateway/test_stream_final_contract.py b/tests/gateway/test_stream_final_contract.pynew file mode 100644index 00000000000..303f44429c5--- /dev/null+++ b/tests/gateway/test_stream_final_contract.py@@ -0,0 +1,268 @@+"""Regression: the consumer-declared final + interim-send contract+(live findings, 2026-08-16 canary — the duplicate-final class).++Three invariants:++1. ``finish(final_text=...)`` makes the finalize payload the AUTHORITATIVE+ completed final_response — post-stream augmentation (file-mutation+ verifier footer) rides the seal/final edit instead of arriving via a+ separate corrective send (live finding #11).++2. Interim sends (commentary) from the consumer carry ``_interim_send``+ metadata, and the relay adapter's seal-interception ignores them — a+ mid-turn commentary must never seal the live native stream (which+ orphaned the true final into a plain-send duplicate).++3. The queued-follow-up lane reconciles an unconfirmed final by EDITING the+ consumer's delivered message in place, not by plain-sending a duplicate.+"""++import asyncio+from types import SimpleNamespace++import pytest++from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig+++def _make_draft_adapter():+ """BasePlatformAdapter subclass with stream-is-the-message drafts."""+ from gateway.platforms.base import BasePlatformAdapter, SendResult++ A = type("StreamIsMsgAdapter", (BasePlatformAdapter,), {"MAX_MESSAGE_LENGTH": 39000})+ A.__abstractmethods__ = frozenset()+ a = A.__new__(A)+ a._typing_paused = set()+ a._fatal_error_message = None+ a.draft_stream_is_message = True+ a.draft_calls = []+ a.send_calls = []+ a.edit_calls = []++ def _supports(chat_type=None, metadata=None):+ return True+ a.supports_draft_streaming = _supports++ async def _send_draft(*, chat_id, draft_id, content, metadata=None):+ a.draft_calls.append({"draft_id": draft_id, "content": content})+ return SendResult(success=True, message_id=None)+ a.send_draft = _send_draft++ async def _send(chat_id, content, reply_to=None, metadata=None, **kw):+ a.send_calls.append({"content": content, "metadata": dict(metadata or {})})+ return SendResult(success=True, message_id="sealed_ts_1")+ a.send = _send++ async def _edit(chat_id, message_id, content, **kw):+ a.edit_calls.append({"message_id": message_id, "content": content})+ return SendResult(success=True, message_id=message_id)+ a.edit_message = _edit+ return a+++class TestConsumerDeclaredFinal:+ @pytest.mark.asyncio+ async def test_finish_final_text_rides_the_final_send(self):+ """The footer-bearing final_response must BE the finalize payload —+ one message, no separate corrective send needed."""+ adapter = _make_draft_adapter()+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(adapter, "D1", cfg)++ task = asyncio.create_task(sc.run())+ sc.on_delta("streamed answer body")+ await asyncio.sleep(0.06)+ # Turn completes; turn_finalizer appended the verifier footer.+ final_with_footer = (+ "streamed answer body\n\n"+ "⚠️ File-mutation verifier: 1 file(s) were NOT modified this turn."+ )+ sc.finish(final_with_footer)+ await task++ # The turn-final send carried the COMPLETE footer-bearing final.+ assert adapter.send_calls, "expected a turn-final send"+ assert adapter.send_calls[-1]["content"] == final_with_footer+ # And the recorded payload reconciles → gateway suppression is safe.+ assert sc.delivered_final_matches(final_with_footer) is True++ @pytest.mark.asyncio+ async def test_finish_bare_keeps_legacy_behavior(self):+ adapter = _make_draft_adapter()+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(adapter, "D1", cfg)+ task = asyncio.create_task(sc.run())+ sc.on_delta("plain answer")+ await asyncio.sleep(0.06)+ sc.finish()+ await task+ assert adapter.send_calls[-1]["content"] == "plain answer"+++class TestInterimSendContract:+ @pytest.mark.asyncio+ async def test_commentary_is_marked_interim(self):+ adapter = _make_draft_adapter()+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(adapter, "D1", cfg)+ ok = await sc._send_commentary("Using the browser tool…")+ assert ok is True+ assert adapter.send_calls[-1]["metadata"].get("_interim_send") is True++ @pytest.mark.asyncio+ async def test_relay_adapter_interim_send_does_not_seal(self):+ """An armed open draft must survive an interim send untouched."""+ from tests.gateway.relay.test_relay_live_cards import _connected_adapter++ adapter, _ = _connected_adapter(+ supported_ops=("send", "edit", "typing", "draft"),+ )++ class _T:+ def __init__(self):+ self.ops = []+ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "111.222"}++ t = _T()+ adapter._transport = t+ md = {"thread_ts": "1700.42"}+ await adapter.send_draft("C1", 5, "streaming...", metadata=md)+ key = adapter._draft_key("C1", md)+ assert adapter._open_draft_by_chat.get(key) == 5++ # Interim commentary while the stream is open: must NOT seal.+ res = await adapter.send(+ "C1", "delegation dispatched, continuing…",+ metadata={**md, "_interim_send": True},+ )+ assert res.success+ assert adapter._open_draft_by_chat.get(key) == 5, "interim send sealed the stream"+ sent_ops = [o for o in t.ops if o["op"] == "send"]+ assert len(sent_ops) == 1+ # Marker never leaks to the wire.+ assert "_interim_send" not in (sent_ops[0].get("metadata") or {})++ # The true turn-final still seals.+ final = await adapter.send("C1", "streaming... done.", metadata=md)+ assert final.success+ assert key not in adapter._open_draft_by_chat+ seals = [o for o in t.ops if o["op"] == "draft" and o.get("final")]+ assert len(seals) == 1++ @pytest.mark.asyncio+ async def test_send_for_platform_interim_does_not_seal(self):+ """The delivery-resolver egress door honors the interim contract too.++ send_for_platform is the second seal-interception site (finding #7);+ an interim send routed through it must neither seal the open stream+ nor leak the gateway-internal marker onto the wire.+ """+ from tests.gateway.relay.test_relay_live_cards import _connected_adapter++ adapter, _ = _connected_adapter(+ supported_ops=("send", "edit", "typing", "draft"),+ )++ class _T:+ def __init__(self):+ self.ops = []+ # fronts_platform reads the handshake identity set off the+ # transport; advertise slack so send_for_platform proceeds.+ self._identities = [("slack", "U-bot")]+ async def send_outbound(self, payload, platform=None):+ self.ops.append(dict(payload))+ return {"success": True, "message_id": "111.333"}++ t = _T()+ adapter._transport = t+ md = {"thread_ts": "1700.77"}+ await adapter.send_draft("C2", 9, "streaming...", metadata=md)+ key = adapter._draft_key("C2", md)+ assert adapter._open_draft_by_chat.get(key) == 9++ res = await adapter.send_for_platform(+ "slack", "C2", "interim status", metadata={**md, "_interim_send": True},+ )+ assert res.success+ assert adapter._open_draft_by_chat.get(key) == 9, "interim send_for_platform sealed the stream"+ sent_ops = [o for o in t.ops if o["op"] == "send"]+ assert len(sent_ops) == 1+ assert "_interim_send" not in (sent_ops[0].get("metadata") or {})+++class TestFinalAdoptionGuards:+ @pytest.mark.asyncio+ async def test_no_stream_turn_does_not_adopt_final(self):+ """finish(final_text) on a turn that never streamed must not move+ delivery ownership into the consumer — the gateway's normal final+ send path owns those turns (non-streaming models, tool-only turns)."""+ adapter = _make_draft_adapter()+ cfg = StreamConsumerConfig(+ transport="auto", chat_type="dm",+ edit_interval=0.01, buffer_threshold=1, cursor="",+ )+ sc = GatewayStreamConsumer(adapter, "D1", cfg)+ task = asyncio.create_task(sc.run())+ # No on_delta at all — straight to completion with a payload.+ sc.finish("the final answer from a non-streaming turn")+ await task+ assert adapter.send_calls == [], "no-stream turn must not deliver via the consumer"+ assert adapter.draft_calls == []+++class TestQueuedLaneReconcile:+ @pytest.mark.asyncio+ async def test_queued_first_response_edits_in_place(self):+ from gateway.run import GatewayRunner++ runner = object.__new__(GatewayRunner)+ adapter = _make_draft_adapter()+ sc = SimpleNamespace(message_id="sealed_ts_9", _turn_split_delivery=False)+ source = SimpleNamespace(chat_id="D1")+ await GatewayRunner._deliver_queued_first_response(+ runner,+ "the complete final with footer",+ source=source,+ adapter=adapter,+ metadata=None,+ text_already_delivered=False,+ deliver_media=False,+ stream_consumer=sc,+ )+ # Edited the sealed message; did NOT plain-send a duplicate.+ assert adapter.edit_calls == [+ {"message_id": "sealed_ts_9", "content": "the complete final with footer"}+ ]+ assert adapter.send_calls == []++ @pytest.mark.asyncio+ async def test_queued_first_response_falls_back_without_message(self):+ from gateway.run import GatewayRunner++ runner = object.__new__(GatewayRunner)+ adapter = _make_draft_adapter()+ sc = SimpleNamespace(message_id=None, _turn_split_delivery=False)+ source = SimpleNamespace(chat_id="D1")+ await GatewayRunner._deliver_queued_first_response(+ runner,+ "final text",+ source=source,+ adapter=adapter,+ metadata=None,+ text_already_delivered=False,+ deliver_media=False,+ stream_consumer=sc,+ )+ assert adapter.edit_calls == []+ assert len(adapter.send_calls) == 1