The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): type the failed-turn boundary row so clients never read it as the model's reply
teknium13dbb417809bf
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 3957b89a348..57af87b558c 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -40,7 +40,7 @@ from agent.turn_retry_state import TurnRetryStatefrom agent.turn_api_call import handle_api_interrupt, nous_rate_limit_guard, perform_api_callfrom agent.turn_api_error import handle_api_errorfrom agent.turn_api_request import build_api_request-from agent.turn_failure_copy import failed_turn_notice, site_copy+from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, failed_turn_notice, site_copyfrom agent.turn_final_response import finish_text_responsefrom agent.turn_finalizer import finalize_turnfrom agent.turn_iteration_prep import (@@ -1693,7 +1693,9 @@ def _close_durable_failed_turn(agent, result: Any) -> None:# hedge over the whole list rather than under-report a possible side effect.start = result.get("current_turn_user_idx")turn_messages = messages[start:] if isinstance(start, int) and 0 <= start < len(messages) else messages- append_message(messages, {"role": "assistant", "content": failed_turn_notice(turn_messages)})+ append_message(messages, {+ "role": "assistant", "content": failed_turn_notice(turn_messages), "display_kind": FAILED_TURN_DISPLAY_KIND,+ })agent._flush_messages_to_session_db(messages)except Exception:logger.debug("failed-turn boundary not written", exc_info=True)diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.pyindex a980a9ff2db..e33f259223e 100644--- a/agent/turn_failure_copy.py+++ b/agent/turn_failure_copy.py@@ -43,6 +43,9 @@ PARTIAL_FAILED_TURN_NOTICE = ("This turn did not complete. Some actions may already have run; verify their effects ""before resending.")+# ``messages.display_kind`` of that row: display-only (stripped before every provider request),+# so renderers show a Hermes notice and room pollers never read it as the model's reply.+FAILED_TURN_DISPLAY_KIND = "failed_turn"def failed_turn_notice(turn_messages: Any) -> str:diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 0fcf6c84f61..1484ea2059d 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -17,7 +17,7 @@ import threadingimport timefrom agent.i18n import tfrom agent.session_activity import format_iteration_progress-from agent.turn_failure_copy import FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE+from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICEfrom contextlib import nullcontext, suppressfrom contextvars import copy_contextfrom gateway.config import Platform@@ -1721,7 +1721,7 @@ class GatewayTurnMixin:if await self.async_session_store.transcript_tail_role(session_id) != "user":returnawait self.async_session_store.append_to_transcript(session_id, {- "role": "assistant", "content": notice, "timestamp": time.time(),+ "role": "assistant", "content": notice, "timestamp": time.time(), "display_kind": FAILED_TURN_DISPLAY_KIND,})def _hmwa_classify_turn_failure(self, agent_result, history, session_entry):diff --git a/tests/acp_adapter/test_failed_turn_closure.py b/tests/acp_adapter/test_failed_turn_closure.pyindex 590290b76c4..5db652681e3 100644--- a/tests/acp_adapter/test_failed_turn_closure.py+++ b/tests/acp_adapter/test_failed_turn_closure.py@@ -144,7 +144,7 @@ def test_acp_refusal_closes_the_turn_and_is_not_replayed_into_the_next_prompt(acInvariant: the durable tail after a failed turn is a Hermes-authored assistant row (neverprovider text), and the next prompt reaches the provider as its own user row."""- from agent.turn_failure_copy import FAILED_TURN_NOTICE+ from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICEprovider, prompt, conversation_rows, db, sid, conn, server = acp@@ -155,6 +155,12 @@ def test_acp_refusal_closes_the_turn_and_is_not_replayed_into_the_next_prompt(acassert [r[0] for r in rows] == ["user", "assistant"], rowsassert rows[1][1] == FAILED_TURN_NOTICE # no tool ran: no hedging, no provider detailassert db.latest_conversation_role(sid) == "assistant"+ # Typed, so a renderer or room poller never has to match the English copy to tell the+ # boundary from a model reply.+ with sqlite3.connect(db.db_path) as c:+ kinds = [r[0] for r in c.execute(+ "SELECT display_kind FROM messages WHERE session_id = ? AND role = 'assistant'", (sid,))]+ assert kinds == [FAILED_TURN_DISPLAY_KIND]# The refusal reaches the ACP client, but never becomes canonical assistant history.texts = [getattr(getattr(u, "content", None), "text", None) or getattr(u, "text", None) for u in conn.updates]assert any(_REFUSAL_DETAIL in (t or "") for t in texts)@@ -165,6 +171,7 @@ def test_acp_refusal_closes_the_turn_and_is_not_replayed_into_the_next_prompt(acsent = [m for m in provider.requests[-1]["messages"] if m["role"] != "system"]assert [m["role"] for m in sent] == ["user", "assistant", "user"], sentassert [m["content"] for m in sent if m["role"] == "user"] == [_REFUSED, _NEW_REQUEST]+ assert sent[1] == {"role": "assistant", "content": FAILED_TURN_NOTICE} # the type never reaches the wire# Turn 3: cancelled mid-turn. The interrupt envelope carries ``final_response=None``# (no assistant text yet); ``_finish_turn`` must still report ``cancelled`` — never crashdiff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 346991441b8..846a4828bd1 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -2518,6 +2518,25 @@ def test_history_to_messages_preserves_tool_calls_for_resume_display():]+def test_history_to_messages_types_the_failed_turn_boundary_for_resume():+ """Desktop keys the failed-turn boundary on ``display_kind`` (a room poller must not post it+ as the member's reply); rows written before the closer typed it are typed on read."""+ from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE++ history = [+ {"role": "user", "content": "a"},+ {"role": "assistant", "content": FAILED_TURN_NOTICE, "display_kind": FAILED_TURN_DISPLAY_KIND},+ {"role": "user", "content": "b"},+ {"role": "assistant", "content": PARTIAL_FAILED_TURN_NOTICE}, # legacy untyped row+ {"role": "user", "content": "c"},+ {"role": "assistant", "content": f"Quoting Hermes: {FAILED_TURN_NOTICE}"}, # a real reply+ ]++ assert [m.get("display_kind") for m in server._history_to_messages(history)] == [+ None, FAILED_TURN_DISPLAY_KIND, None, FAILED_TURN_DISPLAY_KIND, None, None,+ ]++def test_history_to_messages_drops_pure_compaction_scaffolding():from agent.context_compressor import (HISTORICAL_TASK_HEADING,diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.pyindex af1954877b9..540f3a16dc8 100644--- a/tui_gateway/session_history.py+++ b/tui_gateway/session_history.py@@ -7,6 +7,7 @@ import refrom .method_ctx import bind_modulefrom agent.prompt_builder import STEER_DISPLAY_KIND+from agent.turn_failure_copy import FAILED_TURN_DISPLAY_KIND, FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE# Discord routing note (gateway/run_inbound.py::discord_triggering_note) persisted as user# ``content`` by gateways before the authored-text fix; presentation-only heal for those rows.@@ -179,6 +180,8 @@ _AUTO_CONTINUE_NOTE_PREFIX = "[System note: Your previous turn was interrupted mdef _legacy_display_kind(role: str, text: str) -> str | None:"""Display type of a synthetic row persisted untyped: new rows are typed at turn start (``persist_user_display_kind``);this prefix sniff migrates rows already on disk (a turn killed mid-run never reached the stamp)."""+ if role == "assistant" and text.strip() in (FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE):+ return FAILED_TURN_DISPLAY_KIND # failed-turn boundary written before it was typedreturn "auto_continue" if role == "user" and text.lstrip().startswith(_AUTO_CONTINUE_NOTE_PREFIX) else None