The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): settle the turn before best-effort post-turn trim/TTS
StanleyStetson5babdc36f6e0
diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.pyindex c069f3bae18..3d6ef13fd13 100644--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@ -36,7 +36,8 @@ def test_refused_input_commits_failed_mailbox_receipt(tmp_path):"_TurnRun": prompt_turn._TurnRun,"_record_turn_marker": lambda *args, **kwargs: "marker","_prepare_turn_input": lambda *args: None,- "_finish_turn": noop, "_clear_inflight_turn": noop,+ "_release_turn_scopes": noop, "_post_turn_housekeeping": noop,+ "_clear_inflight_turn": noop,# Hosted room member sessions drop their bot_room slot at turn end (#106847); a canonical chat is not one."_release_hosted_room_turn_slot": noop,"_retire_turn_marker": lambda *args: retired.append(args),diff --git a/tests/tui_gateway/test_prompt_accept_logging.py b/tests/tui_gateway/test_prompt_accept_logging.pyindex 5593b432f5c..4a482dc81bf 100644--- a/tests/tui_gateway/test_prompt_accept_logging.py+++ b/tests/tui_gateway/test_prompt_accept_logging.py@@ -104,3 +104,35 @@ def test_accepted_and_finished_records_on_success(turn_env, caplog):fin = finished[0].getMessage()assert "hunter2" not in fin+++def test_turn_settles_before_post_turn_trim(monkeypatch, caplog):+ """A blocked post-turn trim must not hold the session running or its bookend (#131740)."""+ import hermes_cli.mem_trim as mem_trim++ entered, release = threading.Event(), threading.Event()++ def blocking_trim(**_kw):+ entered.set()+ release.wait(timeout=10)++ monkeypatch.setattr(mem_trim, "trim_memory", blocking_trim)+ for name in ("_emit", "_wire_callbacks", "_register_session_cwd", "_sync_session_key_after_compress"):+ monkeypatch.setattr(server, name, lambda *a, **k: None)+ monkeypatch.setattr(server, "_sync_agent_model_with_config", lambda sid, session: None)+ monkeypatch.setattr(server, "_tts_stream_begin", lambda: None)+ monkeypatch.setattr(server, "_get_usage", lambda agent: {})+ agent = types.SimpleNamespace(+ session_id="agent-sid-1", run_conversation=lambda *a, **k: {"final_response": "done"},+ clear_interrupt=lambda: None)+ session = _session(agent=agent, running=True)+ monkeypatch.setattr(server, "_sessions", {"ui-sid": session})+ try:+ with caplog.at_level(logging.INFO, logger="tui_gateway.server"):+ assert server._run_prompt_submit("rid", "ui-sid", session, "hi")+ assert entered.wait(timeout=5)+ assert session["running"] is False+ assert len(_records(caplog, "tui turn finished")) == 1+ finally:+ release.set()+ session["_run_thread"].join(timeout=5)diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex ed2a482b580..e324c1e2903 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -20255,8 +20255,7 @@ def test_periodic_trim_runs_once_every_session_is_quiescent(monkeypatch):def test_turn_completion_trim_skips_while_another_session_is_running(monkeypatch):- """The finishing session is still marked running when _finish_turn runs, so only OTHER sessions gate its- trim: a sole session trims at every turn end; a second in-flight turn defers it (#58576)."""+ """Only OTHER sessions gate the post-turn trim: a sole session trims at every turn end; a second in-flight turn defers it (#58576)."""calls = _periodic_trim_calls(monkeypatch)monkeypatch.setattr(server, "_clear_session_context", lambda tokens: None)now = time.time()@@ -20264,12 +20263,12 @@ def test_turn_completion_trim_skips_while_another_session_is_running(monkeypatchserver._sessions.clear()server._sessions["own"] = owntry:- server._finish_turn("own", own, server._TurnRun(agent=None, one_turn_restore=None, terminal_callback=None, receipt_committed=True))+ server._post_turn_housekeeping("own", own, server._TurnRun(agent=None, one_turn_restore=None, terminal_callback=None, receipt_committed=True))assert len(calls) == 1calls.clear()server._sessions["other"] = _idle_evictable_session(now) | {"running": True}- server._finish_turn("own", own, server._TurnRun(agent=None, one_turn_restore=None, terminal_callback=None, receipt_committed=True))+ server._post_turn_housekeeping("own", own, server._TurnRun(agent=None, one_turn_restore=None, terminal_callback=None, receipt_committed=True))assert calls == []finally:server._sessions.clear()diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 9a811ff756a..90d4290b9ff 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -460,7 +460,7 @@ def _run_post_turn_followups(# not consume session A's event. Unclaimable events are requeued for the poller.try:from tools.process_registry import process_registry- # _finish_turn has released the worker's runtime scope. Queue ownership,+ # _post_turn_housekeeping has released the worker's runtime scope. Queue ownership,# notification policy and nested dispatch still belong to this session.with _session_profile_runtime_scope(session):drained = process_registry.drain_notifications(@@ -1027,27 +1027,14 @@ def _recover_turn_exception(sid: str, session: dict, st: _TurnRun, e: BaseExcept_emit("error", sid, {"message": str(e)})-def _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:- """Finally-path of the turn: release everything, then the "tui turn finished" bookend."""+def _release_turn_scopes(sid: str, session: dict, st: _TurnRun) -> None:+ """Finally-path, before settlement: drop snapshots, undo a one-turn model, reset scopes (home stays bound)."""# Drop both pre-turn history snapshots before asking glibc to return pages (a test# inspects these two locals by name).history, run_kwargs = st.history, st.run_kwargshistory.clear()if isinstance(run_kwargs, dict):run_kwargs.clear()- try: # while the profile HERMES_HOME override is still active (session's own config)- from hermes_cli.mem_trim import trim_memory- # The finishing session is still marked running here; every OTHER session must be idle (#58576).- if _sessions_quiescent(exclude=sid):- trim_memory(reason="tui turn completion")- except Exception:- logger.debug("post-turn memory trim failed", exc_info=True)- if st.thinking_started:- with contextlib.suppress(Exception):- from tools.voice_mode import stop_thinking_sound- stop_thinking_sound()- if st.tts_queue is not None:- st.tts_queue.put(None) # end-of-text sentinel — flush + finish speakingif st.one_turn_restore:try:_restore_agent_model_runtime(st.agent, st.one_turn_restore)@@ -1061,8 +1048,6 @@ def _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:if scopes.approval is not None:from tools.approval_context import reset_current_session_keyreset_current_session_key(scopes.approval)- if scopes.home is not None:- reset_hermes_home_override(scopes.home)if scopes.secret is not None:reset_secret_scope(scopes.secret)if scopes.terminal is not None:@@ -1071,6 +1056,25 @@ def _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:_clear_session_context(scopes.session_tokens)+def _post_turn_housekeeping(sid: str, session: dict, st: _TurnRun) -> None:+ """Best-effort tail AFTER the turn settled: a slow trim/TTS flush must not hold the bookend (#131740)."""+ try: # while the profile HERMES_HOME override is still active (session's own config)+ from hermes_cli.mem_trim import trim_memory+ # Every OTHER session must be idle (#58576).+ if _sessions_quiescent(exclude=sid):+ trim_memory(reason="tui turn completion")+ except Exception:+ logger.debug("post-turn memory trim failed", exc_info=True)+ if st.thinking_started:+ with contextlib.suppress(Exception):+ from tools.voice_mode import stop_thinking_sound+ stop_thinking_sound()+ if st.tts_queue is not None:+ st.tts_queue.put(None) # end-of-text sentinel — flush + finish speaking+ if st.scopes.home is not None:+ reset_hermes_home_override(st.scopes.home)++# Bounded so a contended state.db cannot hold ``_sessions_lock``; a skipped heal is retried on the next prompt._ROUTING_REOPEN_PATIENCE_S = 0.5@@ -1182,7 +1186,7 @@ def _run_prompt_submit(except Exception as e:_recover_turn_exception(sid, session, st, e)finally:- _finish_turn(sid, session, st)+ _release_turn_scopes(sid, session, st)_current_runtime_session_record.reset(runtime_session_token)reset_transport(transport_token)# A stale interim closure must not fire during a later turn.@@ -1215,6 +1219,7 @@ def _run_prompt_submit(session.pop("_hosted_room_task", None)session.pop("_auto_continue_scheduled", None)_emit_settled_session_info(sid, session, st.agent)+ _post_turn_housekeeping(sid, session, st)return st.result, goal_followupdef run():from agent.notification_presentation import notification_turn