The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway+relay): approval prompts survive ambiguity without duplicates; streamed finals keep block formatting
Victor Kyriazakos5210dd48b83e
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex af029700877..7536062ae42 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -513,7 +513,15 @@ class RelayAdapter(BasePlatformAdapter):"draft_id": draft_id,"content": content,"final": False,- "metadata": self._with_scope(chat_id, dict(metadata or {})),+ # Boundary rule (observed in live relay testing): the draft lane+ # is a text egress lane like send/edit — a streamed final+ # can only render blocks if its frames carry the hint.+ "metadata": self._with_scope(+ chat_id,+ self._with_format_hints_for_chat(+ chat_id, dict(metadata or {})+ ),+ ),},platform=self._platform_by_chat.get(str(chat_id)),)@@ -576,7 +584,13 @@ class RelayAdapter(BasePlatformAdapter):"draft_id": draft_id,"content": content,"final": True,- "metadata": self._with_scope(chat_id, dict(metadata or {})),+ # Same boundary rule as the interim frame: the SEAL frame is the+ # one the connector's block reconcile reads — a hintless seal is+ # exactly the plain-code-block downgrade seen in live relay testing.+ "metadata": self._with_scope(+ chat_id,+ self._with_format_hints_for_chat(chat_id, dict(metadata or {})),+ ),}_seal_platform = self._platform_by_chat.get(str(chat_id))_transport = self._transport # narrowed by the None-guard abovediff --git a/gateway/run.py b/gateway/run.pyindex 29d6c9dd410..bcf991a9f4d 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -895,6 +895,31 @@ async def _send_or_update_status_coro(adapter, chat_id, status_key, content, metreturn await adapter.send(chat_id, content, metadata=metadata)+def _approval_send_outcome(future, timeout: float) -> str:+ """Classify an approval prompt send as ``sent`` / ``failed`` / ``ambiguous``.++ ``ambiguous`` == the scheduling future timed out. The card may well have+ posted: the connector may only ack after the deadline (slow platform API+ call, transient backpressure, event-loop stall), and treating that timeout+ as a failure has been observed in live relay testing to re-send the card+ repeatedly, leaving the user's tap resolving a prompt whose turn had moved+ on. Callers must treat+ ``ambiguous`` as possibly-delivered: keep the prompt registration alive+ and do NOT re-send or fall back — the boundary rule is that only a+ DEFINITIVE failure (error result / non-timeout exception / no future)+ re-asks.+ """+ if future is None:+ return "failed"+ try:+ result = future.result(timeout=timeout)+ except concurrent.futures.TimeoutError:+ return "ambiguous"+ except Exception:+ return "failed"+ return "sent" if getattr(result, "success", False) else "failed"++def _resolve_progress_thread_id(platform: Any,source_thread_id: Any,@@ -6083,12 +6108,26 @@ class TurnRunner:)if _approval_fut is None:raise RuntimeError("send_exec_approval: loop unavailable")- _approval_result = _approval_fut.result(timeout=15)- if _approval_result.success:+ _outcome = _approval_send_outcome(_approval_fut, timeout=15)+ if _outcome == "sent":+ return+ if _outcome == "ambiguous":+ # Timeout ≠ failure: the card may have posted with a+ # late ack (slow platform API call or transient+ # connector backpressure). The prompt+ # registration stays alive, so a tap on the rendered+ # card still resolves; re-sending here is what+ # produced duplicate cards and an orphaned+ # "/approve: nothing pending" in live relay testing.+ # Skip the text fallback.+ logger.warning(+ "Button-based approval send timed out — treating "+ "as possibly-delivered (no re-send; the prompt "+ "stays armed for a late tap)"+ )returnlogger.warning(- "Button-based approval failed (send returned error), falling back to text: %s",- _approval_result.error,+ "Button-based approval failed (send returned error), falling back to text")except Exception as _e:logger.warning(diff --git a/tests/gateway/test_approval_send_timeout_ambiguity.py b/tests/gateway/test_approval_send_timeout_ambiguity.pynew file mode 100644index 00000000000..de7a128493b--- /dev/null+++ b/tests/gateway/test_approval_send_timeout_ambiguity.py@@ -0,0 +1,62 @@+"""Approval prompt-send TIMEOUT must not trigger the re-ask/fallback lane.++Observed in live relay testing: `send_exec_approval`'s scheduling future can+hit its 15s `.result(timeout=...)` while the card HAS already posted to the+platform — the connector's ack simply arrives after the deadline (slow+platform API call, transient backpressure, event-loop stall). run.py treated+the timeout like a definitive send failure and ran the text fallback, so the+user saw the same approval multiple times; tapping an older card resolved a+prompt whose turn had already moved on ("/approve: nothing pending").++Contract under test (boundary rule — every prompt caller crossing the+send-timeout boundary): concurrent.futures.TimeoutError from the approval+send is AMBIGUOUS (possibly delivered). The gateway must NOT fall back /+re-send; the prompt registration stays live so the user's tap on the+(probably rendered) card still resolves. A definitive error (SendResult+success=False, or a non-timeout exception) keeps today's fallback.+"""++import concurrent.futures+from unittest.mock import MagicMock++import pytest++from gateway.run import _approval_send_outcome+++class _Result:+ def __init__(self, success, error=None):+ self.success = success+ self.error = error+++def test_timeout_is_ambiguous_not_failure():+ fut = MagicMock()+ fut.result.side_effect = concurrent.futures.TimeoutError()+ outcome = _approval_send_outcome(fut, timeout=0.01)+ assert outcome == "ambiguous", (+ "a send timeout re-ran the fallback — this is the duplicate-approval "+ "re-pop (card posted, ack late); ambiguous must suppress the re-ask"+ )+++def test_success_is_sent():+ fut = MagicMock()+ fut.result.return_value = _Result(True)+ assert _approval_send_outcome(fut, timeout=1) == "sent"+++def test_definitive_error_result_is_failed():+ fut = MagicMock()+ fut.result.return_value = _Result(False, "relay prompt op unavailable")+ assert _approval_send_outcome(fut, timeout=1) == "failed"+++def test_non_timeout_exception_is_failed():+ fut = MagicMock()+ fut.result.side_effect = RuntimeError("loop unavailable")+ assert _approval_send_outcome(fut, timeout=1) == "failed"+++def test_missing_future_is_failed():+ assert _approval_send_outcome(None, timeout=1) == "failed"diff --git a/tests/relay/test_relay_format_hints.py b/tests/relay/test_relay_format_hints.pyindex aa18b8590c1..0c756809277 100644--- a/tests/relay/test_relay_format_hints.py+++ b/tests/relay/test_relay_format_hints.py@@ -158,6 +158,61 @@ class TestFormatHintsStamping:hints = (frame.get("metadata") or {}).get("format_hints")assert hints == {"rich_blocks": True}+ @pytest.mark.asyncio+ async def test_draft_interim_and_seal_frames_carry_hints(self):+ """Observed in live relay testing: a STREAMED bash+ snippet sealed as a plain code block while send/edit rendered+ blocks. The draft lane (interim frame AND the final=true seal+ frame) is a text egress lane crossing the same frame contract —+ the connector's seal reconcile can only attach the markdown block+ if the seal frame carries the hint. Boundary rule: send, edit,+ send_for_platform, AND draft/seal all stamp format_hints."""+ a = _adapter(+ extra={"slack": {"markdown_blocks": True}},+ descriptor=_descriptor(+ supports_block_formatting=True,+ supports_draft_streaming=True,+ supported_ops=("send", "edit", "draft"),+ ),+ )+ code = "```bash\necho hi\n```"+ await a.send_draft("D01", 7, "```bash\necho")+ interim, _ = a._transport.frames[-1]+ assert interim["op"] == "draft" and interim["final"] is False+ assert (interim.get("metadata") or {}).get("format_hints") == {+ "markdown_blocks": True+ }+ seal = getattr(a, "seal_draft", None) or getattr(+ a, "send_draft_final", None+ )+ if seal is not None:+ await seal("D01", 7, code)+ else:+ # The seal frame is built by _seal_open_draft (send()+ # interception converts an armed final into draft final=true).+ await a._seal_open_draft("D01", code, None)+ final_frame, _ = a._transport.frames[-1]+ assert final_frame["op"] == "draft" and final_frame["final"] is True+ assert (final_frame.get("metadata") or {}).get("format_hints") == {+ "markdown_blocks": True+ }++ @pytest.mark.asyncio+ async def test_draft_frames_no_hints_when_knobs_off(self):+ """Regression control: knob off -> draft frames byte-identical to+ today (no format_hints key)."""+ a = _adapter(+ extra={},+ descriptor=_descriptor(+ supports_block_formatting=True,+ supports_draft_streaming=True,+ supported_ops=("send", "edit", "draft"),+ ),+ )+ await a.send_draft("D01", 8, "plain text")+ interim, _ = a._transport.frames[-1]+ assert "format_hints" not in (interim.get("metadata") or {})+class TestMultiPlatformResolution:"""One RelayAdapter fronts N platforms: capability must resolve from thediff --git a/tools/approval.py b/tools/approval.pyindex f3f78f38b85..1ecda55ec45 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -4891,7 +4891,11 @@ def check_all_command_guards(command: str, env_type: str,"command": _disp_command,"description": _disp_combined_desc,"message": (- f"⚠️ {_disp_combined_desc}. Asking the user for approval.\n\n**Command:**\n```\n{_disp_command}\n```"+ f"⚠️ {_disp_combined_desc}. Asking the user for approval.\n\n**Command:**\n```\n{_disp_command}\n```\n\n"+ "STOP: do NOT re-run, rephrase, or re-issue this command — each "+ "variant sends the user ANOTHER approval card. Wait for the "+ "user's decision; if this turn must end, report that approval "+ "is pending."),}if smart_denied_for_owner:@@ -5320,7 +5324,11 @@ def check_execute_code_guard(code: str, env_type: str,"description": display_description,"message": (f"⚠️ {display_description}. Asking the user for approval.\n\n"- f"**Code:**\n```python\n{display_code}\n```"+ f"**Code:**\n```python\n{display_code}\n```\n\n"+ "STOP: do NOT re-run, rephrase, or re-issue this code — each "+ "variant sends the user ANOTHER approval card. Wait for the "+ "user's decision; if this turn must end, report that approval "+ "is pending."),}if smart_denied_for_owner: