The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway,cli): release the classic CLI's clarify panel when another viewer completes it
Teknium85ad26771b78
diff --git a/gateway/session_sudo_prompt.py b/gateway/session_sudo_prompt.pyindex c927ed062c7..f76a888c382 100644--- a/gateway/session_sudo_prompt.py+++ b/gateway/session_sudo_prompt.py@@ -166,6 +166,13 @@ def _ask(events, session_id, method, params, *, cancelled, timeout, qids=None):events.publish(session_id, {"id": request_id, "method": method, "reason": reason},event_type="request.cancel")return pending if pending.qids is not None else None+ # Settled by a viewer (a response frame or the last ``clarify.lock``): every OTHER viewer still+ # shows the card, and a classic CLI is parked inside its modal callback. Withdraw it everywhere+ # with ``reason: resolved`` (``RequestCancelReason``) so each renderer closes the matching card and+ # the CLI's connection thread releases its modal (``hermes_cli.gateway_agent``). No answer rides it.+ with contextlib.suppress(Exception):+ events.publish(session_id, {"id": request_id, "method": method, "reason": "resolved"},+ event_type="request.cancel")return pendingdiff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex bd645da2850..5426e81443e 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -679,6 +679,8 @@ class CLIAgentSetupMixin:clarify_callback=clarify_callback, connection_callback=connection_callback,# The gateway's model-guard refusal is asked like main's own guard; -q cannot answer it.model_confirm_callback=None if single_query_mode else self._confirm_owner_model_switch,+ # Another viewer answering the gateway's clarify/sudo/secret request closes this modal.+ modal_withdraw_callback=None if single_query_mode else self._withdraw_gateway_modal,reasoning_callback=self._current_reasoning_callback(),fallback_model=self._fallback_model, thinking_callback=self._on_thinking,checkpoints_enabled=self.checkpoints_enabled,diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.pyindex b4917a55467..684d29fc793 100644--- a/hermes_cli/cli_modal_mixin.py+++ b/hermes_cli/cli_modal_mixin.py@@ -1038,6 +1038,20 @@ class CLIModalMixin:_cprint(f"\n{_DIM}{t('cli.clarify.timed_out_locked_answers', timeout=timeout)}{_RST}")return {"answers": partial, "outcome": "timed_out"}+ def _withdraw_gateway_modal(self, method) -> None:+ """The gateway withdrew the server request this CLI's modal is answering (``request.cancel``:+ another viewer completed it, or its wait ended): close that modal as if cancelled locally, so+ the blocked agent thread returns. Called from the gateway connection's thread."""+ # Each modal's response queue is an unbounded queue.Queue: put() never blocks or raises.+ if method == "clarify" and self._clarify_state:+ state = self._clarify_state+ self._clarify_teardown()+ state["response_queue"].put(None)+ elif method == "sudo" and self._sudo_state:+ self._sudo_state["response_queue"].put("")+ elif method == "secret" and getattr(self, "_secret_state", None):+ self._cancel_secret_capture()+def _sudo_password_callback(self) -> str:"""Prompt for a sudo password through the prompt_toolkit UI (agent thread); clarify-stylestate + queue answered by the Enter binding."""diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex ae70d254405..9afebd01044 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -77,7 +77,7 @@ class GatewayAgent:tool_start_callback=None, tool_complete_callback=None, stream_delta_callback=None,tool_gen_callback=None, notice_callback=None, notice_clear_callback=None,reaction_callback=None, interim_assistant_callback=None, connection=None,- push_reasoning=False, model_confirm_callback=None, **_ignored):+ push_reasoning=False, model_confirm_callback=None, modal_withdraw_callback=None, **_ignored):conn = connection or getattr(session_db, "connection", None)if conn is None:raise GatewayClientError("Gateway session unavailable; no local fallback")@@ -108,6 +108,10 @@ class GatewayAgent:self.interim_assistant_callback = interim_assistant_callback# The CLI's confirm prompt for the owner's model-guard refusal; None where nobody can answer (-q).self.model_confirm_callback = model_confirm_callback+ # Closes the CLI's open modal for one server-request method when the gateway withdraws it+ # (``request.cancel``: another viewer answered, the turn ended); called off the agent thread.+ self.modal_withdraw_callback = modal_withdraw_callback+ self._open_request = None # (request id, method) of the server request a modal is answeringself.suppress_status_output = Falseself._print_fn = None# Inert private attributes main's CLI writes (CALLMAP §3.2).@@ -171,6 +175,7 @@ class GatewayAgent:self.service_tier = service_tierstate = self._state()state.usage_listeners.append(self.apply_session_usage)+ state.request_listeners.append(self._on_request_withdrawn)if state.usage:self.apply_session_usage(state.usage)@@ -285,6 +290,8 @@ class GatewayAgent:state = self._state()if self.apply_session_usage not in state.usage_listeners:state.usage_listeners.append(self.apply_session_usage)+ if self._on_request_withdrawn not in state.request_listeners:+ state.request_listeners.append(self._on_request_withdrawn)self._apply_info(state.info)if state.usage:self.apply_session_usage(state.usage)@@ -815,16 +822,32 @@ class GatewayAgent:answers it on this (agent) thread, through the callback HermesCLI registered for the turn; theanswer travels only in the JSON-RPC response frame."""method = frame["method"]+ self._open_request = (frame["id"], method)try:answer = _SERVER_REQUESTS[method](self, frame.get("params") or {})except Exception: # health: allow BLE001 -- a broken modal is a skip, never a hung toollogger.debug("server request %s failed", method, exc_info=True)answer = {"outcome": "cancelled"} if method == "clarify" else ""+ finally:+ self._open_request = Noneif method == "clarify":self.connection.reply(frame["id"], answer)else:self.connection.reply(frame["id"], {"value": answer if isinstance(answer, str) else ""})+ def _on_request_withdrawn(self, payload):+ """``request.cancel`` (connection loop thread): the gateway settled or withdrew a request. When+ this agent thread is parked in the modal answering it (another viewer completed the form, the+ turn timed out or was interrupted), release that modal so the pump reads the turn's remaining+ frames; its late reply to the already-settled request is dropped by the gateway."""+ current = self._open_request+ if current is None or payload.get("id") != current[0] or self.modal_withdraw_callback is None:+ return+ try:+ self.modal_withdraw_callback(current[1])+ except Exception: # health: allow BLE001 -- a broken teardown must not stop the connection pump+ logger.debug("modal withdraw for %s failed", current[1], exc_info=True)+def _ask_clarify(self, params):"""Main's batch clarify panel (``clarify_callback(questions)``) for the whole question set."""questions = [{"qid": q.get("qid"), "question": q.get("question") or "",diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.pyindex 47d6329e470..471fe4c24e0 100644--- a/hermes_cli/gateway_connection.py+++ b/hermes_cli/gateway_connection.py@@ -56,6 +56,9 @@ class SessionState:# Called (loop thread) with each ``session.usage`` payload; GatewayAgent maps it onto main's# agent attributes, so a frame landing between turns is never dropped with the turn queue.self.usage_listeners: list = []+ # Called (loop thread) with each ``request.cancel`` payload: the agent thread may be parked in a+ # modal answering that very request (another viewer settled it), so it cannot read the queue.+ self.request_listeners: list = []# A gateway-admitted notification turn the idle CLI queued a header for (gateway_tools_notify).self.admitted_turn: dict | None = None@@ -77,6 +80,9 @@ class SessionState:self.todos = list(payload.get("todos") or [])elif kind == "session.usage" and isinstance(payload, dict):self.apply_usage(payload.get("usage") if isinstance(payload.get("usage"), dict) else payload)+ elif kind == "request.cancel" and isinstance(payload, dict):+ for listener in list(self.request_listeners):+ listener(payload)def apply_usage(self, usage):"""One session-cumulative usage dict (``session.usage`` payload or ``session.stats`` result)."""diff --git a/tests/gateway/test_clarify_lock_owner.py b/tests/gateway/test_clarify_lock_owner.pyindex 639e2e27702..2335ff82c03 100644--- a/tests/gateway/test_clarify_lock_owner.py+++ b/tests/gateway/test_clarify_lock_owner.py@@ -83,6 +83,11 @@ async def test_clarify_lock_answers_the_owner_batch_request(tmp_path, monkeypatcassert last.get('result') == {'status': 'ok', 'remaining': []}, lastawait asyncio.to_thread(worker.join, 5)assert out == {'answers': {'q0': 'red', 'q1': None}, 'outcome': 'submitted'}+ # Settled: every other viewer's card (and a classic CLI parked in its panel) is withdrawn.+ await _wait_for(lambda: any(f.get('params', {}).get('type') == 'request.cancel' for f in peer.frames))+ cancel = next(f['params'] for f in peer.frames if f.get('params', {}).get('type') == 'request.cancel')+ assert cancel['payload'] == {'id': rid, 'method': 'clarify', 'reason': 'resolved'}+ assert 'red' not in repr(cancel) # no answer rides the withdrawallate = await _lock(connection, rid, 'q1', 'late', 6)assert late.get('result') == {'status': 'expired'}, latefinally:diff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex a102c7d8ec9..fd5c15fde58 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -823,3 +823,45 @@ def test_a_background_review_summary_during_a_turn_is_printed_like_mains(make_agagent._print_fn = printed.appendagent.run_conversation("hi")assert printed == [" 💾 Self-improvement review: Memory updated"]+++def test_another_viewer_completing_the_clarify_batch_releases_mains_panel(make_agent, monkeypatch):+ """Another viewer (Desktop/Ink) locks every answer of the batch the classic CLI is showing: the+ gateway settles it and withdraws the request (``request.cancel`` reason ``resolved``). main's real+ batch panel (``CLIModalMixin._clarify_callback``) blocks the agent thread, so the withdrawal must+ close it from the connection thread; the pump then reads the turn's completion instead of sitting+ in the modal until clarify_timeout."""+ import cli+ from tests.hermes_cli.test_cli_clarify_batch import _make_cli_stub+ monkeypatch.setattr(cli, "CLI_CONFIG", {"agent": {"clarify_timeout": 60}})+ panel = _make_cli_stub()+ panel._ring_bell = lambda **kw: None+ request = {"jsonrpc": "2.0", "id": "srq-clr", "method": "clarify", "params": {"session_id": SID, "questions": [+ {"qid": "q0", "question": "colour?", "choices": ["red", "blue"]},+ {"qid": "q1", "question": "size?", "choices": ["s", "l"]}]}}+ withdrawn = frame("request.cancel", {"id": "srq-clr", "method": "clarify", "reason": "resolved"}, admission=None)+ agent, _client = make_agent(+ [request, "wait", withdrawn, frame("message.complete", {"text": "ok", "outcome": "completed"})],+ clarify_callback=panel._clarify_callback, modal_withdraw_callback=panel._withdraw_gateway_modal)+ replies = []+ agent.connection.reply = lambda rid, result: replies.append((rid, result)) or True+ out = {}+ worker = threading.Thread(target=lambda: out.update(agent.run_conversation("ask")), daemon=True)+ worker.start()+ worker.join(10)+ assert not worker.is_alive(), "the CLI stayed blocked in its clarify panel"+ assert panel._clarify_state is None+ assert out["completed"] is True or out.get("final_response") is not None+ # Its late reply is a cancel the gateway drops (the request is already settled).+ assert replies == [("srq-clr", {"answers": {}, "outcome": "cancelled"})]+++def test_a_withdrawal_for_another_request_leaves_the_panel_open(make_agent):+ agent, _client = make_agent([])+ closed = []+ agent.modal_withdraw_callback = closed.append+ agent._open_request = ("srq-mine", "clarify")+ agent._on_request_withdrawn({"id": "srq-other", "method": "clarify", "reason": "resolved"})+ assert closed == []+ agent._on_request_withdrawn({"id": "srq-mine", "method": "clarify", "reason": "resolved"})+ assert closed == ["clarify"]