Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions forks/hermes-agent/gateway/run_turn_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,8 +585,14 @@ def _close_native_stream_boundary(self, reason: str, placeholder: str | None = N
logger.warning("%s boundary timed out or failed: %s", reason, err)
return False

async def _send_shared_clarify(self, entry, **kwargs):
result = await self._ctx._status_adapter.send_clarify(**kwargs)
def _live_delivery_adapter(self):
ctx = self._ctx
return (self._runner._delivery_adapter_for(ctx.source)
if getattr(ctx, "source", None) is not None else ctx._status_adapter)


async def _send_shared_clarify(self, entry, adapter, **kwargs):
result = await adapter.send_clarify(**kwargs)
if self._approval_owner is not None and result.success:
authority, session_id, generation = self._approval_owner
from gateway import local_viewer_events
Expand Down Expand Up @@ -642,7 +648,8 @@ def _ask_clarify_question(self, question, choices, multi_select, rearm: bool = T
from tools import clarify_gateway as clarify_mod
import uuid
ctx = self._ctx
if not ctx._status_adapter:
adapter = self._live_delivery_adapter()
if not adapter:
# Nothing can render the question: say so, or the batch's blank answers read as
# user inactivity (#112684).
return UNDELIVERED_NO_SURFACE, False
Expand All @@ -656,7 +663,7 @@ def _ask_clarify_question(self, question, choices, multi_select, rearm: bool = T

def _text_fallback():
"""Schedule the plain-text prompt when the native card cannot render; None = no such path."""
coro = text_fallback_coro(ctx._status_adapter, **send_kwargs)
coro = text_fallback_coro(self._live_delivery_adapter(), **send_kwargs)
return None if coro is None else self._schedule(coro, "Clarify text fallback failed to schedule")
entry = clarify_mod.register(
clarify_id=clarify_id, session_key=session_key, question=question, choices=choices,
Expand All @@ -668,7 +675,7 @@ def _text_fallback():
# Pause typing: a "thinking..." status must not obscure the prompt or block an "Other" reply
# on platforms that disable input while typing (Slack Assistant).
with suppress(Exception):
ctx._status_adapter.pause_typing_for_chat(ctx._status_chat_id)
adapter.pause_typing_for_chat(ctx._status_chat_id)
# Ordering barrier: flush buffered assistant prose BEFORE the poll, which goes out on a
# separate agent-thread-blocking path and would otherwise render ABOVE its own explanation.
# Best-effort + short timeout so the agent thread never hangs if the consumer isn't running.
Expand All @@ -679,7 +686,7 @@ def _text_fallback():
except Exception:
logger.debug("Stream-consumer flush before clarify prompt failed", exc_info=True)
fut = self._schedule(
self._send_shared_clarify(entry, **send_kwargs),
self._send_shared_clarify(entry, adapter, **send_kwargs),
"Clarify send failed to schedule",
)
# Boundary rule (see _approval_send_outcome): a send timeout is AMBIGUOUS — the card may
Expand All @@ -697,10 +704,11 @@ def _text_fallback():
if not answered:
# No answer arrived (timeout, /new, run end): retire the native card so it stops
# looking answerable. Adapters without a persistent card have no such method.
retire = getattr(type(ctx._status_adapter), "retire_clarify_card", None)
live = self._live_delivery_adapter()
retire = getattr(type(live), "retire_clarify_card", None)
if callable(retire):
self._schedule(
retire(ctx._status_adapter, clarify_id, _clarify_expired_notice()),
retire(live, clarify_id, _clarify_expired_notice()),
"Clarify card retire failed to schedule")
elif rearm:
# Reopen typing IMMEDIATELY, not on the LLM's first post-answer token (native streaming
Expand All @@ -713,8 +721,7 @@ def _text_fallback():
except Exception:
logger.debug("request_reopen_seed after clarify answer failed", exc_info=True)
try:
(self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None
else ctx._status_adapter).resume_typing_for_chat(ctx._status_chat_id)
self._live_delivery_adapter().resume_typing_for_chat(ctx._status_chat_id)
except Exception:
logger.debug("resume_typing_for_chat after clarify answer failed", exc_info=True)
return response, answered
Expand All @@ -737,7 +744,7 @@ def _render_approval_sync(self, approval_data: dict) -> None:
from gateway.run_turn_runner_approval_settle import register_timeout_notice
from gateway.run_turn_runner_approval_text import approval_text_prompt
ctx = self._ctx
adapter = self._runner._delivery_adapter_for(ctx.source) if getattr(ctx, "source", None) is not None else ctx._status_adapter
adapter = self._live_delivery_adapter()
if adapter is None:
raise RuntimeError("exec approval undeliverable: no live delivery adapter")
# Slack's assistant_threads_setStatus disables the compose box, so the user can't type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ class _CardAdapter:
def __init__(self):
self.retired: list[tuple[str, str]] = []
self.asked: list[str] = []
self.paused: int = 0
self.resumed: int = 0

def pause_typing_for_chat(self, chat_id):
return None
self.paused += 1

def resume_typing_for_chat(self, chat_id):
self.resumed += 1
Expand All @@ -46,7 +47,7 @@ def _asked(adapter):
return [text.split("\n")[0] for text in adapter.asked]


def _run_clarify(adapter, questions=_ONE_QUESTION, answers=(), via_tool=False):
def _run_clarify(adapter, questions=_ONE_QUESTION, answers=(), via_tool=False, live_adapter=None):
"""Returns (clarify result, labels of every coroutine the runner scheduled).

Question i resolves from ``answers[i]``, and ``None`` leaves it unanswered so it expires.
Expand All @@ -57,9 +58,14 @@ def _run_clarify(adapter, questions=_ONE_QUESTION, answers=(), via_tool=False):

runner = object.__new__(TurnRunner)
runner._approval_owner = None # no owning authority: the controls snapshot is skipped
runner._ctx = SimpleNamespace(
ctx = SimpleNamespace(
_status_adapter=adapter, _status_chat_id="C1", _status_thread_metadata={},
session_key="sk1", stream_consumer_holder=[None])
if live_adapter is not None:
ctx.source = object()
runner._ctx = ctx
if live_adapter is not None:
runner._runner = SimpleNamespace(_delivery_adapter_for=lambda _source: live_adapter)
labels: list[str] = []

class _Fut:
Expand Down Expand Up @@ -92,6 +98,89 @@ def _register(**kwargs):
return runner._clarify_callback_sync(questions), labels


def test_clarify_sends_and_rearms_typing_on_live_adapter_when_status_adapter_is_stale():
stale, live = _CardAdapter(), _CardAdapter()

reply, _labels = _run_clarify(stale, answers=("green",), live_adapter=live)

assert reply["answers"] == {"q0": "green"}
assert _asked(live) == ["Pick one"]
assert live.paused == 1
assert live.resumed == 1
assert stale.asked == []
assert stale.paused == 0
assert stale.resumed == 0


def test_clarify_retires_live_adapter_card_when_status_adapter_is_stale():
stale, live = _CardAdapter(), _CardAdapter()

reply, _labels = _run_clarify(stale, live_adapter=live)

assert reply["outcome"] == "timed_out"
assert _asked(live) == ["Pick one"]
assert live.paused == 1
assert len(live.retired) == 1
assert stale.asked == []
assert stale.paused == 0
assert stale.retired == []


def test_late_text_fallback_uses_adapter_live_when_fallback_starts():
from concurrent.futures import Future

from gateway.run_turn_runner import TurnRunner
from tools import clarify_gateway as clarify_mod

stale, live = _CardAdapter(), _CardAdapter()
current_adapter = [stale]
runner = object.__new__(TurnRunner)
runner._approval_owner = None
runner._ctx = SimpleNamespace(
_status_adapter=stale, _status_chat_id="C1", _status_thread_metadata={},
session_key="sk1", stream_consumer_holder=[None], source=object())
runner._runner = SimpleNamespace(_delivery_adapter_for=lambda _source: current_adapter[0])
runner._close_native_stream_boundary = lambda *args, **kwargs: None
card_send = Future()
fallback_adapters = []

labels = []

def _schedule(coro, label):
labels.append(label)
if label == "Clarify send failed to schedule":
asyncio.run(coro)
return card_send
future = Future()
future.set_result(asyncio.run(coro))
return future

async def _send_text_fallback(adapter, **kwargs):
fallback_adapters.append(adapter)
return await adapter.send_clarify(**kwargs)


def _wait_for_response(*args, **kwargs):
current_adapter[0] = live
card_send.set_result(SendResult(success=False, error="late send failure"))
return None

runner._schedule = _schedule
with patch("gateway.run_turn_runner_clarify_delivery.text_fallback_coro",
lambda adapter, **kwargs: _send_text_fallback(adapter, **kwargs)), \
patch("gateway.run_turn_runner_clarify_delivery.SEND_ACK_WINDOW", 0), \
patch.object(clarify_mod, "wait_for_response", _wait_for_response), \
patch.object(clarify_mod, "get_clarify_timeout", return_value=0.05):
response, answered = runner._ask_clarify_question("Pick one", ["a", "b"], False)

assert response.startswith("[user did not respond")
assert not answered
assert stale.asked == ["Pick one"]
assert live.asked == ["Pick one"]
assert fallback_adapters == [live]
assert labels[:2] == ["Clarify send failed to schedule", "Clarify text fallback failed to schedule"]


def test_timeout_retires_the_native_card_with_the_expired_notice():
adapter = _CardAdapter()
reply, _labels = _run_clarify(adapter)
Expand Down Expand Up @@ -186,6 +275,7 @@ def test_skip_hint_only_on_messaging_platforms(platform, hinted):
_status_adapter=adapter, _status_chat_id="C1", _status_thread_metadata={},
session_key="sk1", stream_consumer_holder=[None],
source=SimpleNamespace(platform=Platform(platform)))
runner._runner = SimpleNamespace(_delivery_adapter_for=lambda _source: adapter)

class _Fut:
def __init__(self, r): self._r = r
Expand Down
Loading