Skip to content

The agent that grows with you

fix(agent): reasoning promoted on a reasoning-only clean stop is never persisted as an ordinary reply

teknium1eb11e7eac932
diff --git a/agent/turn_final_response.py b/agent/turn_final_response.py
index 71dcd185ddf..889c2e99af0 100644
--- a/agent/turn_final_response.py
+++ b/agent/turn_final_response.py
@@ -77,22 +77,30 @@ def finish_text_response(
# delimiter. ``finish_reason == "stop"`` means the provider considers generation
# complete, so the empty-response ladder would only re-bill the same input to arrive
# at a truncated preview of this text; promote the reasoning to the visible answer
- # BEFORE the ladder. ``length`` (cut off mid-thought) stays on the continuation path,
- # and the promoted text is persisted as ordinary content so the next turn replays it.
+ # BEFORE the ladder. ``length`` (cut off mid-thought) stays on the continuation path.
+ # The promoted text is RETURNED as the answer but never written into the assistant
+ # row's ``content``: chain-of-thought stored as ordinary content is indistinguishable
+ # from a real reply on every history surface (#111761). The row keeps ``content``
+ # empty with the text in its reasoning fields and carries the promoted text as the
+ # ``api_content`` sidecar, so the next turn still replays it byte-identically.
_content = assistant_message.content
+ _promoted = None
if (
finish_reason == "stop"
and not assistant_message.tool_calls
and (_content is None or (isinstance(_content, str) and not _content.strip()))
):
- _promoted = agent._extract_reasoning(assistant_message)
+ _promoted = agent._extract_reasoning(assistant_message) or None
if _promoted:
- logger.info(
- "Reasoning-only clean stop (%d chars) — using reasoning as the final response",
- len(_promoted),
+ # WARNING, not INFO: a model that keeps ending turns this way is stalled
+ # (planning monologue, zero tool calls) while the turn reports "complete".
+ logger.warning(
+ "Reasoning-only clean stop (%d chars) — returning the reasoning as the final "
+ "response (model=%s provider=%s api_calls=%d tool_turns=%d)",
+ len(_promoted), agent.model, agent.provider, api_call_count,
+ sum(1 for m in messages if isinstance(m, dict) and m.get("role") == "assistant" and m.get("tool_calls")),
)
- assistant_message.content = _promoted
- final_response = assistant_message.content or ""
+ final_response = _promoted or assistant_message.content or ""
# Unmute: _mute_post_response from a housekeeping tool turn must not silence
# empty-response warnings on the final response path.
agent._mute_post_response = False
@@ -187,6 +195,10 @@ def finish_text_response(
final_response = agent._strip_think_blocks(final_response).strip()
final_msg = agent._build_assistant_message(assistant_message, finish_reason)
+ if _promoted:
+ # Replay sidecar only: ``content`` stays empty so the row is never mistaken for a
+ # real reply; ``build_api_messages`` substitutes ``api_content`` on the wire.
+ final_msg["api_content"] = final_response
# Dropped tool-call recovery (copilot/Claude): finish_reason="tool_calls" with empty
# tool_calls would end the turn unstarted; re-prompt (max 3 CONSECUTIVE stalls).
diff --git a/tests/agent/test_empty_terminal_reasoning_surface.py b/tests/agent/test_empty_terminal_reasoning_surface.py
index 21c13ad3044..6711a329f0e 100644
--- a/tests/agent/test_empty_terminal_reasoning_surface.py
+++ b/tests/agent/test_empty_terminal_reasoning_surface.py
@@ -91,9 +91,12 @@ def test_clean_stop_reasoning_only_returns_on_first_call(tmp_path, monkeypatch):
assert result["final_response"] == "The answer is 42 because of the calculation above."
assert result["api_calls"] == 1
- # The promoted text is durable content, so the next turn replays a real answer.
- assert result["messages"][-1]["role"] == "assistant"
- assert result["messages"][-1]["content"] == "The answer is 42 because of the calculation above."
+ # The promoted text replays as a real answer through the api_content sidecar; the row's
+ # own content stays empty so chain-of-thought is never persisted as an ordinary reply.
+ row = result["messages"][-1]
+ assert row["role"] == "assistant"
+ assert not row.get("content")
+ assert row["api_content"] == "The answer is 42 because of the calculation above."
def test_exhausted_truly_empty_keeps_existing_behavior(tmp_path, monkeypatch):
diff --git a/tests/agent/test_reasoning_only_stop_persistence.py b/tests/agent/test_reasoning_only_stop_persistence.py
new file mode 100644
index 00000000000..8e81b384701
--- /dev/null
+++ b/tests/agent/test_reasoning_only_stop_persistence.py
@@ -0,0 +1,92 @@
+"""Reasoning promoted on a reasoning-only clean stop is returned, never persisted as a reply.
+
+A clean ``stop`` with empty content and reasoning text is promoted to ``final_response`` (the
+vLLM nemotron parser files the whole answer as reasoning; re-running the empty-response ladder
+re-bills the prompt). The promoted text must NOT become the assistant row's ordinary ``content``:
+chain-of-thought stored as content is indistinguishable from a real reply on every history
+surface (#111761). The row keeps ``content`` empty and carries the text as the ``api_content``
+sidecar, so the next request still replays the answer byte-identically.
+"""
+
+from __future__ import annotations
+
+import logging
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+REASONING = "嗯,长度合适。Let me check the file first."
+
+
+def loop_agent():
+ from run_agent import AIAgent
+ with (
+ patch("model_tools.get_tool_definitions", return_value=[]),
+ patch("model_tools.check_toolset_requirements", return_value={}),
+ patch("agent.process_bootstrap.OpenAI"),
+ ):
+ agent = AIAgent(
+ api_key="test-key-1234567890",
+ base_url="https://api.deepseek.com/v1",
+ model="deepseek-reasoner",
+ provider="deepseek",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ agent.client = MagicMock()
+ agent._cached_system_prompt = "You are helpful."
+ agent._use_prompt_caching = False
+ agent.compression_enabled = False
+ agent.save_trajectories = False
+ return agent
+
+
+def _run(agent, responses, user_message="hello", conversation_history=None):
+ agent.client.chat.completions.create.side_effect = list(responses)
+ with (
+ patch.object(agent, "_persist_session"),
+ patch.object(agent, "_save_trajectory"),
+ patch.object(agent, "_cleanup_task_resources"),
+ ):
+ return agent.run_conversation(user_message, conversation_history=conversation_history)
+
+
+def test_promoted_reasoning_is_returned_but_persisted_row_keeps_content_empty(loop_agent):
+ from tests.agent.test_run_agent import _mock_response
+
+ result = _run(loop_agent, [_mock_response(content="", finish_reason="stop", reasoning_content=REASONING)])
+
+ # Return contract from the parser-compat fix survives: one call, the reasoning is the answer.
+ assert result["final_response"] == REASONING
+ assert result["api_calls"] == 1
+
+ row = result["messages"][-1]
+ assert row["role"] == "assistant"
+ assert not row.get("content") # never chain-of-thought as an ordinary reply
+ assert row["reasoning"] == REASONING
+ assert row["api_content"] == REASONING
+
+ # The next request still replays the promoted text as the assistant's own turn.
+ _run(loop_agent, [_mock_response(content="Second answer.", finish_reason="stop")],
+ user_message="next", conversation_history=result["messages"])
+ sent = loop_agent.client.chat.completions.create.call_args.kwargs["messages"]
+ assistant_rows = [m for m in sent if m.get("role") == "assistant"]
+ assert [m["role"] for m in sent] == ["system", "user", "assistant", "user"]
+ assert assistant_rows[0]["content"] == REASONING
+ assert "api_content" not in assistant_rows[0]
+
+
+def test_reasoning_only_clean_stop_logs_warning_with_route(loop_agent, caplog):
+ from tests.agent.test_run_agent import _mock_response
+
+ with caplog.at_level(logging.WARNING, logger="agent.conversation_loop"):
+ _run(loop_agent, [_mock_response(content=None, finish_reason="stop", reasoning_content=REASONING)])
+
+ hits = [r for r in caplog.records if r.getMessage().startswith("Reasoning-only clean stop")]
+ assert len(hits) == 1
+ assert hits[0].levelno == logging.WARNING
+ assert f"model={loop_agent.model}" in hits[0].getMessage()
+ assert "provider=deepseek" in hits[0].getMessage()
+ assert "tool_turns=0" in hits[0].getMessage()
diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.md
index 6dccf68dcfc..78f34343f0f 100644
--- a/website/docs/developer-guide/session-storage.md
+++ b/website/docs/developer-guide/session-storage.md
@@ -229,6 +229,7 @@ Notes:
- `reasoning_details`, `codex_reasoning_items`, and `codex_message_items` are stored as JSON strings
- Desktop history hydration retains assistant sidecars in both REST and JSON-RPC (`session.resume`, `session.activate`, `session.history`) projections, including rows with reasoning and tool calls. REST may return the SQLite JSON string while RPC returns decoded items; Desktop accepts both. A final Responses reply may live only in `codex_message_items` while `content` is empty. Canonical content still takes precedence, and analysis/commentary items are not promoted to reply text.
- `reasoning` stores the raw reasoning text for providers that expose it
+- A reasoning-only clean stop (empty `content`, `finish_reason=stop`, reasoning present) is answered with the reasoning text, but the assistant row is never written with that text as `content`: `content` stays empty, the text lives in `reasoning`/`reasoning_content`, and `api_content` carries it so the next request replays the answer byte-identically. History surfaces therefore show it as reasoning, not as a reply.
- `api_content` is a byte-fidelity sidecar: the exact content string sent to the API for this message when it differs from `content` (ephemeral memory/plugin injections, persist overrides). It preserves the wire bytes for prompt-cache-stable replay — stored as sent, except lone surrogates, which sqlite3 cannot bind and which the conversation loop scrubs from every outgoing payload anyway. `NULL` means `content` was sent verbatim.
- Timestamps are Unix epoch floats (`time.time()`)