The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: ACP, classic CLI and attach clients settle a voice_stopped prompt.submit reply
Tekniumc9c79487049d
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex 5e806d1643a..d539cfead80 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -662,15 +662,9 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):raisefinally:self._submitting.discard(session_id)- admission_id = receipt["admission_id"]- self._admissions[session_id] = admission_id- if receipt.get("status") == "terminal":- # A retry of an un-acked submit whose turn already settled: report that turn once.- await self._settled_receipt(client, held_id, session_id, receipt)- elif receipt.get("status") == "unknown":- # A retry of an un-acked submit the owner lost in a restart: never a second turn.- self._admissions.pop(session_id, None)- raise GatewayClientError(self._unknown_recovery(session_id, admission_id))+ admission_id = await self._admission_from_receipt(client, held_id, session_id, receipt)+ if admission_id is None:+ return PromptResponse(stop_reason='end_turn')self._inflight[(session_id, admission_id)] = Nonetry:await self._after_ack(session_id, admission_id, link, resumes)@@ -709,6 +703,28 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn",usage=turn_usage(self._usage.get(session_id)))+ async def _admission_from_receipt(self, client, held_id, session_id, receipt):+ """The admission a ``prompt.submit`` receipt names, or None when the owner admitted nothing."""+ if receipt.get("voice_stopped") is True:+ # TUI-26: a bare stop phrase typed into this LOCAL session's voice chat ended the chat on+ # the owner and admitted nothing, so no turn will settle: the prompt ends here.+ self._pending_cancels.discard(session_id)+ if self._conn:+ from agent.i18n import t+ await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text(+ t('cli.voice.stop_phrase_typed') + '\n'))+ return None+ admission_id = receipt["admission_id"]+ self._admissions[session_id] = admission_id+ if receipt.get("status") == "terminal":+ # A retry of an un-acked submit whose turn already settled: report that turn once.+ await self._settled_receipt(client, held_id, session_id, receipt)+ elif receipt.get("status") == "unknown":+ # A retry of an un-acked submit the owner lost in a restart: never a second turn.+ self._admissions.pop(session_id, None)+ raise GatewayClientError(self._unknown_recovery(session_id, admission_id))+ return admission_id+async def _run_slash(self, held_id, session_id, text):"""Run a slash command's local half: ``(answered, text to submit)``; answered ends the prompt."""command = _slash_command(text)diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex e1b89b88067..fd1e535917f 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -727,6 +727,8 @@ class GatewayAgent:failure_reason="session_busy" if busy else None, retryable=busy)except GatewayClientError as exc:return self._failed(history, user_message, str(exc), failure_reason="gateway_connection")+ if (receipt or {}).get("voice_stopped") is True:+ return self._voice_stopped(history)self._epoch = getattr(self.connection, "epoch", None)turn.admission = self._admission = (receipt or {}).get("admission_id")if receipt and receipt.get("execution_generation") is not None:@@ -1110,6 +1112,15 @@ class GatewayAgent:return stagedreturn {"role": "user", "content": user_message}+ def _voice_stopped(self, history):+ """TUI-26: the owner took a bare stop phrase typed into this LOCAL session's voice chat (turned+ on by another viewer) as the end of that chat and admitted nothing, so no ``message.complete``+ will come. The turn ends at once with main's typed-stop notice; the history is unchanged."""+ from agent.i18n import t+ self._give_back_turn_route() # nothing was admitted: a ``/model --once`` pick is still owed+ self._emit_print(t("cli.voice.stop_phrase_typed"))+ return {**_RESULT_DEFAULTS, "messages": list(history), "voice_stopped": True, "session_id": self.session_id}+def _failed(self, history, user_message, error, *, failure_reason=None, retryable=False):"""``failure_reason="gateway_connection"``: the CLI shows ``error`` as written instead ofclassifying a lost gateway as a model failure ("Run /model to switch...")."""diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex f3e8e426e86..2782e6d77bf 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -305,6 +305,13 @@ class GatewayChatView:input_id=uuid.uuid4().hex, text=text,**({"finite": True} if self.finite else {}),**({"unattended": True} if self.finite and self.unattended else {}))+ if (receipt or {}).get("voice_stopped") is True:+ # TUI-26: a bare stop phrase typed into this LOCAL session's voice chat (another viewer+ # turned it on) ended the chat on the owner; nothing was admitted and no turn follows.+ if not self.quiet:+ from agent.i18n import t+ print(t("cli.voice.stop_phrase_typed"), flush=True)+ return receiptadmission = (receipt or {}).get("admission_id")if admission and admission not in self.completions and self.session_id == sid:self.mine[admission] = None@@ -503,9 +510,9 @@ class GatewayChatView:try:receipt = await self.submit(query) if query else Noneif oneshot:- if receipt is None:- raise GatewayClientError("One-shot requires a query")- admission = receipt["admission_id"]+ admission = _oneshot_admission(receipt)+ if admission is None:+ return 0 # the voice chat ended; no turn was admitted, so none is awaitedself.finite_admission = admissionfor kind, event_admission, payload in self._finite_events:if event_admission == admission and admission not in self.completions:@@ -587,6 +594,14 @@ class GatewayChatView:await renderer+def _oneshot_admission(receipt):+ """The one-shot query's admission id; None when the owner admitted nothing because the query was a+ bare stop phrase that ended the session's LOCAL voice chat (TUI-26 ``{voice_stopped: true}``)."""+ if receipt is None:+ raise GatewayClientError("One-shot requires a query")+ return None if receipt.get("voice_stopped") is True else receipt["admission_id"]++def resume_footer(session_id):"""The classic single-query exit block (``_print_exit_summary``): how to continue this session.A non-default profile needs ``-p`` because session ids are profile-scoped."""diff --git a/tests/acp_adapter/test_gateway_voice_stopped.py b/tests/acp_adapter/test_gateway_voice_stopped.pynew file mode 100644index 00000000000..14999ab9822--- /dev/null+++ b/tests/acp_adapter/test_gateway_voice_stopped.py@@ -0,0 +1,43 @@+"""TUI-26: the owner's canonical prompt.submit may answer ``{voice_stopped: true}`` (a bare stop+phrase typed into a LOCAL session whose owner /voice mode is on: the voice chat ends and nothing is+admitted). The ACP adapter settles that prompt as an ended turn with the stop notice instead of+reading a missing ``admission_id``."""+import pytest+from acp.schema import TextContentBlock++from acp_adapter.gateway_server import GatewayACPAgent+++class _VoiceStoppedClient:+ def __init__(self):+ self.calls = []++ async def rpc(self, method, **params):+ self.calls.append((method, params))+ if method == 'prompt.submit':+ return {'voice_stopped': True}+ return {}+++class _Conn:+ def __init__(self):+ self.updates = []++ async def session_update(self, session_id, update):+ self.updates.append((session_id, update))+++async def test_acp_prompt_settles_a_voice_stopped_reply_as_an_ended_turn(tmp_path, monkeypatch):+ from agent.i18n import t+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ agent = GatewayACPAgent()+ agent._gateway = _VoiceStoppedClient()+ agent._conn = _Conn()+ agent._snapshots['s'] = {}+ response = await agent.prompt([TextContentBlock(type='text', text='stop')], 's')+ assert response.stop_reason == 'end_turn'+ assert [m for m, _ in agent._gateway.calls] == ['prompt.submit']+ assert 's' not in agent._admissions and not agent._inflight+ texts = [getattr(getattr(u, 'content', None), 'text', '') for _, u in agent._conn.updates]+ assert any(t('cli.voice.stop_phrase_typed') in text for text in texts), textsdiff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex fff0878e521..d033331a7c8 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -922,3 +922,39 @@ def test_ctrl_c_during_the_first_api_call_keeps_mains_estimate_marker(make_agentanchor = agent._turn_base_usage_anchorassert anchor["base_count"] == 2 # the unanswered ask is the estimated delta: main's `~`assert anchored_context_tokens(agent._session_messages, anchor, charge_stale_thinking=False) == 700+++def test_a_voice_stopped_reply_returns_without_waiting_for_a_turn():+ """TUI-26: the owner answers a typed stop phrase in a LOCAL voice chat (turned on by another+ viewer) with ``{voice_stopped: true}`` and admits nothing, so no ``message.complete`` will ever+ come: the classic CLI returns at once with the stop notice instead of pumping forever."""+ from agent.i18n import t++ class Client(FakeClient):+ async def rpc(self, method, *, _timeout=None, **params):+ if method == "prompt.submit":+ self.calls.append((method, params))+ return {"voice_stopped": True}+ return await super().rpc(method, _timeout=_timeout, **params)++ client = Client([])+ conn = GatewayConnection(connect=connect_with(client))+ conn.start(5)+ conn.state(SID)+ try:+ printed = []+ agent = GatewayAgent(connection=conn, session_id=SID)+ agent._print_fn = printed.append+ done = {}+ worker = threading.Thread(target=lambda: done.setdefault("r", agent.run_conversation(+ "stop", conversation_history=[{"role": "user", "content": "hi"}])), daemon=True)+ worker.start()+ worker.join(8)+ assert not worker.is_alive(), "run_conversation hung waiting for a turn that was never admitted"+ result = done["r"]+ assert result["voice_stopped"] is True and not result["failed"] and result["final_response"] == ""+ assert result["messages"] == [{"role": "user", "content": "hi"}], "nothing was admitted"+ assert "prompt.receipt" not in [m for m, _ in client.calls]+ assert any(t("cli.voice.stop_phrase_typed") in line for line in printed), printed+ finally:+ conn.close()diff --git a/tests/tui_gateway/test_voice_stopped_consumers.py b/tests/tui_gateway/test_voice_stopped_consumers.pynew file mode 100644index 00000000000..309e53a952c--- /dev/null+++ b/tests/tui_gateway/test_voice_stopped_consumers.py@@ -0,0 +1,53 @@+"""TUI-26: every Python caller of the owner's canonical ``prompt.submit`` treats the declared+``{voice_stopped: true}`` reply (a bare stop phrase typed into a LOCAL voice chat: the chat ends and+nothing is admitted) as settled with no turn, never as a malformed admission receipt."""+import asyncio+import contextlib+from types import SimpleNamespace++import pytest+++class _StopClient:+ def __init__(self):+ self.calls, self.events = [], asyncio.Queue()++ async def rpc(self, method, **params):+ self.calls.append(method)+ if method == "session.resume":+ return {"session_id": params["session_id"]}+ if method == "prompt.submit":+ return {"voice_stopped": True}+ raise AssertionError(f"unexpected {method}")+++def test_owner_forward_relays_nothing_after_a_voice_stopped_reply(monkeypatch, tmp_path):+ from tui_gateway import owner_forward, server+ client = _StopClient()++ @contextlib.asynccontextmanager+ async def connect(_home, _endpoint):+ yield client+ monkeypatch.setattr(owner_forward, "discover_owner", lambda _home: "ready-owner")+ monkeypatch.setattr(owner_forward, "connect_owner", connect)+ monkeypatch.setattr(owner_forward, "forwardable", lambda *_a: True)+ emitted = []+ session = {"session_key": "stored-a", "profile_home": str(tmp_path)}+ receipt = owner_forward.forward_prompt("sid", session, "stop", emit=lambda *a: emitted.append(a))+ assert receipt == {"voice_stopped": True}+ assert client.calls == ["session.resume", "prompt.submit"]+ assert emitted == [], "no turn was admitted, so nothing is relayed or settled"+ monkeypatch.setattr(owner_forward, "forward_prompt", lambda *_a, **_k: {"voice_stopped": True})+ refusal = SimpleNamespace(ledger_status="started")+ reply = server._submit_to_ledger_owner("r", "sid", session, "stop", {}, refusal)+ assert reply["result"] == {"voice_stopped": True}, reply+++async def test_attach_view_submit_and_oneshot_return_on_a_voice_stopped_reply(capsys):+ from agent.i18n import t+ from hermes_cli.gateway_chat_view import GatewayChatView+ view = GatewayChatView(_StopClient(), {"stored_session_id": "s"})+ assert await view.submit("stop") == {"voice_stopped": True}+ assert view.mine == {}+ assert t("cli.voice.stop_phrase_typed") in capsys.readouterr().outdiff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 66dc551533e..b0957e335c4 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -753,6 +753,8 @@ def _submit_to_ledger_owner(rid, sid, session, text, params, refusal) -> dict:session.get("session_key") or sid, exc, exc_info=True)why = str(exc) if isinstance(exc, owner_forward.OwnerUnavailable) else "the gateway refused it"else:+ if receipt.get("voice_stopped") is True:+ return _ok(rid, {"voice_stopped": True}) # the owner ended its voice chat; nothing queuedreturn _ok(rid, {"status": "queued", "admission_id": receipt.get("admission_id"),"forwarded": True})return _err(rid, 4090, "The gateway is running a turn in this chat and " + whydiff --git a/tui_gateway/owner_forward.py b/tui_gateway/owner_forward.pyindex 8c1f7e21e63..f9d6e087bf1 100644--- a/tui_gateway/owner_forward.py+++ b/tui_gateway/owner_forward.py@@ -129,6 +129,11 @@ class _Relay:attached = await client.rpc("session.resume", session_id=self.key)target = str(attached.get("session_id") or self.key)receipt = await self._submit(client, target)+ if receipt.get("voice_stopped") is True:+ # TUI-26: the owner took a typed stop phrase as the end of its LOCAL voice chat and+ # admitted nothing: there is no turn to relay.+ self.admitted.set_result(receipt)+ returnadmission_id = receipt.get("admission_id")if not isinstance(admission_id, str) or receipt.get("status") not in ("queued", "started", "terminal"):raise OwnerUnavailable("the gateway did not admit it")