Skip to content

The agent that grows with you

fix(compaction): keep just-delivered assistant reply live across commit (#118900)

finn763946b68865bba
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 1354dfd141f..1792307104a 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -2460,6 +2460,86 @@ def _ensure_compressed_has_user_turn(original_messages: list, compressed: list)
return "placeholder_appended"
+def _ensure_compressed_keeps_last_assistant_reply(
+ original_messages: list, compressed: list,
+) -> str:
+ """Keep the latest visible assistant reply live across compaction (#118900).
+
+ A reply that just finished streaming is the row the user is reading; when an
+ engine's fold drops it into the summary region, the commit archives its row
+ (active=0) and surfaces that render it from the active set drop it on the
+ next refresh — while the content sits intact on disk. The built-in
+ compressor keeps this row in the tail (``_ensure_last_assistant_message_in_tail``),
+ but plugin engines implement their own ``compress()`` without that guard, so
+ it is enforced here, next to ``_ensure_compressed_has_user_turn``, where
+ every engine and every path (threshold preflight, engine maintenance,
+ manual /compress; in-place and rotation) routes through.
+
+ The reply is re-inserted ahead of the first surviving row that originally
+ followed it (order-preserving), else appended. Empty (reasoning-only) and
+ tool-call rows are out of scope: the former is a different bug family, the
+ latter must keep its atomic tool group.
+ """
+ from agent.context_compressor import (
+ _DB_PERSISTED_MARKER, _fresh_compaction_message_copy,
+ is_compaction_summary_message,
+ )
+
+ reply = None
+ for message in reversed(original_messages):
+ if not isinstance(message, dict) or message.get("role") != "assistant":
+ continue
+ if message.get("tool_calls") or is_compaction_summary_message(message):
+ continue
+ if not _message_text(message).strip():
+ continue
+ reply = message
+ break
+ if reply is None:
+ return "no_reply"
+ for message in compressed:
+ if (
+ isinstance(message, dict)
+ and message.get("role") == "assistant"
+ and not message.get("tool_calls")
+ and message.get("content") == reply.get("content")
+ ):
+ return "already_present"
+ anchor = _fresh_compaction_message_copy(reply)
+ # Identity scan, not list.index(): duplicate rows with identical content
+ # exist in the wild, and == would resolve to the older twin (#118900).
+ reply_pos = next(i for i, m in enumerate(original_messages) if m is reply)
+ followers = original_messages[reply_pos + 1:]
+ index = len(compressed)
+ for follower in followers:
+ if not isinstance(follower, dict):
+ continue
+ for pos, message in enumerate(compressed):
+ if (
+ isinstance(message, dict)
+ and message.get("role") == follower.get("role")
+ and message.get("content") == follower.get("content")
+ ):
+ index = pos
+ break
+ if index < len(compressed):
+ break
+ # Never sit assistant-adjacent: slide left past a kept older reply rather
+ # than breaking strict-template alternation for the reinserted row.
+ while (
+ index > 0
+ and isinstance(compressed[index - 1], dict)
+ and compressed[index - 1].get("role") == "assistant"
+ ):
+ index -= 1
+ # Post-commit contract (#98450, mirrors _insert_real_user_anchor._place):
+ # archive_and_compact durably writes every dict in `compressed` as the new
+ # active set, so stamp the copy or the next flush re-INSERTs it as a duplicate.
+ anchor[_DB_PERSISTED_MARKER] = True
+ compressed.insert(index, anchor)
+ return "reinserted"
+
+
def _messages_match_scoped_identity(left: Any, right: Any) -> bool:
"""Compare the live turn identity we care about for rotation stamping."""
if (
@@ -4079,6 +4159,9 @@ def compress_context(
_warn_summary_or_aux_fallback(agent)
_fold_todo_snapshot(agent, compressed)
compressed_user_turn_outcome = _ensure_compressed_has_user_turn(messages, compressed)
+ # A just-delivered reply the engine folded away must stay live or the
+ # next render drops it from the surface (#118900).
+ _ensure_compressed_keeps_last_assistant_reply(messages, compressed)
new_system_prompt = _rebuild_system_prompt_at_boundary(agent, system_message)
commit = _commit_compaction(
agent, messages, compressed, in_place=in_place, lease=lease, new_system_prompt=new_system_prompt,
diff --git a/tests/agent/test_compression_abort_state_reset.py b/tests/agent/test_compression_abort_state_reset.py
index 602b99d6f61..5f3a47c00a7 100644
--- a/tests/agent/test_compression_abort_state_reset.py
+++ b/tests/agent/test_compression_abort_state_reset.py
@@ -107,6 +107,14 @@ class TestAbortPathsResetPerAttemptState:
{"role": "user", "content": "old question"},
{"role": "assistant", "content": "old answer"},
]
+ # Bulk middle so the stub fold genuinely shrinks: the commit
+ # guard keeps a dropped last reply live (#118900), and a 2-row
+ # transcript cannot shrink once "old answer" is restored —
+ # refusal (keep everything live) would be correct there, but
+ # this test needs one successful compaction first.
+ for i in range(10):
+ original.append({"role": "user", "content": f"old bulk question {i} " + "x" * 60})
+ original.append({"role": "assistant", "content": f"old bulk answer {i} " + "y" * 60})
agent._flush_messages_to_session_db(original, [])
compacted, history = self._in_place_success(agent, original)
diff --git a/tests/agent/test_compression_concurrent_fork.py b/tests/agent/test_compression_concurrent_fork.py
index 70aa7696a75..bfa54a756bc 100644
--- a/tests/agent/test_compression_concurrent_fork.py
+++ b/tests/agent/test_compression_concurrent_fork.py
@@ -722,6 +722,14 @@ def test_durable_message_committed_before_lease_is_adopted(
parent_sid = "PRE_LEASE_DURABLE_RACE"
db.create_session(parent_sid, source="webui")
db.append_message(parent_sid, "user", "old durable")
+ # A genuinely compressible middle: the commit-site guards now keep a
+ # dropped last assistant reply live (#118900), so a 2-row transcript can
+ # no longer shrink once the late row is restored — refusal (keep
+ # everything live) would be the correct outcome there. Bulk old rows give
+ # the stub fold real middle to reclaim, as in production.
+ for i in range(10):
+ db.append_message(parent_sid, "user", f"old durable question {i} " + "x" * 60)
+ db.append_message(parent_sid, "assistant", f"old durable answer {i} " + "y" * 60)
# Frontend takes its snapshot, then another producer commits before this
# compressor acquires the lease.
@@ -735,10 +743,13 @@ def test_durable_message_committed_before_lease_is_adopted(
agent.context_compressor.compress.assert_called_once()
compressed_arg = agent.context_compressor.compress.call_args.args[0]
- assert [m["content"] for m in compressed_arg] == [
- "old durable",
- "late committed before lease",
- ]
+ assert [m["content"] for m in compressed_arg][0] == "old durable"
+ assert [m["content"] for m in compressed_arg][-1] == "late committed before lease"
+ assert len(compressed_arg) == 22
+ # The late assistant reply the stub fold drops must stay live in the
+ # committed child (#118900), not archived away with the folded middle.
+ live_contents = [m["content"] for m in db.get_messages_as_conversation(agent.session_id)]
+ assert "late committed before lease" in live_contents
# Must not echo the stale snapshot — compression proceeded on the
# adopted durable transcript (rotation publishes a child session).
assert returned is not stale_snapshot
diff --git a/tests/agent/test_compression_last_assistant_anchor.py b/tests/agent/test_compression_last_assistant_anchor.py
new file mode 100644
index 00000000000..2a89e47b32f
--- /dev/null
+++ b/tests/agent/test_compression_last_assistant_anchor.py
@@ -0,0 +1,210 @@
+"""Compaction must not deactivate the just-delivered assistant reply (#118900).
+
+Measured cause (Desktop macOS client, Hermes 0.21.4): a reply that had just
+finished streaming was folded into the compaction summary by engine-driven
+preflight maintenance and its row archived (active=0). The Desktop renders the
+active set, so the reply vanished from the surface on next render while its
+content stayed on disk.
+
+The built-in compressor keeps the latest visible reply in the tail
+(``_ensure_last_assistant_message_in_tail``), but plugin engines (e.g. LCM)
+implement their own ``compress()`` without that guard — and nothing enforces
+the invariant at the durable commit layer. ``_commit_compaction`` is the one
+choke point every engine and every path (threshold preflight, engine
+maintenance, manual /compress; in-place and rotation) routes through, so the
+guard lives here, mirroring ``_ensure_compressed_has_user_turn``.
+"""
+
+from agent.conversation_compression import (
+ _ensure_compressed_keeps_last_assistant_reply,
+)
+
+REPLY = "x" * 200 + " just-delivered verdict report the user is still reading."
+
+SUMMARY = "[Recent Summary (d0, node 490)]\n\nEarlier turns summarized."
+
+
+def _transcript(*, with_follower=True):
+ original = [
+ {"role": "user", "content": "Audit the auth module."},
+ {"role": "assistant", "content": "Short ack."},
+ {"role": "user", "content": "Go deeper, full report."},
+ {"role": "assistant", "content": REPLY, "finish_reason": "stop"},
+ ]
+ if with_follower:
+ original.append({"role": "user", "content": "Thanks, one more question."})
+ return original
+
+
+def test_s1_dropped_reply_reinserted_before_surviving_follower():
+ """S1 (the measured bug): engine folds the just-delivered long reply into
+ the summary; the next-turn user message survives. The reply must come back
+ ahead of that follower, not appended after it."""
+ original = _transcript(with_follower=True)
+ compressed = [
+ {"role": "user", "content": SUMMARY},
+ {"role": "user", "content": "Thanks, one more question."},
+ ]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "reinserted"
+ kept = [m for m in compressed if m.get("role") == "assistant" and m.get("content") == REPLY]
+ assert len(kept) == 1
+ follower = next(m for m in compressed if m.get("content") == "Thanks, one more question.")
+ assert compressed.index(kept[0]) < compressed.index(follower)
+ roles = [m.get("role") for m in compressed]
+ assert not any(a == b == "assistant" for a, b in zip(roles, roles[1:]))
+
+
+def test_s2_reply_already_kept_is_noop():
+ """S2: engine (built-in path) kept the reply in the tail — transcript must
+ not be touched."""
+ original = _transcript(with_follower=True)
+ compressed = [
+ {"role": "user", "content": SUMMARY},
+ {"role": "assistant", "content": REPLY, "finish_reason": "stop"},
+ {"role": "user", "content": "Thanks, one more question."},
+ ]
+ before = [dict(m) for m in compressed]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "already_present"
+ assert compressed == before
+
+
+def test_s3_trailing_reply_without_follower_appends_at_end():
+ """S3: compression ran before the next user turn; the reply is the last
+ row. It must be appended back at the end."""
+ original = _transcript(with_follower=False)
+ compressed = [{"role": "user", "content": SUMMARY}]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "reinserted"
+ assert compressed[-1].get("role") == "assistant"
+ assert compressed[-1].get("content") == REPLY
+
+
+def test_s4_empty_reasoning_only_reply_not_reinserted():
+ """S4: the #118755/#118738 family (text stranded in reasoning, empty
+ content) is a different bug with its own fix — this guard stays out."""
+ original = [
+ {"role": "user", "content": "Think hard."},
+ {"role": "assistant", "content": "", "reasoning": "long chain of thought"},
+ ]
+ compressed = [{"role": "user", "content": SUMMARY}]
+ before = [dict(m) for m in compressed]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "no_reply"
+ assert compressed == before
+
+
+def test_s5_tool_call_assistant_not_reinserted():
+ """S5: an assistant row carrying tool_calls must keep its atomic tool
+ group — reinserting it alone would corrupt pairing."""
+ original = [
+ {"role": "user", "content": "Run it."},
+ {
+ "role": "assistant",
+ "content": "Working.",
+ "tool_calls": [{"id": "call-1", "function": {"name": "terminal", "arguments": "{}"}}],
+ },
+ ]
+ compressed = [{"role": "user", "content": SUMMARY}]
+ before = [dict(m) for m in compressed]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "no_reply"
+ assert compressed == before
+
+
+def test_s6_summary_rows_never_count_as_the_reply():
+ """S6: a compaction handoff must not satisfy the presence check — the live
+ reply text must survive verbatim, not merely inside a summary."""
+ original = _transcript(with_follower=False)
+ compressed = [{"role": "user", "content": SUMMARY + "\n\n" + REPLY}]
+
+ outcome = _ensure_compressed_keeps_last_assistant_reply(original, compressed)
+
+ assert outcome == "reinserted"
+ assert sum(1 for m in compressed if m.get("role") == "assistant" and m.get("content") == REPLY) == 1
+
+
+class TestEngineDropsReplyEndToEnd:
+ """Full ``_compress_context`` with a stub engine that mimics the measured
+ LCM fold (long just-delivered reply summarized away, next-turn user row
+ kept): the reply row must stay ACTIVE in state.db after commit, while
+ genuinely old rows are still archived (compression itself keeps working)."""
+
+ def _agent(self, db, session_id):
+ import os
+ from unittest.mock import MagicMock, patch
+
+ from agent.conversation_compression import CompressionCommitFence # noqa: F401 (re-export check)
+ with patch.dict(os.environ, {"OPENROUTER_API_KEY": "test-key"}):
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ api_key="test-key",
+ base_url="https://openrouter.ai/api/v1",
+ model="test/model",
+ platform="telegram",
+ quiet_mode=True,
+ session_db=db,
+ session_id=session_id,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ engine = MagicMock()
+ # LCM-shaped fold: summary + next-turn tail only; the long reply gone.
+ engine.compress.return_value = [
+ {"role": "user", "content": SUMMARY},
+ {"role": "user", "content": "Thanks, one more question."},
+ ]
+ engine.compression_count = 1
+ engine.last_prompt_tokens = 0
+ engine.last_completion_tokens = 0
+ engine._last_summary_error = None
+ engine._last_compress_aborted = False
+ engine._last_summary_auth_failure = False
+ engine._last_aux_model_failure_model = None
+ engine._last_aux_model_failure_error = None
+ agent.context_compressor = engine
+ return agent
+
+ def test_reply_row_stays_active_after_commit(self, tmp_path):
+ from agent.conversation_compression import CompressionCommitFence
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "E2E_118900_REPLY"
+ db.create_session(session_id, source="cli")
+ for role, content in [
+ ("user", "Audit the auth module."),
+ ("assistant", "Short ack."),
+ ("user", "Go deeper, full report."),
+ ("assistant", REPLY),
+ ]:
+ db.append_message(session_id, role, content)
+
+ messages = [*db.get_messages_as_conversation(session_id),
+ {"role": "user", "content": "Thanks, one more question."}]
+ agent = self._agent(db, session_id)
+ agent._persist_user_message_idx = len(messages) - 1
+
+ agent._compress_context(
+ messages, "sys", approx_tokens=120_000,
+ commit_fence=CompressionCommitFence(),
+ )
+
+ live = [m.get("content") for m in db.get_messages_as_conversation(session_id)]
+ assert REPLY in live, "just-delivered reply left the active set after compaction"
+ assert "Thanks, one more question." in live
+ # Compression still folds: the superseded early rows are archived, not live.
+ assert "Short ack." not in live
+ assert "Go deeper, full report." not in live
diff --git a/tests/agent/test_compression_persistence.py b/tests/agent/test_compression_persistence.py
index 2abdc07ad84..43c94207300 100644
--- a/tests/agent/test_compression_persistence.py
+++ b/tests/agent/test_compression_persistence.py
@@ -211,9 +211,14 @@ class TestFlushAfterCompression:
awaiting_real_usage_after_compression = False
def compress(self, _messages, **_kwargs):
+ # Conforming-engine shape (#118900): the retained tail row is
+ # the transcript's own last reply, kept verbatim — the commit
+ # guard reinserts a dropped last reply, so inventing a new
+ # tail row here would (correctly) come back with the original
+ # alongside it.
return [
{"role": "user", "content": "[summary] earlier state"},
- {"role": "assistant", "content": "retained tail"},
+ {"role": "assistant", "content": "old answer"},
]
class AbortCompressor:
@@ -269,7 +274,7 @@ class TestFlushAfterCompression:
agent.session_id
)] == [
"[summary] earlier state",
- "retained tail",
+ "old answer",
"new request",
"new answer",
]
diff --git a/tests/agent/test_compression_rotation_state.py b/tests/agent/test_compression_rotation_state.py
index 747eefd677a..a5a7f3f38a2 100644
--- a/tests/agent/test_compression_rotation_state.py
+++ b/tests/agent/test_compression_rotation_state.py
@@ -221,6 +221,12 @@ class TestRotationChildFlushDedup:
db.create_session(parent, source="cli")
db.append_message(parent, "user", "persisted question")
db.append_message(parent, "assistant", "persisted answer")
+ # Bulk middle so the stub fold genuinely shrinks: the commit guard
+ # keeps a dropped last reply live (#118900), and without real middle
+ # to reclaim the no-growth guard correctly refuses the attempt.
+ for i in range(10):
+ db.append_message(parent, "user", f"bulk question {i} " + "x" * 60)
+ db.append_message(parent, "assistant", f"bulk answer {i} " + "y" * 60)
loaded = db.get_messages_as_conversation(parent)
messages = [*loaded, {"role": "user", "content": "live question"}]
@@ -1297,11 +1303,21 @@ class TestTodoSnapshotMergedNotDuplicated:
"image_url": {"url": "https://example.com/context.png"},
},
]
- agent.context_compressor.compress.return_value = [
- {"role": "user", "content": "[CONTEXT COMPACTION] summary"},
- {"role": "assistant", "content": "ok"},
- {"role": "user", "content": list(original_parts)},
- ]
+ agent.context_compressor.compress.return_value = None
+
+ def _keep_last_reply(messages, **_kwargs):
+ # Conforming-engine shape (#118900): the retained tail assistant
+ # row is the transcript's own last reply, kept verbatim — the
+ # commit guard reinserts a dropped last reply, so a stub that
+ # invents a new tail row would (correctly) come back with the
+ # original alongside it.
+ return [
+ {"role": "user", "content": "[CONTEXT COMPACTION] summary"},
+ {"role": "assistant", "content": messages[-1]["content"]},
+ {"role": "user", "content": list(original_parts)},
+ ]
+
+ agent.context_compressor.compress.side_effect = _keep_last_reply
agent._todo_store._todos = [
{"id": "t1", "content": "inspect image", "status": "in_progress"}
]