Skip to content

The agent that grows with you

fix(desktop): preserve streamed assistant text and unify atomic persistence (#95514)

StanleyStetson24e54b55f509
diff --git a/agent/transcript_repair.py b/agent/transcript_repair.py
new file mode 100644
index 00000000000..545818f5d9a
--- /dev/null
+++ b/agent/transcript_repair.py
@@ -0,0 +1,112 @@
+"""Transcript repair and in-place row reconciliation helpers for SessionDB and run_agent.
+
+Extracted from hermes_state.py and run_agent.py to keep the godfiles narrow and bounded
+under the 2K invariant (#95514 / PR #95886). Provides focused helpers to:
+1. Resolve active assistant rows and watermark compaction clones in SQLite during batch appends.
+2. In-place update blank assistant rows or adopt concurrent non-blank winner content without overwrite.
+3. Synchronize in-memory message dicts with canonical committed content and row IDs after commit.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from typing import Any, Callable, Dict, List, Optional
+
+from agent.context_compressor import _DB_PERSISTED_MARKER
+
+
+def is_content_blank(content: Any) -> bool:
+ """True when decoded message content is None, whitespace-only, or has no visible text parts."""
+ if content is None:
+ return True
+ if isinstance(content, str):
+ return not content.strip()
+ if isinstance(content, list):
+ if not content:
+ return True
+ texts = [
+ p.get("text", "")
+ for p in content
+ if isinstance(p, dict) and p.get("type") == "text"
+ ]
+ return not "".join(texts).strip()
+ return False
+
+
+def resolve_and_repair_transcript_batch(
+ conn: sqlite3.Connection,
+ session_id: str,
+ messages: List[Dict[str, Any]],
+ encode_content_fn: Callable[[Any], Any],
+ decode_content_fn: Callable[[Any], Any],
+) -> List[Dict[str, Any]]:
+ """Partition a message batch within an active write transaction.
+
+ For assistant messages carrying an existing integer `_row_id`:
+ - Checks for an active target row or watermark compaction clone in SQLite.
+ - If blank, updates the row in-place with new content.
+ - If already non-blank (concurrent winner), adopts canonical content without overwrite.
+ - Returns the list of messages that must be inserted as fresh rows.
+ """
+ inserted_rows: List[Dict[str, Any]] = []
+ for msg in messages:
+ role = msg.get("role", "unknown") if isinstance(msg, dict) else "unknown"
+ existing_row_id = msg.get("_row_id") if isinstance(msg, dict) else None
+ repaired = False
+ if role == "assistant" and isinstance(existing_row_id, int):
+ row = conn.execute(
+ "SELECT id, role, active, timestamp, content FROM messages "
+ "WHERE id = ? AND session_id = ?",
+ (existing_row_id, session_id),
+ ).fetchone()
+ target_row = None
+ if row is not None and row["role"] == "assistant":
+ if int(row["active"] or 0) == 1:
+ target_row = row
+ else:
+ # Watermark compaction soft-archived the concurrent tail
+ # and cloned it. Find the active clone.
+ clone = conn.execute(
+ "SELECT id, role, active, timestamp, content FROM messages "
+ "WHERE session_id = ? AND active = 1 AND role = 'assistant' "
+ "AND timestamp IS ? AND id != ? "
+ "ORDER BY id DESC LIMIT 1",
+ (session_id, row["timestamp"], row["id"]),
+ ).fetchone()
+ if clone is not None:
+ target_row = clone
+ if target_row is not None:
+ target_id = int(target_row["id"])
+ raw_content = target_row["content"]
+ decoded = decode_content_fn(raw_content)
+ if is_content_blank(decoded):
+ encoded = encode_content_fn(msg.get("content"))
+ conn.execute(
+ "UPDATE messages SET content = ? "
+ "WHERE id = ? AND session_id = ? AND active = 1",
+ (encoded, target_id, session_id),
+ )
+ if isinstance(msg, dict):
+ msg["_row_id"] = target_id
+ else:
+ # Concurrent winner: adopt canonical content without overwrite
+ if isinstance(msg, dict):
+ msg["_row_id"] = target_id
+ msg["_canonical_content"] = decoded
+ repaired = True
+ if not repaired:
+ inserted_rows.append(msg)
+ return inserted_rows
+
+
+def sync_flushed_message_markers(
+ batch_msgs: List[Dict[str, Any]],
+ batch_rows: List[Dict[str, Any]],
+) -> None:
+ """Stamp _DB_PERSISTED_MARKER and sync canonical row ID / content onto live dicts after commit."""
+ for written, row in zip(batch_msgs, batch_rows):
+ written[_DB_PERSISTED_MARKER] = True
+ if isinstance(row.get("_row_id"), int):
+ written["_row_id"] = row["_row_id"]
+ if "_canonical_content" in row:
+ written["content"] = row["_canonical_content"]
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index 8b1c8e64e2a..bc279c767a5 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -32,20 +32,28 @@ from agent.message_metadata import append_message, stamp_message_timestamp
from agent.message_sanitization import _sanitize_surrogates
-def _is_pure_tool_call_tail(msg: dict) -> bool:
- """An assistant row with ``tool_calls`` but no visible text content of its own.
-
- Such a row satisfies the role check (``tail role == "assistant"``) while
- carrying none of the delivered answer — see the #43849/#44100 invariant
- block in :func:`finalize_turn`. Uses :func:`flatten_message_text` so that
- multimodal (list-type) content is evaluated by its text parts, not just
- its type.
- """
- if not msg.get("tool_calls"):
+def _assistant_row_missing_visible_text(msg: dict) -> bool:
+ """True when an assistant row has no visible text (blank final or tool-only)."""
+ if not isinstance(msg, dict) or msg.get("role") != "assistant":
return False
return not flatten_message_text(msg.get("content")).strip()
+def _is_pure_tool_call_tail(msg: dict) -> bool:
+ """Assistant row with ``tool_calls`` but no visible text of its own."""
+ if not isinstance(msg, dict) or not msg.get("tool_calls"):
+ return False
+ return _assistant_row_missing_visible_text(msg)
+
+
+def _fill_assistant_tail_content(agent, tail: dict, final_response) -> None:
+ """Write delivered text onto an already-persisted blank assistant row."""
+ tail["content"] = final_response
+ stamp_message_timestamp(tail)
+ tail.pop(_DB_PERSISTED_MARKER, None)
+ agent._db_flush_scan_prefix = None
+
+
# Verification continuation scaffolding flags: verify-on-stop / pre_verify
# inject a synthetic user nudge to keep the agent going one more turn.
# These nudges must be stripped from returned/live history to avoid
@@ -305,6 +313,21 @@ def finalize_turn(
# state.db. (#65919 §7)
_drop_verification_continuation_scaffolding(messages)
+ # #95514: an empty terminal completion is not authoritative when the
+ # stream already delivered text. Recover before persist so a blank
+ # assistant tail is filled instead of frozen as content=''.
+ _recovered_from_stream = False
+ if not interrupted and not failed:
+ _streamed = getattr(agent, "_current_streamed_assistant_text", "") or ""
+ if isinstance(_streamed, str):
+ _streamed = _streamed.strip()
+ else:
+ _streamed = ""
+ _final_visible = flatten_message_text(final_response).strip() if final_response else ""
+ if not _final_visible and _streamed:
+ final_response = _streamed
+ _recovered_from_stream = True
+
# When the turn was interrupted and the last message is a tool
# result, append a synthetic assistant message to close the
# tool-call sequence. Without this, the session persists a
@@ -351,40 +374,23 @@ def finalize_turn(
messages,
{"role": "assistant", "content": final_response},
)
- elif isinstance(_tail, dict) and _tail.get("content") != final_response and _is_pure_tool_call_tail(_tail):
- # The tail IS an assistant row, but a *pure tool-call turn*:
- # tool_calls with no text of its own. The role check alone
- # leaves the #43849/#44100 invariant unmet — the user saw a
- # response that never reached the transcript, and the next turn
- # replays the user backlog and re-answers it (the very symptom
- # this block was added for). Fill that row's empty content
- # instead of appending, so the durable turn ends with the answer
- # without disturbing the tool-call structure or creating an
- # assistant→assistant pair.
- #
- # The ``content != final_response`` guard prevents filling when
- # the tail already carries the final response text (verification
- # candidate collapse — the provisional answer was persisted and
- # reused as the terminal response, #65919 §7).
- _tail["content"] = final_response
- # The normal assistant builder already stamps this row. Cover
- # legacy/exceptional pure-tool tails before they become a
- # delivered final response.
- stamp_message_timestamp(_tail)
- # The row may have already been flushed to SQLite by the
- # incremental tool-call persist (conversation_loop.py:4990),
- # which stamps ``_DB_PERSISTED_MARKER`` so subsequent flushes
- # skip it. Pop the marker so the next ``_persist_session``
- # re-writes the filled content to the durable store —
- # otherwise ``/resume`` reloads ``content=""`` and the bug
- # resurfaces cross-session.
- _tail.pop(_DB_PERSISTED_MARKER, None)
- # The bounded flush-scan cursor (run_agent.py) skips the
- # identity-matched prefix of its previous snapshot on the
- # assumption that no live dict loses the marker in place —
- # this pop is the one place that does. Invalidate it so the
- # filled row is re-examined instead of skipped.
- agent._db_flush_scan_prefix = None
+ elif (
+ isinstance(_tail, dict)
+ and _tail.get("content") != final_response
+ and (
+ _is_pure_tool_call_tail(_tail)
+ or (
+ _recovered_from_stream
+ and _assistant_row_missing_visible_text(_tail)
+ )
+ )
+ ):
+ # The tail IS an assistant row, but a *pure tool-call turn* or
+ # a blank assistant tail whose content was recovered from the
+ # stream buffer (#95514). Fill that row's content instead of
+ # appending, so the durable turn ends with the answer without
+ # creating an assistant→assistant pair.
+ _fill_assistant_tail_content(agent, _tail, final_response)
# The model has completed its request, so replace API-local
# voice/model/skill guidance with the clean user input before writing the
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index 36cec7c71d1..98a38b8cc26 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
@@ -725,15 +725,25 @@ export function useMessageStream({
const hasInlineError = nextMessages.some(m => m.role === 'assistant' && m.error && !m.hidden)
const lastVisible = [...nextMessages].reverse().find(m => !m.hidden)
const unresolvedUserTail = lastVisible?.role === 'user'
+ const sameTurnAssistant = streamId
+ ? nextMessages.find(m => m.id === streamId)
+ : [...nextMessages].reverse().find(m => m.role === 'assistant' && !m.hidden)
+ const localVisibleText = sameTurnAssistant ? chatMessageText(sameTurnAssistant).trim() : ''
// Having streamed the reply normally means this window owns the whole
// turn and re-reading stored history would be wasted work. That only
// holds for a turn it STARTED: an adopted one (resumed onto a session
// already running elsewhere) arrives reply-first, with no prompt row,
// so it has to hydrate or the user's own message never shows up.
+ // Adopted turns still hydrate so a resume-onto-running session can
+ // pick up the user's prompt row — unless this window already has
+ // visible assistant text and the terminal frame is empty. In that
+ // case hydrate would replace the live bubble with a stored empty
+ // row (#95514; adoptedRunningTurn must not short-circuit).
shouldHydrate =
!completionError &&
!hasInlineError &&
!unresolvedUserTail &&
+ !(localVisibleText && !finalText) &&
(state.adoptedRunningTurn || !state.sawAssistantPayload || !finalText)
return {
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
index bbc760a677f..3e0b6f24f34 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/session-info-side-effects.test.tsx
@@ -264,6 +264,88 @@ describe('session.info settles a turn that produced no assistant payload', () =>
})
})
+describe('empty message.complete after streamed text (#95514)', () => {
+ it('keeps streamed text and does not hydrate over it', () => {
+ mountStream()
+
+ act(() => stream.handleEvent({ payload: {}, session_id: ACTIVE_SID, type: 'message.start' }))
+ act(() =>
+ stream.handleEvent({
+ payload: { text: 'Already rendered answer.' },
+ session_id: ACTIVE_SID,
+ type: 'message.delta'
+ })
+ )
+ act(() => stream.handleEvent({ payload: { text: '' }, session_id: ACTIVE_SID, type: 'message.complete' }))
+
+ const assistant = stream.state(ACTIVE_SID).messages.find(message => message.role === 'assistant')
+ expect(assistant?.parts.filter(part => part.type === 'text').map(part => part.text)).toEqual([
+ 'Already rendered answer.'
+ ])
+ expect(hydrateFromStoredSession).not.toHaveBeenCalled()
+ })
+
+ it('does not hydrate over interim-sealed text when streamId is already cleared', () => {
+ mountStream()
+
+ act(() => stream.handleEvent({ payload: {}, session_id: ACTIVE_SID, type: 'message.start' }))
+ act(() =>
+ stream.handleEvent({
+ payload: { text: 'Let me check the files.' },
+ session_id: ACTIVE_SID,
+ type: 'message.delta'
+ })
+ )
+ act(() =>
+ stream.handleEvent({
+ payload: { already_streamed: true, text: 'Let me check the files.' },
+ session_id: ACTIVE_SID,
+ type: 'message.interim'
+ })
+ )
+ act(() => stream.handleEvent({ payload: { text: '' }, session_id: ACTIVE_SID, type: 'message.complete' }))
+
+ const assistant = stream.state(ACTIVE_SID).messages.find(message => message.role === 'assistant')
+ expect(assistant?.parts.filter(part => part.type === 'text').map(part => part.text)).toEqual([
+ 'Let me check the files.'
+ ])
+ expect(hydrateFromStoredSession).not.toHaveBeenCalled()
+ })
+
+ it('does not hydrate an adopted turn over streamed text on empty complete', () => {
+ mountStream()
+ act(() => {
+ const current = stream.states.get(ACTIVE_SID) ?? createClientSessionState()
+ stream.states.set(ACTIVE_SID, { ...current, adoptedRunningTurn: true })
+ })
+
+ act(() => stream.handleEvent({ payload: {}, session_id: ACTIVE_SID, type: 'message.start' }))
+ act(() =>
+ stream.handleEvent({
+ payload: { text: 'Already rendered answer.' },
+ session_id: ACTIVE_SID,
+ type: 'message.delta'
+ })
+ )
+ act(() => stream.handleEvent({ payload: { text: '' }, session_id: ACTIVE_SID, type: 'message.complete' }))
+
+ const assistant = stream.state(ACTIVE_SID).messages.find(message => message.role === 'assistant')
+ expect(assistant?.parts.filter(part => part.type === 'text').map(part => part.text)).toEqual([
+ 'Already rendered answer.'
+ ])
+ expect(hydrateFromStoredSession).not.toHaveBeenCalled()
+ })
+
+ it('still hydrates an empty complete when this turn streamed no text', () => {
+ mountStream()
+
+ act(() => stream.handleEvent({ payload: {}, session_id: ACTIVE_SID, type: 'message.start' }))
+ act(() => stream.handleEvent({ payload: { text: '' }, session_id: ACTIVE_SID, type: 'message.complete' }))
+
+ expect(hydrateFromStoredSession).toHaveBeenCalled()
+ })
+})
+
describe('message.complete sidebar refresh coalescing', () => {
it('collapses near-simultaneous completions into one refresh', async () => {
mountStream()
diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.ts
index 65d8182ee13..087247ff125 100644
--- a/apps/desktop/src/lib/chat-messages.test.ts
+++ b/apps/desktop/src/lib/chat-messages.test.ts
@@ -1248,14 +1248,24 @@ describe('mergeFinalAssistantText', () => {
expect(result.filter(p => p.type === 'text')).toHaveLength(1)
})
- it('handles empty final text', () => {
+ it('does not erase streamed text when the final completion is empty (#95514)', () => {
const parts = [{ type: 'text' as const, text: 'streamed' }, reasoningPart('some reasoning')]
const result = mergeFinalAssistantText(parts, '')
- expect(result.filter(p => p.type === 'text')).toHaveLength(0)
+ expect(result.filter(p => p.type === 'text')).toHaveLength(1)
+ expect(result.filter(p => p.type === 'text')[0]).toMatchObject({ text: 'streamed' })
expect(result.filter(p => p.type === 'reasoning')).toHaveLength(1)
})
+
+ it('treats whitespace-only final text as non-authoritative (#95514)', () => {
+ const parts = [{ type: 'text' as const, text: 'already on screen' }]
+
+ const result = mergeFinalAssistantText(parts, ' \n\t')
+
+ expect(result.filter(p => p.type === 'text')).toHaveLength(1)
+ expect(result.filter(p => p.type === 'text')[0]).toMatchObject({ text: 'already on screen' })
+ })
})
describe('collectUnspokenTurnSpeech', () => {
diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.ts
index 158f85779c7..30fd5ab5b8e 100644
--- a/apps/desktop/src/lib/chat-messages/parts.ts
+++ b/apps/desktop/src/lib/chat-messages/parts.ts
@@ -155,6 +155,12 @@ export function mergeFinalAssistantText(
finalText: string,
fallbackTimestamp?: number
): ChatMessagePart[] {
+ // Empty / whitespace-only completion is not authoritative — keep streamed
+ // text, reasoning, and tool parts (#95514).
+ if (!finalText.trim()) {
+ return parts
+ }
+
const dedupeReference = normalizeWs(finalText)
const streamedText = normalizeWs(
diff --git a/hermes_state.py b/hermes_state.py
index 3abc45c3bd4..715cbe7a238 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -11261,17 +11261,30 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
turn_lease_holder=turn_lease_holder,
turn_lease_ttl_seconds=turn_lease_ttl_seconds,
)
- inserted, tool_calls_total = self._insert_message_rows(
- conn, session_id, messages
- )
- # One aggregated counter update for the whole batch.
+ from agent.transcript_repair import resolve_and_repair_transcript_batch
+
+ inserted_rows = resolve_and_repair_transcript_batch(
+ conn,
+ session_id,
+ messages,
+ encode_content_fn=self._encode_content,
+ decode_content_fn=self._decode_content,
+ )
+ inserted = 0
+ tool_calls_total = 0
+ if inserted_rows:
+ inserted, tool_calls_total = self._insert_message_rows(
+ conn, session_id, inserted_rows
+ )
+
+ # One aggregated counter update for the newly inserted rows.
if tool_calls_total > 0:
conn.execute(
"""UPDATE sessions SET message_count = message_count + ?,
tool_call_count = tool_call_count + ? WHERE id = ?""",
(inserted, tool_calls_total, session_id),
)
- else:
+ elif inserted > 0:
conn.execute(
"UPDATE sessions SET message_count = message_count + ? WHERE id = ?",
(inserted, session_id),
diff --git a/run_agent.py b/run_agent.py
index 4fc9b479cb8..f5d23fba3b4 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -2229,6 +2229,7 @@ class AIAgent:
while (
_scan_start < _limit
and messages[_scan_start] is _prev_prefix[_scan_start]
+ and bool(messages[_scan_start].get(_DB_PERSISTED_MARKER))
):
_scan_start += 1
@@ -2354,7 +2355,7 @@ class AIAgent:
]
elif isinstance(msg.get("tool_calls"), list):
tool_calls_data = msg["tool_calls"]
- _batch_rows.append({
+ _row = {
"role": role,
"content": content,
"tool_name": msg.get("tool_name"),
@@ -2395,7 +2396,10 @@ class AIAgent:
else msg.get("display_kind")
),
"display_metadata": msg.get("display_metadata"),
- })
+ }
+ if isinstance(msg.get("_row_id"), int):
+ _row["_row_id"] = msg["_row_id"]
+ _batch_rows.append(_row)
_batch_msgs.append(msg)
# One transaction for the whole turn's new rows (typically 3-8
# messages): one BEGIN IMMEDIATE / commit — and, off WAL, one
@@ -2419,8 +2423,9 @@ class AIAgent:
)
or 300.0,
)
- for _written in _batch_msgs:
- _written[_DB_PERSISTED_MARKER] = True
+ from agent.transcript_repair import sync_flushed_message_markers
+
+ sync_flushed_message_markers(_batch_msgs, _batch_rows)
# The intrinsic markers are now the sole source of truth. Reset the
# one-shot seed so no id() outlives this flush to alias a message
# allocated next turn at a recycled address.
diff --git a/tests/agent/test_turn_finalizer_final_response_persistence.py b/tests/agent/test_turn_finalizer_final_response_persistence.py
index 52106f07fe5..e674c85e3a6 100644
--- a/tests/agent/test_turn_finalizer_final_response_persistence.py
+++ b/tests/agent/test_turn_finalizer_final_response_persistence.py
@@ -271,3 +271,141 @@ def test_final_response_fill_invalidates_flush_scan_cursor():
)
assert agent._db_flush_scan_prefix is None
+
+
+def test_empty_final_response_recovers_stream_buffer_into_blank_assistant_row(
+ monkeypatch, tmp_path
+):
+ """#95514: empty terminal completion must not persist content='' over a live stream.
+
+ After a tool result the incremental flush can leave a blank assistant tail.
+ If finalize_turn then receives final_response='' while the stream buffer
+ still holds the delivered text, that blank row is the durable transcript —
+ Desktop reload shows nothing even though the user already saw the answer.
+ """
+ from hermes_state import SessionDB
+
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("sess-test", source="cli")
+ agent = FakeAgent()
+ agent._current_streamed_assistant_text = "Already streamed to the user."
+
+ def persist_to_sqlite(messages, _conversation_history):
+ db.replace_messages(agent.session_id, messages)
+ agent.persisted_messages = db.get_messages_as_conversation(agent.session_id)
+
+ agent._persist_session = persist_to_sqlite
+ messages = [
+ {"role": "user", "content": "summarize"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "t1", "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "t1", "name": "terminal", "content": "ok"},
+ {"role": "assistant", "content": "", "_db_persisted": True},
+ ]
+
+ result = finalize_turn(
+ agent,
+ final_response="",
+ api_call_count=2,
+ interrupted=False,
+ failed=False,
+ messages=messages,
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="summarize",
+ original_user_message="summarize",
+ _should_review_memory=False,
+ _turn_exit_reason="text_response(final)",
+ )
+
+ assert result["final_response"] == "Already streamed to the user."
+ assistants = [m for m in agent.persisted_messages if m.get("role") == "assistant"]
+ assert assistants[-1]["content"] == "Already streamed to the user."
+ assert assistants[0].get("tool_calls")
+ assert sum(1 for m in assistants) == 2
+
+ reopened = SessionDB(db_path=tmp_path / "state.db")
+ reloaded = reopened.get_messages_as_conversation("sess-test")
+ assert reloaded[-1]["role"] == "assistant"
+ assert reloaded[-1]["content"] == "Already streamed to the user."
+ assert sum(1 for m in reloaded if m.get("role") == "assistant") == 2
+
+
+def test_failed_turn_does_not_recover_stream_buffer_as_final_response(monkeypatch):
+ """A failed turn must not invent a successful answer from the stream buffer."""
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ agent = FakeAgent()
+ agent._current_streamed_assistant_text = "partial tokens"
+
+ result = finalize_turn(
+ agent,
+ final_response="",
+ api_call_count=1,
+ interrupted=False,
+ failed=True,
+ messages=[{"role": "user", "content": "q"}],
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="q",
+ original_user_message="q",
+ _should_review_memory=False,
+ _turn_exit_reason="error",
+ )
+
+ assert result["final_response"] in ("", None)
+ assert result["failed"] is True
+
+
+def test_delivery_only_reasoning_excerpt_does_not_fill_blank_assistant(monkeypatch):
+ """Labeled empty-terminal excerpt is delivery-only, not durable content.
+
+ ``empty_response_exhausted`` sets final_response to a labeled reasoning
+ excerpt while the transcript tail is a blank/sentinel assistant without
+ tool_calls. Filling that tail would persist the excerpt and break replay
+ (test_empty_terminal_reasoning_surface).
+ """
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ agent = FakeAgent()
+ excerpt = (
+ "⚠️ The model produced only internal reasoning and no final answer, "
+ "despite retries. Its last reasoning, which may contain the answer:\n\n"
+ "The answer is 42"
+ )
+ messages = [
+ {"role": "user", "content": "what is the answer?"},
+ {"role": "assistant", "content": ""},
+ ]
+
+ result = finalize_turn(
+ agent,
+ final_response=excerpt,
+ api_call_count=6,
+ interrupted=False,
+ failed=False,
+ messages=messages,
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="what is the answer?",
+ original_user_message="what is the answer?",
+ _should_review_memory=False,
+ _turn_exit_reason="empty_response_exhausted",
+ )
+
+ assert result["final_response"] == excerpt
+ assert not any(
+ m.get("role") == "assistant"
+ and "only internal reasoning" in (m.get("content") or "")
+ for m in result["messages"]
+ )
+
diff --git a/tests/run_agent/test_tool_call_incremental_persistence.py b/tests/run_agent/test_tool_call_incremental_persistence.py
index 20a2c2de9dc..24f7a4202a6 100644
--- a/tests/run_agent/test_tool_call_incremental_persistence.py
+++ b/tests/run_agent/test_tool_call_incremental_persistence.py
@@ -614,3 +614,288 @@ def test_execute_tool_calls_concurrent_flushes_each_tool_result_in_order():
# production flush call breaks one of these assertions.
assert flushed_tool_ids == ["c1", "c2"]
assert flush_lengths == [1, 2]
+
+
+def test_empty_final_response_updates_already_flushed_blank_assistant_row(tmp_path):
+ """#95514: popping _db_persisted must UPDATE the flushed row, not INSERT.
+
+ Incremental persist already wrote assistant(content=''). finalize_turn
+ recovers the stream buffer onto that live dict. Production flush is
+ append-only, so a re-insert would leave the empty row and add a second
+ assistant (assistant→assistant on reload).
+ """
+ from agent.turn_finalizer import finalize_turn
+
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-empty-final-flush"
+ _attach_real_session_db(agent, db_path, session_id)
+ agent._current_streamed_assistant_text = "Already streamed to the user."
+
+ messages = [
+ {"role": "user", "content": "summarize"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "t1", "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "t1", "name": "terminal", "content": "ok"},
+ {"role": "assistant", "content": ""},
+ ]
+ agent._flush_messages_to_session_db(messages)
+ pre = _durable_messages(db_path, session_id)
+ assert pre[-1]["role"] == "assistant"
+ assert (pre[-1].get("content") or "") == ""
+
+ finalize_turn(
+ agent,
+ final_response="",
+ api_call_count=2,
+ interrupted=False,
+ failed=False,
+ messages=messages,
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="summarize",
+ original_user_message="summarize",
+ _should_review_memory=False,
+ _turn_exit_reason="text_response(final)",
+ )
+
+ reloaded = _durable_messages(db_path, session_id)
+ assistants = [m for m in reloaded if m.get("role") == "assistant"]
+ assert assistants[-1]["content"] == "Already streamed to the user."
+ assert len(assistants) == 2
+ assert assistants[0].get("tool_calls")
+ assert sum(
+ 1 for m in assistants
+ if not (m.get("content") or "").strip() and not m.get("tool_calls")
+ ) == 0
+
+
+def test_flush_stale_row_id_from_other_session_still_inserts(tmp_path):
+ """Copied dicts that keep a parent _row_id must still INSERT in a child session."""
+ parent = _make_agent()
+ child = _make_agent()
+ db_path = tmp_path / "state.db"
+ _attach_real_session_db(parent, db_path, "sess-parent")
+ _attach_real_session_db(child, db_path, "sess-child")
+ parent_msgs = [
+ {"role": "user", "content": "p-user"},
+ {"role": "assistant", "content": "p-answer"},
+ ]
+ parent._flush_messages_to_session_db(parent_msgs)
+ copies = [{k: v for k, v in m.items() if k != "_db_persisted"} for m in parent_msgs]
+ copies.extend(
+ [
+ {"role": "user", "content": "c-user"},
+ {"role": "assistant", "content": "c-answer"},
+ ]
+ )
+ child._flush_messages_to_session_db(copies)
+ reloaded = _durable_messages(db_path, "sess-child")
+ assert [m.get("content") for m in reloaded] == [
+ "p-user",
+ "p-answer",
+ "c-user",
+ "c-answer",
+ ]
+
+
+def test_flush_stale_row_id_from_other_session_does_not_fill_child_blank(tmp_path):
+ """A parent `_row_id` must INSERT in the child, not steal a blank tail."""
+ parent = _make_agent()
+ child = _make_agent()
+ db_path = tmp_path / "state.db"
+ _attach_real_session_db(parent, db_path, "sess-parent")
+ _attach_real_session_db(child, db_path, "sess-child")
+ parent_msgs = [
+ {"role": "user", "content": "p-user"},
+ {"role": "assistant", "content": "p-answer"},
+ ]
+ parent._flush_messages_to_session_db(parent_msgs)
+ child_msgs = [
+ {"role": "user", "content": "c-keep"},
+ {"role": "assistant", "content": ""},
+ ]
+ child._flush_messages_to_session_db(child_msgs)
+ copies = [{k: v for k, v in m.items() if k != "_db_persisted"} for m in parent_msgs]
+ copies.extend(
+ [
+ {"role": "user", "content": "c-user"},
+ {"role": "assistant", "content": "c-answer"},
+ ]
+ )
+ child._flush_messages_to_session_db(copies)
+ reloaded = _durable_messages(db_path, "sess-child")
+ assert [m.get("content") for m in reloaded] == [
+ "c-keep",
+ "",
+ "p-user",
+ "p-answer",
+ "c-user",
+ "c-answer",
+ ]
+
+
+def test_flush_archived_same_session_row_id_fills_active_clone(tmp_path):
+ """Watermark compaction clones the tail; stale `_row_id` must not win.
+
+ ``archive_and_compact(..., watermark=...)`` archives the original
+ concurrent-tail row and inserts a fresh active clone with a new id.
+ The live dict still holds the archived id. A rewrite keyed only on
+ ``id + session_id`` updates the inactive row, stamps persistence, and
+ skips INSERT — reload then still sees the blank clone (#95514 P0).
+ """
+ from agent.turn_finalizer import finalize_turn
+
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-archived-row-id"
+ db = _attach_real_session_db(agent, db_path, session_id)
+ recovered = "Already streamed to the user."
+ agent._current_streamed_assistant_text = recovered
+ messages = [
+ {"role": "user", "content": "summarize"},
+ {"role": "assistant", "content": ""},
+ ]
+ agent._flush_messages_to_session_db(messages)
+ stale_id = messages[-1]["_row_id"]
+ user_id = messages[0]["_row_id"]
+ assert isinstance(stale_id, int)
+ assert stale_id > user_id
+
+ db.archive_and_compact(
+ session_id,
+ compacted_messages=[{"role": "user", "content": "prior turns summarized"}],
+ watermark=user_id,
+ )
+
+ finalize_turn(
+ agent,
+ final_response="",
+ api_call_count=1,
+ interrupted=False,
+ failed=False,
+ messages=messages,
+ conversation_history=[],
+ effective_task_id="task",
+ turn_id="turn",
+ user_message="summarize",
+ original_user_message="summarize",
+ _should_review_memory=False,
+ _turn_exit_reason="text_response(final)",
+ )
+
+ reloaded = _durable_messages(db_path, session_id)
+ active_assistants = [m for m in reloaded if m.get("role") == "assistant"]
+ assert active_assistants, "compaction clone should keep an active assistant"
+ assert any(
+ (m.get("content") or "").strip() == recovered for m in active_assistants
+ )
+ assert not any(
+ not (m.get("content") or "").strip() for m in active_assistants
+ )
+ inactive = db.get_messages(session_id, include_inactive=True)
+ archived = next(m for m in inactive if m.get("id") == stale_id)
+ assert archived.get("active") in (0, False)
+ assert messages[-1].get("_row_id") != stale_id
+
+
+def test_flush_atomic_mixed_repair_and_append_rollback_on_failure(tmp_path, monkeypatch):
+ """Mixed rewrite + append must be atomic: failure rolls back repair and stamps no markers.
+
+ If a turn contains both a blank assistant repair and a subsequent new message,
+ failure during the batch insert must roll back the assistant update and stamp
+ no in-memory markers.
+ """
+ from hermes_state import SessionDB
+
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-atomic-rollback"
+ db = _attach_real_session_db(agent, db_path, session_id)
+
+ messages = [
+ {"role": "user", "content": "summarize"},
+ {"role": "assistant", "content": ""},
+ ]
+ agent._flush_messages_to_session_db(messages)
+ orig_row_id = messages[-1]["_row_id"]
+ assert isinstance(orig_row_id, int)
+
+ # Now modify assistant message in memory and add a new message to the batch
+ messages[-1]["content"] = "Recovered stream answer"
+ messages[-1].pop("_db_persisted", None)
+ new_tool_msg = {"role": "tool", "tool_call_id": "t1", "name": "terminal", "content": "ok"}
+ messages.append(new_tool_msg)
+
+ # Force a failure inside the batch write transaction on the second message
+ orig_insert = SessionDB._insert_message_rows
+
+ def _failing_insert(self_db, conn, sid, msgs):
+ for msg in msgs:
+ if msg.get("role") == "tool":
+ raise RuntimeError("Simulated mid-batch persistence crash")
+ return orig_insert(self_db, conn, sid, msgs)
+
+ monkeypatch.setattr(SessionDB, "_insert_message_rows", _failing_insert)
+
+ success = agent._flush_messages_to_session_db(messages)
+ assert success is False or getattr(agent, "_incremental_persistence_failed", False) is True
+
+ # Check that in-memory markers were NOT stamped
+ assert messages[-1].get("_db_persisted") is not True
+ assert new_tool_msg.get("_db_persisted") is not True
+
+ # Check that the durable SQLite row was NOT updated (rolled back)
+ durable = _durable_messages(db_path, session_id)
+ assert len(durable) == 2
+ assert durable[-1]["role"] == "assistant"
+ assert (durable[-1].get("content") or "") == ""
+
+
+def test_flush_concurrent_nonblank_winner_adopts_canonical_content(tmp_path):
+ """A concurrent non-blank winner must be adopted without overwrite and synced to live dict."""
+ agent = _make_agent()
+ db_path = tmp_path / "state.db"
+ session_id = "sess-concurrent-winner"
+ db = _attach_real_session_db(agent, db_path, session_id)
+
+ messages = [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": ""},
+ ]
+ agent._flush_messages_to_session_db(messages)
+ row_id = messages[-1]["_row_id"]
+ assert isinstance(row_id, int)
+
+ # Concurrent writer updates the row in SQLite to non-blank canonical content
+ def _concurrent_write(conn):
+ conn.execute(
+ "UPDATE messages SET content = ? WHERE id = ?",
+ (db._encode_content("Canonical winner answer from sibling"), row_id),
+ )
+
+ db._execute_write(_concurrent_write)
+
+ # Live agent attempts to flush divergent content
+ messages[-1]["content"] = "Divergent live agent answer"
+ messages[-1].pop("_db_persisted", None)
+
+ success = agent._flush_messages_to_session_db(messages)
+ assert success is True
+
+ # SQLite must still have canonical winner content
+ durable = _durable_messages(db_path, session_id)
+ assert durable[-1]["content"] == "Canonical winner answer from sibling"
+
+ # Live dict must have adopted the canonical content and be marked persisted
+ assert messages[-1]["content"] == "Canonical winner answer from sibling"
+ assert messages[-1]["_db_persisted"] is True
+ assert messages[-1]["_row_id"] == row_id
+