Skip to content

The agent that grows with you

fix(gateway): cancel native clarify only on free prose

deacon-botdoctor9bff109783aa
diff --git a/gateway/run.py b/gateway/run.py
index ee720f168e5..0d7b368db1c 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -15963,10 +15963,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# so the user can retry; if it times out, the agent unblocks
# with an empty response.
if _raw_clarify_reply and not _raw_clarify_reply.startswith("/"):
- _resolved = _clarify_mod.resolve_text_response_for_session(
+ _text_outcome = _clarify_mod.attempt_text_response_for_session(
_quick_key, _raw_clarify_reply,
)
- if _resolved:
+ if _text_outcome == _clarify_mod.TEXT_RESOLVED:
logger.info(
"Gateway intercepted clarify text response (session=%s, id=%s)",
_quick_key, _pending_clarify.clarify_id,
@@ -15990,15 +15990,27 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# the agent's response don't double-post. The agent
# itself will produce the next user-facing message.
return ""
- # Native-choice prompts deliberately reject unmatched prose
- # so it can continue through normal busy-message routing.
- # Release this clarify first: redirect() degrades to steer()
- # while tools are executing, and that steer cannot drain until
- # the clarify tool returns.
- _clarify_mod.resolve_gateway_clarify(
- _pending_clarify.clarify_id,
- "",
- )
+ if _text_outcome == _clarify_mod.TEXT_REJECTED_SELECTION:
+ # Selection-shaped but invalid (out-of-range number,
+ # unrecognised comma-list). Keep the clarify armed so
+ # the user can retry — do not cancel and do not treat
+ # this as an unrelated follow-up turn.
+ logger.info(
+ "Gateway retained pending clarify after invalid "
+ "selection attempt (session=%s, id=%s)",
+ _quick_key, _pending_clarify.clarify_id,
+ )
+ return ""
+ if _text_outcome == _clarify_mod.TEXT_REJECTED_PROSE:
+ # Native-choice prompts deliberately reject unmatched
+ # prose so it can continue through normal busy-message
+ # routing. Release this clarify first: redirect()
+ # degrades to steer() while tools are executing, and
+ # that steer cannot drain until the clarify tool returns.
+ _clarify_mod.resolve_gateway_clarify(
+ _pending_clarify.clarify_id,
+ "",
+ )
# Intercept messages that are responses to a pending /reload-mcp
# (or future) slash-confirm prompt. Recognized confirm replies are
diff --git a/tests/gateway/test_clarify_thread_followup_not_swallowed.py b/tests/gateway/test_clarify_thread_followup_not_swallowed.py
index 7f476579019..210fd7bba8b 100644
--- a/tests/gateway/test_clarify_thread_followup_not_swallowed.py
+++ b/tests/gateway/test_clarify_thread_followup_not_swallowed.py
@@ -157,6 +157,92 @@ async def test_thread_prose_does_not_overwrite_concurrent_button_choice():
_clear_clarify_state()
+async def test_native_multi_select_out_of_range_keeps_clarify_pending():
+ """Out-of-range multi-select numbers must not cancel the pending prompt."""
+ _clear_clarify_state()
+ from tools import clarify_gateway as cm
+
+ adapter = _StubAdapter()
+ runner = _make_runner(adapter)
+ entry = cm.register(
+ "cl-ms-oor",
+ SESSION_KEY,
+ "Pick some targets",
+ ["staging", "prod", "canary"],
+ multi_select=True,
+ )
+ assert entry.awaiting_text is False
+
+ result = await _dispatch(runner, _event("99"))
+
+ assert result == ""
+ with cm._lock:
+ still = cm._entries.get("cl-ms-oor")
+ assert still is not None
+ assert not still.event.is_set()
+ assert still.response is None
+ _clear_clarify_state()
+
+
+async def test_native_multi_select_bad_comma_list_keeps_clarify_pending():
+ """Unrecognised comma-lists are retryable selection attempts, not prose."""
+ _clear_clarify_state()
+ from tools import clarify_gateway as cm
+
+ adapter = _StubAdapter()
+ runner = _make_runner(adapter)
+ entry = cm.register(
+ "cl-ms-bad",
+ SESSION_KEY,
+ "Pick some targets",
+ ["staging", "prod", "canary"],
+ multi_select=True,
+ )
+ assert entry.awaiting_text is False
+
+ result = await _dispatch(runner, _event("1,99"))
+
+ assert result == ""
+ with cm._lock:
+ still = cm._entries.get("cl-ms-bad")
+ assert still is not None
+ assert not still.event.is_set()
+ assert still.response is None
+ _clear_clarify_state()
+
+
+async def test_native_multi_select_prose_releases_clarify_before_routing():
+ """Free prose on multi-select still breaks the redirect/steer deadlock."""
+ _clear_clarify_state()
+ from tools import clarify_gateway as cm
+
+ adapter = _StubAdapter()
+ runner = _make_runner(adapter)
+ cm.register(
+ "cl-ms-prose",
+ SESSION_KEY,
+ "Pick some targets",
+ ["staging", "prod"],
+ multi_select=True,
+ )
+
+ with pytest.raises(_FellThroughIntercept):
+ await _dispatch(
+ runner,
+ _event("just checking the visual UI, no need to pass any data"),
+ )
+
+ with cm._lock:
+ entry = cm._entries.get("cl-ms-prose")
+ assert entry is not None
+ assert entry.event.is_set()
+ assert entry.response == ""
+ _clear_clarify_state()
+
+
@pytest.mark.asyncio
async def test_prose_still_accepted_after_other_flips_text_capture():
"""After the user taps 'Other', free text IS the answer — must resolve."""
diff --git a/tests/tools/test_clarify_gateway.py b/tests/tools/test_clarify_gateway.py
index 3a164d0c6cc..e06bf9d6085 100644
--- a/tests/tools/test_clarify_gateway.py
+++ b/tests/tools/test_clarify_gateway.py
@@ -379,3 +379,84 @@ class TestMultiSelectTextFallback:
from tools import clarify_gateway as cm
entry = cm.register("s4", "sk", "Q?", ["A", "B"])
assert cm._coerce_text_response(entry, "b") == "B"
+
+
+class TestNativeRejectClassification:
+ """Rejected typed replies must distinguish free prose from bad selections.
+
+ Free prose cancels/falls through (deadlock break). Selection-shaped but
+ invalid replies (out-of-range number, unrecognised comma-list) keep the
+ pending clarify armed so the user can retry.
+ """
+
+ def setup_method(self):
+ _clear_clarify_state()
+
+ def test_multi_select_out_of_range_is_invalid_selection(self):
+ from tools import clarify_gateway as cm
+
+ entry = cm.register(
+ "ms-oor", "sk-ms", "Pick some", ["A", "B", "C"], multi_select=True,
+ )
+ assert entry.awaiting_text is False
+ value, reason = cm._coerce_text_response_detailed(entry, "99")
+ assert value is None
+ assert reason == "invalid_selection"
+ assert cm.attempt_text_response_for_session("sk-ms", "99") == (
+ cm.TEXT_REJECTED_SELECTION
+ )
+ pending = cm.get_pending_for_session("sk-ms", include_choice_prompts=True)
+ assert pending is not None
+ assert not pending.event.is_set()
+
+ def test_multi_select_bad_comma_list_is_invalid_selection(self):
+ from tools import clarify_gateway as cm
+
+ entry = cm.register(
+ "ms-bad", "sk-ms2", "Pick some", ["A", "B", "C"], multi_select=True,
+ )
+ value, reason = cm._coerce_text_response_detailed(entry, "1,99")
+ assert value is None
+ assert reason == "invalid_selection"
+ assert cm.attempt_text_response_for_session("sk-ms2", "nope,nope") == (
+ cm.TEXT_REJECTED_SELECTION
+ )
+ pending = cm.get_pending_for_session("sk-ms2", include_choice_prompts=True)
+ assert pending is not None
+ assert not pending.event.is_set()
+
+ def test_multi_select_free_prose_is_rejected_prose(self):
+ from tools import clarify_gateway as cm
+
+ entry = cm.register(
+ "ms-prose", "sk-ms3", "Pick some", ["A", "B"], multi_select=True,
+ )
+ value, reason = cm._coerce_text_response_detailed(
+ entry, "just checking the visual UI, no need to pass any data",
+ )
+ assert value is None
+ assert reason == "prose"
+ assert cm.attempt_text_response_for_session(
+ "sk-ms3", "just checking the visual UI, no need to pass any data",
+ ) == cm.TEXT_REJECTED_PROSE
+
+ def test_single_select_out_of_range_is_invalid_selection(self):
+ from tools import clarify_gateway as cm
+
+ entry = cm.register("ss-oor", "sk-ss", "Pick one", ["A", "B"])
+ value, reason = cm._coerce_text_response_detailed(entry, "9")
+ assert value is None
+ assert reason == "invalid_selection"
+ assert cm.attempt_text_response_for_session("sk-ss", "9") == (
+ cm.TEXT_REJECTED_SELECTION
+ )
+
+ def test_single_select_prose_is_rejected_prose(self):
+ from tools import clarify_gateway as cm
+
+ entry = cm.register("ss-prose", "sk-ss2", "Pick one", ["A", "B"])
+ value, reason = cm._coerce_text_response_detailed(
+ entry, "one more unrelated thought",
+ )
+ assert value is None
+ assert reason == "prose"
diff --git a/tools/clarify_gateway.py b/tools/clarify_gateway.py
index 212cb0b4446..e9bec3e95ca 100644
--- a/tools/clarify_gateway.py
+++ b/tools/clarify_gateway.py
@@ -214,19 +214,111 @@ def _label_matches(text: str, choice: object) -> bool:
return strip_recommended(text).casefold() == strip_recommended(str(choice)).casefold()
+# Outcomes for typed clarify replies. Gateway uses these to decide whether to
+# cancel a pending prompt (free prose deadlock break) or keep it armed so the
+# user can retry a selection-like invalid reply (out-of-range / bad list).
+TEXT_RESOLVED = "resolved"
+TEXT_REJECTED_PROSE = "rejected_prose"
+TEXT_REJECTED_SELECTION = "rejected_selection"
+TEXT_NO_PENDING = "no_pending"
+
+
+def _selection_attempt_tokens(
+ text: str,
+ choices: Optional[List[str]] = None,
+) -> Optional[List[str]]:
+ """Return tokens when ``text`` looks like a typed selection attempt.
+
+ Selection-shaped input includes:
+ - a bare integer ("2", "99")
+ - comma-separated numbers/labels ("1,3", "staging, prod", "1,99")
+ - space-separated all-numeric lists ("1 3")
+
+ Free prose ("just checking the visual UI, no need to pass any data") returns
+ None even when it contains commas, so the gateway can release the clarify
+ and continue normal routing instead of forcing a retry.
+
+ Multi-word choice labels are allowed in comma-lists up to the longest
+ choice's word count (e.g. "Send to SOL, Keep with Enoch").
+ """
+ stripped = str(text).strip()
+ if not stripped:
+ return None
+
+ max_choice_words = 1
+ if choices:
+ max_choice_words = max(
+ (len(str(choice).split()) for choice in choices),
+ default=1,
+ )
+ max_choice_words = max(1, max_choice_words)
+
+ if "," in stripped:
+ tokens = [t.strip() for t in stripped.split(",") if t.strip()]
+ if not tokens:
+ return None
+ # Natural-language clauses with commas are not selection lists.
+ # Each selection token is either a number or at most as many words
+ # as the longest configured choice label.
+ for token in tokens:
+ if token.isdigit():
+ continue
+ words = token.split()
+ if len(words) == 0 or len(words) > max_choice_words:
+ return None
+ return tokens
+
+ parts = stripped.split()
+ if len(parts) > 1 and all(p.strip().isdigit() for p in parts):
+ return [p.strip() for p in parts]
+
+ # Bare integer (in-range or out-of-range) is always a selection attempt.
+ if stripped.isdigit() or (stripped.startswith("-") and stripped[1:].isdigit()):
+ return [stripped]
+
+ try:
+ int(stripped)
+ return [stripped]
+ except ValueError:
+ return None
+
+
def _coerce_text_response(entry: _ClarifyEntry, response: str) -> Optional[str]:
"""Map typed choice replies to canonical choice text, otherwise keep or reject custom text.
+ Thin wrapper over :func:`_coerce_text_response_detailed` for callers that
+ only need the accepted value (or ``None`` on any rejection).
+ """
+ coerced, _reason = _coerce_text_response_detailed(entry, response)
+ return coerced
+
+
+def _coerce_text_response_detailed(
+ entry: _ClarifyEntry,
+ response: str,
+) -> tuple[Optional[str], Optional[str]]:
+ """Map typed replies and classify rejections.
+
+ Returns ``(value, None)`` when the reply is accepted.
+
+ Returns ``(None, reason)`` when rejected:
+ - ``"invalid_selection"`` — selection-shaped but unusable (out-of-range
+ number, unrecognised comma-list). Keep the pending clarify so the
+ user can retry.
+ - ``"prose"`` — free text that is not a selection attempt. Gateway may
+ cancel the clarify and continue normal busy-message routing so a
+ redirect-to-steer path cannot deadlock behind the waiting tool.
+
For native interactive multi-choice clarifies (button UI, awaiting_text=False):
- Accept numeric selections ("2" → choice[1])
- Accept exact choice label matches (case-insensitive)
- - Reject arbitrary prose (return None) so the message continues as a normal turn
+ - Reject arbitrary prose so the message can continue as a normal turn
For multi-select clarifies (entry.multi_select=True):
- Accept several numbers separated by commas and/or spaces ("1,3" / "1 3")
- Accept exact choice label matches (single or comma-separated)
- - Out-of-range numbers reject the whole reply (return None) so the user
- can retry instead of silently getting a partial selection
+ - Out-of-range numbers / unrecognised lists reject the whole reply so the
+ user can retry instead of silently getting a partial selection
- Selections are returned as a JSON array string, which the clarify
tool's ``_parse_multi_select_response`` decodes back into a list
@@ -235,43 +327,50 @@ def _coerce_text_response(entry: _ClarifyEntry, response: str) -> Optional[str]:
For open-ended clarifies (no choices):
- Accept any text
-
- Returns None when the response should be rejected (arbitrary prose for native multi-choice).
"""
text = str(response).strip()
if not entry.choices:
# Open-ended: accept any text
- return text
+ return text, None
if entry.multi_select:
coerced = _coerce_multi_select_text(entry, text)
if coerced is not None:
- return coerced
+ return coerced, None
# Not a parseable selection — accept as custom text only in
- # awaiting_text mode (the "Other" path); otherwise reject.
- return text if entry.awaiting_text else None
+ # awaiting_text mode (the "Other" path); otherwise classify reject.
+ if entry.awaiting_text:
+ return text, None
+ if _selection_attempt_tokens(text, entry.choices) is not None:
+ return None, "invalid_selection"
+ return None, "prose"
# Try numeric selection first (always valid for multi-choice)
try:
idx = int(text) - 1
+ is_int = True
except ValueError:
idx = -1
+ is_int = False
- if 0 <= idx < len(entry.choices):
- return entry.choices[idx]
+ if is_int and 0 <= idx < len(entry.choices):
+ return entry.choices[idx], None
# Try exact choice label match (always valid for multi-choice)
for choice in entry.choices:
if _label_matches(text, choice):
- return str(choice).strip()
+ return str(choice).strip(), None
# For text fallback or awaiting_text mode, accept custom text
- # For native interactive multi-choice mode, reject arbitrary prose
+ # For native interactive multi-choice mode, reject with a reason
if entry.awaiting_text:
- return text
+ return text, None
- return None
+ # Out-of-range / non-canonical integer is a failed selection, not prose.
+ if is_int:
+ return None, "invalid_selection"
+ return None, "prose"
def _coerce_multi_select_text(entry: _ClarifyEntry, text: str) -> Optional[str]:
@@ -326,25 +425,42 @@ def _coerce_multi_select_text(entry: _ClarifyEntry, text: str) -> Optional[str]:
return _json.dumps(selected, ensure_ascii=False)
-def resolve_text_response_for_session(session_key: str, response: str) -> bool:
- """Resolve the oldest pending clarify in ``session_key`` from typed text.
+def attempt_text_response_for_session(session_key: str, response: str) -> str:
+ """Try to resolve the oldest pending clarify in ``session_key`` from typed text.
- Returns False if no pending clarify exists or if the response was rejected
- (arbitrary prose for native interactive multi-choice clarifies).
+ Returns one of:
+ - ``TEXT_RESOLVED`` — accepted; waiter unblocked
+ - ``TEXT_REJECTED_PROSE`` — free prose on a native choice prompt; caller
+ may cancel the clarify and continue ordinary message routing
+ - ``TEXT_REJECTED_SELECTION`` — selection-shaped but invalid; leave the
+ pending clarify armed so the user can retry
+ - ``TEXT_NO_PENDING`` — no interceptable clarify for this session
"""
entry = get_pending_for_session(session_key, include_choice_prompts=True)
if entry is None:
- return False
+ return TEXT_NO_PENDING
- coerced = _coerce_text_response(entry, response)
+ coerced, reason = _coerce_text_response_detailed(entry, response)
if coerced is None:
- # Response rejected: message should continue as a normal turn
- return False
+ if reason == "invalid_selection":
+ return TEXT_REJECTED_SELECTION
+ return TEXT_REJECTED_PROSE
- return resolve_gateway_clarify(
- entry.clarify_id,
- coerced,
- )
+ if resolve_gateway_clarify(entry.clarify_id, coerced):
+ return TEXT_RESOLVED
+ # Lost a race with a button/callback resolution — treat as no work left.
+ return TEXT_NO_PENDING
+
+
+def resolve_text_response_for_session(session_key: str, response: str) -> bool:
+ """Resolve the oldest pending clarify in ``session_key`` from typed text.
+
+ Returns True only when the reply was accepted and the waiter unblocked.
+ Rejected prose, rejected selections, and missing prompts all return False;
+ use :func:`attempt_text_response_for_session` when the caller must
+ distinguish those cases (gateway deadlock vs multi-select retry).
+ """
+ return attempt_text_response_for_session(session_key, response) == TEXT_RESOLVED
def mark_awaiting_text(clarify_id: str) -> bool: