The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): name a final that reuses an already-delivered response
kshitijk4poorf33d817404dd
diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 639e99ed424..1fcf604a3af 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -600,6 +600,7 @@ _PER_TURN_RESET_STATE: Tuple[Tuple[str, Any], ...] = (("_codex_reasoning_only_streak", 0),("_thinking_prefill_retries", 0), ("_post_tool_empty_retried", False),("_last_content_with_tools", None), ("_last_content_tools_all_housekeeping", False),+ ("_reused_response_text", None),("_mute_post_response", False), ("_unicode_sanitization_passes", 0),("_tool_guardrail_halt_decision", None),("_harness_metrics_turn", None),diff --git a/agent/turn_empty_response.py b/agent/turn_empty_response.pyindex 92339b18d4b..dda33917a25 100644--- a/agent/turn_empty_response.py+++ b/agent/turn_empty_response.py@@ -190,6 +190,9 @@ def recover_empty_response(# Do NOT modify the assistant message content (injected text poisoned history).final_response = agent._strip_think_blocks(fallback).strip()agent._response_was_previewed = True+ # The final IS the response streamed before the housekeeping tool: name that identity+ # so a client settles the text it already shows instead of painting it a second time.+ agent._reused_response_text = final_responsereturn _verdict("break")# Post-tool-call empty (no prior content, or only mid-task narration): nudge once.diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex f71dd6c1bb9..efd5e532795 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -144,6 +144,8 @@ def _resolve_budget_fallback(final_response = _pending_verification_responseif _pending_verification_response_previewed:agent._response_was_previewed = True+ # Reuses the candidate the user already saw sealed as an interim (#130396).+ agent._reused_response_text = final_responsepreserved_verification_fallback = Trueelse:# _handle_max_iterations makes one extra toolless request for a summary.@@ -692,6 +694,9 @@ def finalize_turn("response_transformed": _response_transformed,"pre_transform_response": _pre_transform_response,"response_previewed": getattr(agent, "_response_was_previewed", False),+ # The final is byte-for-byte a response this turn already delivered (no footer or+ # explanation appended since): it carries no new text for the client to paint.+ "response_reused": bool(final_response) and final_response == getattr(agent, "_reused_response_text", None),"model": agent.model,# requested_model / served_model: proxy-reported deployment or Hermes' own fallback route.**result_model_fields(agent),@@ -740,6 +745,7 @@ def finalize_turn(if _leftover_steer:result["pending_steer"] = _leftover_steeragent._response_was_previewed = False+ agent._reused_response_text = Noneif interrupted and agent._interrupt_message:result["interrupt_message"] = agent._interrupt_messageagent.clear_interrupt()diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 4d82994b8c7..3f68c2dfc12 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4562,6 +4562,7 @@ export interface MessageCompletePayload {reasoning?: string | nullwarning?: string | nullresponse_previewed?: boolean | null+ response_reused?: boolean | nullresponse_transformed?: boolean | nullbilling?: BillingBlock | nullfailure_reason?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 9f32d89102d..8cf27e31454 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -18446,6 +18446,18 @@"default": null,"title": "Response Previewed"},+ "response_reused": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Response Reused"+ },"response_transformed": {"anyOf": [{diff --git a/tests/agent/test_empty_response_recovery_persistence.py b/tests/agent/test_empty_response_recovery_persistence.pyindex 2bf8d4612a6..5f93b1e73ed 100644--- a/tests/agent/test_empty_response_recovery_persistence.py+++ b/tests/agent/test_empty_response_recovery_persistence.py@@ -267,3 +267,42 @@ def test_stop_during_empty_response_recovery_keeps_the_executed_tool_call_live(r_assert_saved_tool_pairs_stay_live(result, real_loop.db, real_loop.sid)# The Stop owner strips the nudge scaffold itself and closes with its own reason.assert result["messages"][-1]["content"] == result["final_response"]+++def _call(name, args, call_id):+ return SimpleNamespace(id=call_id, type="function", function=SimpleNamespace(name=name, arguments=json.dumps(args)))+++def test_housekeeping_fallback_names_its_final_a_reused_response(real_loop):+ """The empty follow-up after a housekeeping tool ends the turn on the answer the model sent+ BEFORE that tool. The result says so, so a client settles the answer it already shows+ instead of painting it a second time in the same bubble."""+ real_loop.agent.valid_tool_names.add("todo_list")+ real_loop.agent.tools.append({"type": "function", "function": {"name": "todo_list", "parameters": {}}})+ result = real_loop.run(+ [+ _response("Here is the answer.", finish_reason="tool_calls",+ tool_calls=[_call("todo_list", {"todos": []}, "call_todo")]),+ _response(),+ ],+ "answer, then tidy",+ )++ assert result["turn_exit_reason"] == "fallback_prior_turn_content"+ assert result["final_response"] == "Here is the answer."+ assert result["response_reused"] is True+++def test_same_words_in_a_second_response_are_not_a_reused_response(real_loop):+ """Two real responses with the same words: the final is new output, never a reuse."""+ result = real_loop.run(+ [+ _response("Done.", finish_reason="tool_calls",+ tool_calls=[_call("read_file", {"path": "missing.txt"}, "call_read")]),+ _response("Done."),+ ],+ "say it twice",+ )++ assert result["final_response"] == "Done."+ assert result["response_reused"] is Falsediff --git a/tests/tui_gateway/test_turn_payload_reused_final.py b/tests/tui_gateway/test_turn_payload_reused_final.pynew file mode 100644index 00000000000..fc67f346c7e--- /dev/null+++ b/tests/tui_gateway/test_turn_payload_reused_final.py@@ -0,0 +1,44 @@+"""message.complete names a final that reuses a response the turn already delivered.++The housekeeping-tool fallback (turn_empty_response, ``fallback_prior_turn_content``) ends a+turn on the answer the model streamed BEFORE its tool call. The renderer bounds "the current+response" at the bubble's last tool row, so without an identity it appended that answer again:+the same reply twice in one bubble, nothing between the copies when the tool is silent+(``todo_list``). ``response_reused`` is set where the reuse happens, never inferred from equal+text: a model that says the same words in two responses keeps both.+"""++import contextlib+from types import SimpleNamespace++import tui_gateway.server as srv+from agent.stream_delivery import StreamDeliveryMixin+++class _Agent(StreamDeliveryMixin):+ _session_title_hint = "Scratch"+++def _payload(monkeypatch, result):+ monkeypatch.setattr(srv, "_get_usage", lambda _agent: {})+ monkeypatch.setattr(srv, "render_message", lambda _text, _cols: None)+ monkeypatch.setattr(srv, "_clear_inflight_turn", lambda _session: None)+ agent = _Agent()+ session = {"pending_title": None, "session_key": "k", "history_lock": contextlib.nullcontext(), "agent": agent}+ st = SimpleNamespace(+ result=result, agent=agent, terminal_callback=None, receipt_committed=True, receipt_attempted=False,+ marker_key="", error_retained=False, error_detail="", prompt_text="ping",+ )+ payload, _, _ = srv._complete_turn_payload(session, st, None, 80)+ return payload+++def test_reused_final_is_named_on_the_wire(monkeypatch):+ payload = _payload(monkeypatch, {"final_response": "Here is the answer.", "response_previewed": True,+ "response_reused": True})+ assert payload["response_reused"] is True+ assert srv._event_frame("message.complete", "sid", payload)["params"]["payload"]["response_reused"] is True+++def test_a_fresh_final_is_not_named_reused(monkeypatch):+ assert "response_reused" not in _payload(monkeypatch, {"final_response": "Here is the answer."})diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 78690c6a665..7751a1f6189 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -192,6 +192,8 @@ class MessageCompletePayload(Payload):reasoning: str | None = Nonewarning: str | None = Noneresponse_previewed: bool | None = None+ #: ``text`` is a response this turn already delivered (streamed and/or sealed) — it adds no text.+ response_reused: bool | None = Noneresponse_transformed: bool | None = Nonebilling: BillingBlock | None = Nonefailure_reason: str | None = Nonediff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 6152dd0c9f6..d4a954ed3cc 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -947,6 +947,9 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,was_delivered = getattr(agent, "_interim_text_was_delivered", None)if result.get("response_previewed") or (callable(was_delivered) and was_delivered(raw) is True):payload["response_previewed"] = True+ # Only the agent's reuse site sets this; never inferred from equal text (a model may say the same words twice).+ if raw and result.get("response_reused"):+ payload["response_reused"] = True# transform_llm_output may rewrite the final after streaming: the renderer must treat# this payload as the authoritative replacement even without a prefix relationship.if result.get("response_transformed"):