Skip to content

The agent that grows with you

fix(gateway): the authority's message.complete carries the turn's persisted_turn receipt

Teknium3b46bc12fd87
diff --git a/agent/persisted_turn_receipt.py b/agent/persisted_turn_receipt.py
new file mode 100644
index 00000000000..34716afcd9c
--- /dev/null
+++ b/agent/persisted_turn_receipt.py
@@ -0,0 +1,58 @@
+"""``message.complete.persisted_turn``: the committed row addresses of the agent's current turn.
+
+Shared by every host that publishes a turn's completion (the TUI gateway's in-process turn and
+the session authority's TurnRunner turn), so a client sees one receipt contract whichever host
+ran the turn. Clients key on it to bind a streamed reply to its stored row (``SessionMessage.row_id``)
+instead of comparing words.
+"""
+from __future__ import annotations
+
+from typing import Any, Callable
+
+from agent.context_compressor import _DB_PERSISTED_MARKER
+
+
+def committed_row_id(message: Any) -> int | None:
+ row_id = message.get("_row_id") if isinstance(message, dict) else None
+ return row_id if message.get(_DB_PERSISTED_MARKER) and type(row_id) is int and row_id > 0 else None
+
+
+def persisted_turn_receipt(
+ messages: Any, start: Any, history: list, raw: Any, status: str, *,
+ compression_unchanged: bool, prefix_row_matches: Callable[[Any, Any], bool],
+) -> dict | None:
+ """Report committed row addresses, never a text/timestamp search for a matching turn.
+
+ ``start`` is the agent's persistence cursor (``_persist_user_message_idx``), re-anchored during
+ compaction. A partial receipt can address its surviving rows, but cannot retire a client's
+ entire streamed turn. Full coverage additionally requires the unchanged pre-turn prefix
+ (``prefix_row_matches(history_row, turn_row)`` for every row before ``start``), no compaction
+ and no redirected user boundary.
+ """
+ if (not isinstance(messages, list) or type(start) is not int or not 0 <= start < len(messages)
+ or not isinstance(messages[start], dict) or messages[start].get("role") != "user"):
+ return None
+ tail = messages[start:]
+ anchor_id = committed_row_id(tail[0])
+ if any(before is tail[0] or (anchor_id is not None and anchor_id == committed_row_id(before))
+ for before in history):
+ return None # preflight returned the old transcript, not a new turn
+ row_ids = [rid for message in tail if (rid := committed_row_id(message)) is not None]
+ if not row_ids:
+ return None
+ receipt: dict = {"row_ids": row_ids, "complete": False}
+ if (user_row_id := committed_row_id(tail[0])) is not None:
+ receipt["user_row_id"] = user_row_id
+ last = tail[-1]
+ # Equality only verifies the structurally selected final row's body: it never selects an identity.
+ if (status == "complete" and last.get("role") == "assistant" and not last.get("tool_calls")
+ and last.get("content") == raw and (final_id := committed_row_id(last)) is not None):
+ receipt["final_assistant_row_id"] = final_id
+ prefix_unchanged = start == len(history) and all(
+ prefix_row_matches(before, after) for before, after in zip(history, messages[:start]))
+ receipt["complete"] = bool(
+ prefix_unchanged and compression_unchanged
+ and len(row_ids) == len(tail)
+ and sum(message.get("role") == "user" for message in tail) == 1
+ and "final_assistant_row_id" in receipt)
+ return receipt
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 8d4dc1cd337..02142b11f04 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -78,6 +78,24 @@ def _finite_viewer_turn() -> bool:
return finite_turn_required() is True
+def _persisted_turn(agent, agent_history, result, compressions) -> dict | None:
+ """``message.complete.persisted_turn`` for this turn, the receipt the TUI gateway's own turns
+ publish: clients bind the streamed reply to its stored row instead of comparing words. The
+ agent copies ``conversation_history`` into its message list, so an untouched pre-turn prefix
+ is the same dicts (transcript rows here carry no ``_row_id`` to compare)."""
+ from agent.persisted_turn_receipt import persisted_turn_receipt
+ if not isinstance(result, dict):
+ return None
+ status = ("interrupted" if result.get("interrupted")
+ else "error" if result.get("failed") or result.get("error") else "complete")
+ return persisted_turn_receipt(
+ result.get("messages"), getattr(agent, "_persist_user_message_idx", None), agent_history,
+ result.get("final_response"), status,
+ compression_unchanged=type(compressions) is int and compressions == getattr(
+ getattr(agent, "context_compressor", None), "compression_count", None),
+ prefix_row_matches=lambda before, after: before is after)
+
+
class _NoStreamConsumer(RuntimeError):
"""Raised by the delta callback when nothing consumed the text; ``_call_quietly`` turns it into
'not delivered' so the agent's partial-delivery accounting matches what the user saw."""
@@ -1151,7 +1169,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
self._wire_turn_agent_callbacks(agent, turn_route, reasoning_config, stream_delta_cb, interim_cb, want_interim)
agent_history, observed_group_context, history_media_paths = self._load_turn_history(agent, reused_cached_agent)
persist_msg, persist_ts = self._prepare_turn_message(agent_history)
+ compressions = getattr(getattr(agent, "context_compressor", None), "compression_count", None)
result = self._run_conversation_with_approval(agent, agent_history, observed_group_context, persist_msg, persist_ts)
+ persisted_turn = _persisted_turn(agent, agent_history, result, compressions)
self._finish_stream_consumer(result, agent_history, stream_consumer)
if _finite_viewer_turn() and getattr(agent, "_codex_session", None) is not None:
# The classic `chat -q` process exit bounded the codex app-server child; a finite turn
@@ -1194,6 +1214,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
"tools": ctx.tools_holder[0] or [],
"history_offset": history_offset, "compacted_in_place": compacted_in_place, "session_id": effective_session_id,
**usage,
+ **({"persisted_turn": persisted_turn} if persisted_turn else {}),
}
if not final_response:
final_response = _normalize_empty_agent_response(result, final_response or "", history_len=len(agent_history))
diff --git a/tests/gateway/test_authority_complete_persisted_turn.py b/tests/gateway/test_authority_complete_persisted_turn.py
new file mode 100644
index 00000000000..117bdf2a0ce
--- /dev/null
+++ b/tests/gateway/test_authority_complete_persisted_turn.py
@@ -0,0 +1,100 @@
+"""The session authority's message.complete carries the turn's committed row receipt and precedes
+the idle session.info.
+
+The TUI gateway's own turns publish ``persisted_turn`` (the stored row ids of the turn); the
+Desktop binds the streamed reply to its stored row with it, so a transcript read that races the
+completion never paints the reply twice. Turns the session authority runs through TurnRunner must
+publish the same receipt.
+"""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_authority import LiveSession, SessionAuthority
+from gateway.session_contract import Principal, SessionRef, Submission
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch
+from run_agent import AIAgent
+
+ACTOR = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')
+REF = SessionRef('owned', 's')
+
+
+def _flushing_agent(db, session_id):
+ """Agent shell owning the real per-turn flush that stamps ``_row_id`` on live dicts."""
+ agent = SimpleNamespace(
+ _session_db=db, _session_db_created=True, _persist_disabled=False, session_id=session_id,
+ _session_persist_lock=None, _flushed_db_message_ids=set(), _flushed_db_message_session_id=None,
+ _last_flushed_db_idx=0, _persist_user_message_idx=None, _persist_user_message_override=None,
+ _persist_user_message_timestamp=None, _pending_cli_user_message=None,
+ context_compressor=SimpleNamespace(compression_count=0))
+ agent._ensure_db_session = lambda: None
+ agent._flush_messages_to_session_db = AIAgent._flush_messages_to_session_db.__get__(agent, AIAgent)
+ agent._flush_messages_to_session_db_unlocked = AIAgent._flush_messages_to_session_db_unlocked.__get__(agent, AIAgent)
+ return agent
+
+
+def _tool_turn(db, session_id):
+ """One earlier turn already stored, then a tool turn the agent runs and flushes itself."""
+ db.append_message(session_id, 'user', 'earlier')
+ db.append_message(session_id, 'assistant', 'before')
+ history = [{'role': 'user', 'content': 'earlier'}, {'role': 'assistant', 'content': 'before'}]
+ agent = _flushing_agent(db, session_id)
+ call = {'id': 'c1', 'type': 'function', 'function': {'name': 'terminal', 'arguments': '{}'}}
+ messages = list(history) + [
+ {'role': 'user', 'content': 'b'},
+ {'role': 'assistant', 'content': 'checking', 'tool_calls': [call]},
+ {'role': 'tool', 'tool_call_id': 'c1', 'content': 'ok'},
+ {'role': 'assistant', 'content': 'finished while away'}]
+ agent._persist_user_message_idx = len(history)
+ agent._flush_messages_to_session_db(messages, history)
+ rows = db.get_messages_as_conversation(session_id, include_row_ids=True)
+ return agent, history, messages, [row['_row_id'] for row in rows[-4:]]
+
+
+def test_turn_runner_result_carries_the_committed_turn_receipt(tmp_path):
+ from gateway.run_turn_runner import _persisted_turn
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ db.create_session('s', source='test')
+ agent, history, messages, row_ids = _tool_turn(db, 's')
+ result = {'final_response': 'finished while away', 'messages': messages}
+
+ assert _persisted_turn(agent, history, result, 0) == {
+ 'row_ids': row_ids, 'complete': True, 'user_row_id': row_ids[0], 'final_assistant_row_id': row_ids[-1]}
+ # A compaction during the turn can drop streamed rows: the receipt no longer vouches for all of it.
+ assert _persisted_turn(agent, history, result, 1)['complete'] is False
+
+
+async def test_authority_completion_publishes_the_turn_receipt(tmp_path, monkeypatch):
+ from gateway import session_finite
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ db.create_session('s', source='test')
+ epoch = begin_runtime_epoch(db, instance_id='current')
+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False),
+ _adapter_for_source=lambda source: None)
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='current', db=db, epoch=epoch)
+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')
+ frames = []
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ receipt = {'row_ids': [3, 4, 5, 6], 'complete': True, 'user_row_id': 3, 'final_assistant_row_id': 6}
+
+ async def execute(authority, ref, row):
+ authority.pending_results[row['admission_id']] = {'result': {
+ 'final_response': 'finished while away', 'messages': [], 'persisted_turn': receipt}, 'usage': {}}
+ return 'finished while away'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+
+ with db:
+ await authority.submit(ACTOR, Submission(request_id='r', ref=REF, payload={'text': 'b'}, intent='queue'))
+ await asyncio.wait_for(authority.sessions['s'].task, 5)
+
+ [complete] = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']
+ assert complete['persisted_turn'] == receipt
+ # The idle snapshot follows the completion: a viewer never reads running=false for a turn whose
+ # terminal frame has not been published yet.
+ order = [(f['params']['type'], f['params']['payload'].get('running')) for f in frames
+ if f['params']['type'] in ('message.complete', 'session.info')]
+ assert order[-2:] == [('message.complete', None), ('session.info', False)]
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index d4a954ed3cc..6b206ea66ef 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -871,50 +871,17 @@ def _absorb_turn_result(
def _persisted_turn_receipt(st: _TurnRun, raw: Any, status: str) -> dict | None:
- """Report committed row addresses, never a text/timestamp search for a matching turn.
-
- The agent's persistence cursor is re-anchored during compaction. A partial receipt can
- address its surviving rows, but cannot retire a client's entire streamed turn. Full coverage
- additionally requires the unchanged pre-turn prefix and no redirected user boundary.
- """
- from agent.context_compressor import _DB_PERSISTED_MARKER
-
- messages = st.result.get("messages")
- start = getattr(st.agent, "_persist_user_message_idx", None)
- if (not isinstance(messages, list) or type(start) is not int or not 0 <= start < len(messages)
- or messages[start].get("role") != "user"):
- return None
-
- def committed_id(message):
- row_id = message.get("_row_id")
- return row_id if message.get(_DB_PERSISTED_MARKER) and type(row_id) is int and row_id > 0 else None
-
- tail = messages[start:]
- anchor_id = committed_id(tail[0])
- if any(before is tail[0] or (anchor_id is not None and anchor_id == committed_id(before))
- for before in st.history):
- return None # preflight returned the old transcript, not a new turn
- row_ids = [rid for message in tail if (rid := committed_id(message)) is not None]
- if not row_ids:
- return None
- receipt = {"row_ids": row_ids, "complete": False}
- if (user_row_id := committed_id(tail[0])) is not None:
- receipt["user_row_id"] = user_row_id
- last = tail[-1]
- # Equality only verifies the structurally selected final row's body: it never selects an identity.
- if (status == "complete" and last.get("role") == "assistant" and not last.get("tool_calls")
- and last.get("content") == raw and (final_id := committed_id(last)) is not None):
- receipt["final_assistant_row_id"] = final_id
- prefix_unchanged = start == len(st.history) and all(
- committed_id(before) is not None and committed_id(before) == committed_id(after)
- for before, after in zip(st.history, messages[:start]))
- receipt["complete"] = bool(
- prefix_unchanged and type(st.compression_count) is int
- and st.compression_count == getattr(getattr(st.agent, "context_compressor", None), "compression_count", None)
- and len(row_ids) == len(tail)
- and sum(message.get("role") == "user" for message in tail) == 1
- and "final_assistant_row_id" in receipt)
- return receipt
+ """Committed row addresses of this turn (``agent.persisted_turn_receipt``); the pre-turn
+ prefix is unchanged when every history row kept its committed row id."""
+ from agent.persisted_turn_receipt import committed_row_id, persisted_turn_receipt
+
+ return persisted_turn_receipt(
+ st.result.get("messages"), getattr(st.agent, "_persist_user_message_idx", None), st.history,
+ raw, status,
+ compression_unchanged=type(st.compression_count) is int and st.compression_count == getattr(
+ getattr(st.agent, "context_compressor", None), "compression_count", None),
+ prefix_row_matches=lambda before, after: (
+ committed_row_id(before) is not None and committed_row_id(before) == committed_row_id(after)))
def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None, cols: int):