The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): release the turn in a finally so a mid-tail failure cannot wedge the session running
Yagna Vudathubccd45618c16
diff --git a/acp_adapter/server.py b/acp_adapter/server.pyindex eb45bf9fa3f..4f0affc5a2f 100644--- a/acp_adapter/server.py+++ b/acp_adapter/server.py@@ -940,55 +940,57 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):streamed_message: bool,) -> PromptResponse:"""Persist, emit provenance/final text, drain queued prompts, report usage."""- # Key presence, not truthiness: ``messages=[]`` is a legitimate cleared transcript (#10844);- # only a result without the key leaves the history untouched.- if "messages" in result and isinstance(result["messages"], list):- state.history = result["messages"]- self.session_manager.save_session(session_id)-- # Head rotated (compression split): emit provenance so clients can render the boundary.- post_turn_hermes_id = getattr(state.agent, "session_id", None)- if conn and post_turn_hermes_id and pre_turn_hermes_id and post_turn_hermes_id != pre_turn_hermes_id:- try:- await self._send_session_info_update(- session_id, current_hermes_session_id=post_turn_hermes_id,- previous_hermes_session_id=pre_turn_hermes_id,- )- except Exception:- logger.debug("Could not emit ACP provenance update after rotation for %s", session_id, exc_info=True)-- final_response = result.get("final_response") or "" # None on an interrupted turn- cancelled = bool(state.cancel_event and state.cancel_event.is_set())- # The local "waiting for model" interrupt status is metadata, not prose; stop_reason carries it.- from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX-- interrupted = bool(result.get("interrupted")) or cancelled- suppress = interrupted and final_response.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)- # Send the final text unless already streamed — or if a plugin hook transformed it after.- if final_response and conn and not suppress and (not streamed_message or result.get("response_transformed")):- update = acp.update_agent_message_text(final_response)- if state.message_ids is not None:- # A plugin-rewritten reply replaces the streamed bubble (same id); an- # unstreamed final response opens its own.- if streamed_message and result.get("response_transformed"):- update.message_id = state.message_ids.last() or state.message_ids.current()- else:- update.message_id = state.message_ids.current()- state.message_ids.close()- await conn.session_update(session_id, update)-- # Go idle before draining so recursive prompt() calls can acquire the session.- with state.runtime_lock:- state.is_running = False- state.current_prompt_text = ""- while True:+ try:+ # Key presence, not truthiness: ``messages=[]`` is a legitimate cleared transcript (#10844);+ # only a result without the key leaves the history untouched.+ if "messages" in result and isinstance(result["messages"], list):+ state.history = result["messages"]+ self.session_manager.save_session(session_id)++ # Head rotated (compression split): emit provenance so clients can render the boundary.+ post_turn_hermes_id = getattr(state.agent, "session_id", None)+ if conn and post_turn_hermes_id and pre_turn_hermes_id and post_turn_hermes_id != pre_turn_hermes_id:+ try:+ await self._send_session_info_update(+ session_id, current_hermes_session_id=post_turn_hermes_id,+ previous_hermes_session_id=pre_turn_hermes_id,+ )+ except Exception:+ logger.debug("Could not emit ACP provenance update after rotation for %s", session_id, exc_info=True)++ final_response = result.get("final_response") or "" # None on an interrupted turn+ cancelled = bool(state.cancel_event and state.cancel_event.is_set())+ # The local "waiting for model" interrupt status is metadata, not prose; stop_reason carries it.+ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX++ interrupted = bool(result.get("interrupted")) or cancelled+ suppress = interrupted and final_response.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)+ # Send the final text unless already streamed — or if a plugin hook transformed it after.+ if final_response and conn and not suppress and (not streamed_message or result.get("response_transformed")):+ update = acp.update_agent_message_text(final_response)+ if state.message_ids is not None:+ # A plugin-rewritten reply replaces the streamed bubble (same id); an+ # unstreamed final response opens its own.+ if streamed_message and result.get("response_transformed"):+ update.message_id = state.message_ids.last() or state.message_ids.current()+ else:+ update.message_id = state.message_ids.current()+ state.message_ids.close()+ await conn.session_update(session_id, update)++ finally:+ # Go idle before draining so recursive prompt() calls can acquire the session.with state.runtime_lock:- if not state.queued_prompts:- break- next_prompt = state.queued_prompts.pop(0)- if conn:- await conn.session_update(session_id, acp.update_user_message_text(next_prompt))- await self.prompt(prompt=[TextContentBlock(type="text", text=next_prompt)], session_id=session_id)+ state.is_running = False+ state.current_prompt_text = ""+ while True:+ with state.runtime_lock:+ if not state.queued_prompts:+ break+ next_prompt = state.queued_prompts.pop(0)+ if conn:+ await conn.session_update(session_id, acp.update_user_message_text(next_prompt))+ await self.prompt(prompt=[TextContentBlock(type="text", text=next_prompt)], session_id=session_id)usage = Noneif any(result.get(k) is not None for k in ("prompt_tokens", "completion_tokens", "total_tokens")):diff --git a/tests/acp_adapter/test_finish_turn_finally.py b/tests/acp_adapter/test_finish_turn_finally.pynew file mode 100644index 00000000000..f4459269d72--- /dev/null+++ b/tests/acp_adapter/test_finish_turn_finally.py@@ -0,0 +1,79 @@+"""Mid-tail failure in _finish_turn must not wedge the session running (#115588).++An exception in the _finish_turn tail (persist/provenance/final-text sends)+used to skip the bare is_running=False release, leaving the session wedged+running and queued prompts stranded. The tail must release is_running /+current_prompt_text in a finally and still drain the queue.+"""++from __future__ import annotations++import asyncio+import threading+from types import SimpleNamespace++import pytest++from acp_adapter.server import HermesACPAgent+from acp_adapter.session import SessionState+++class _BoomConn:+ """Fails the final-text session_update once (transient mid-tail failure)."""++ def __init__(self) -> None:+ self.calls = 0++ async def session_update(self, session_id, update):+ self.calls += 1+ if self.calls == 1:+ raise RuntimeError("mid-tail boom")+++async def _noop_coro(*args, **kwargs):+ return None+++def _make_server():+ server = HermesACPAgent.__new__(HermesACPAgent)+ server.session_manager = SimpleNamespace(save_session=lambda sid: None)+ server._conn = None+ drained = []++ async def fake_prompt(*, prompt, session_id, **kwargs):+ from acp.schema import PromptResponse++ drained.append(([getattr(b, "text", None) for b in prompt], session_id))+ return PromptResponse(stop_reason="end_turn")++ server.prompt = fake_prompt # type: ignore[method-assign]+ server._send_usage_update = _noop_coro # type: ignore[method-assign]+ return server, drained+++def _running_state() -> SessionState:+ return SessionState(+ session_id="s1",+ agent=SimpleNamespace(session_id="h1"),+ history=[],+ cancel_event=None,+ is_running=True,+ queued_prompts=["queued-one"],+ runtime_lock=threading.Lock(),+ current_prompt_text="hello",+ )+++def test_finish_turn_mid_tail_failure_releases_and_drains():+ server, drained = _make_server()+ state = _running_state()+ conn = _BoomConn()+ result = {"final_response": "done", "messages": []}++ with pytest.raises(RuntimeError, match="mid-tail boom"):+ asyncio.run(server._finish_turn(state, "s1", conn, result, "h1", False))++ assert state.is_running is False+ assert state.current_prompt_text == ""+ assert state.queued_prompts == []+ assert drained == [(["queued-one"], "s1")]