Skip to content

The agent that grows with you

Merge branch 'main' into relay-ws-hardening

Ben Barclay141af4febfb4
diff --cc gateway/relay/adapter.py
index 8139882373d,7a3ae50dd36..0707bded6a7
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@@ -95,9 -95,41 +95,44 @@@ 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]] = {}
+ # Bounded FIFO seen-set for inbound replay dedupe (finding #3);
+ # dict preserves insertion order, giving cheap oldest-first eviction.
+ self._seen_inbound: Dict[str, None] = {}
+ # 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.
diff --cc gateway/relay/ws_transport.py
index 10183459003,2cfd1a88651..3f58069f282
--- a/gateway/relay/ws_transport.py
+++ b/gateway/relay/ws_transport.py
@@@ -807,21 -791,22 +807,46 @@@ class WebSocketRelayTransport
bot_id = self._bot_id_for(platform)
if bot_id:
frame["botId"] = bot_id
++ frame_sent = False
try:
await self._send(frame)
++ frame_sent = True
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,
+ }
+ except Exception as exc: # noqa: BLE001 - a dead socket is a failed send, not a raise
+ # No `is None` check can close the window where the socket dies
+ # BETWEEN the liveness guard above and the actual write — the
+ # reader's finally hasn't cleared _ws yet, so _send raises
+ # ConnectionClosed straight into callers whose contract is a
+ # result dict (RelayAdapter.send consumes it with no try).
+ # Report it like every other failed send. CancelledError is a
+ # BaseException, so cancellation still propagates.
++ #
++ # Ambiguity contract (PR 85796): a raise from the WRITE means the
++ # frame never reached the wire — definite non-delivery, no flag.
++ # A failure surfaced by the FUTURE (e.g. disconnect() failing
++ # pending mid-flight) means the frame WAS sent and only the
++ # outcome is unknown — mark it ambiguous like the timeout above.
+ logger.debug("relay %s send failed", frame_type, exc_info=True)
- return {"success": False, "error": f"relay send failed: {exc}"}
++ result: Dict[str, Any] = {
++ "success": False,
++ "error": f"relay send failed: {exc}",
++ }
++ if frame_sent:
++ result["ambiguous"] = True
++ return result
finally:
self._pending.pop(request_id, None)