The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): the turn receipt names every user row and the authority's submission
Teknium933adf2d9f38
diff --git a/agent/persisted_turn_receipt.py b/agent/persisted_turn_receipt.pyindex 34716afcd9c..7e4d9a8e385 100644--- a/agent/persisted_turn_receipt.py+++ b/agent/persisted_turn_receipt.py@@ -43,6 +43,13 @@ def persisted_turn_receipt(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+ # Every rendered user row of the turn in order (the prompt, then each steer/redirect row), so a+ # client binds its optimistic bubbles even when the turn holds more than one prompt row. Only a+ # fully committed list is published: a gap would shift every later pairing.+ users = [message for message in tail if message.get("role") == "user" and message.get("display_kind") != "hidden"]+ user_row_ids = [committed_row_id(message) for message in users]+ if users and None not in user_row_ids:+ receipt["user_row_ids"] = user_row_idslast = 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")diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex ba3e2d22b79..d1e4e063f9b 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4650,6 +4650,8 @@ export interface PersistedTurn {complete: booleanuser_row_id?: number | nullfinal_assistant_row_id?: number | null+ user_row_ids?: number[] | null+ submission_id?: string | null}/** ``server._status_update`` and the direct emitters (goal / loop / heartbeat / process). */export interface StatusUpdatePayload {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 92946d483d2..c965c7d1944 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -20411,6 +20411,33 @@],"default": null,"title": "Final Assistant Row Id"+ },+ "user_row_ids": {+ "anyOf": [+ {+ "items": {+ "type": "integer"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "User Row Ids"+ },+ "submission_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Submission Id"}},"required": [diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 47e6ba0c4d6..b3ba2a792b2 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -544,8 +544,11 @@ class SessionAuthority:complete['response_reused'] = True# The committed row addresses of the turn: a viewer binds the streamed reply to# its stored row, so a transcript read racing this frame never paints it twice.+ # ``submission_id`` names whose turn it is: the sending viewer binds its optimistic+ # prompt (``user-<submission_id>``), which the queued admission ack could not name.if isinstance(captured_result.get('persisted_turn'), dict):- complete['persisted_turn'] = captured_result['persisted_turn']+ complete['persisted_turn'] = {**captured_result['persisted_turn'],+ 'submission_id': row['request_id']}live.event_stream.publish(ref.session_id, complete)# The idle snapshot (running=false) follows the completion, as on every other# host: a viewer that read running=false first settled the reply as a turn whosediff --git a/tests/gateway/test_authority_complete_persisted_turn.py b/tests/gateway/test_authority_complete_persisted_turn.pyindex 117bdf2a0ce..6611dd5df6b 100644--- a/tests/gateway/test_authority_complete_persisted_turn.py+++ b/tests/gateway/test_authority_complete_persisted_turn.py@@ -61,11 +61,33 @@ def test_turn_runner_result_carries_the_committed_turn_receipt(tmp_path):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]}+ 'row_ids': row_ids, 'complete': True, 'user_row_id': row_ids[0], 'final_assistant_row_id': row_ids[-1],+ 'user_row_ids': [row_ids[0]]}# 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+def test_steered_turn_receipt_names_every_user_row_in_order(tmp_path):+ """A steer/redirect adds a second user row, so the turn is never `complete`; the receipt still+ names each committed user row so the client can bind every optimistic bubble it painted."""+ from gateway.run_turn_runner import _persisted_turn+ db = SessionDB(db_path=tmp_path / 'state.db')+ db.create_session('s', source='test')+ agent = _flushing_agent(db, 's')+ messages = [{'role': 'user', 'content': 'slow one'}, {'role': 'assistant', 'content': 'partial'},+ {'role': 'user', 'content': 'change course'}, {'role': 'assistant', 'content': 'steered reply'}]+ agent._persist_user_message_idx = 0+ agent._flush_messages_to_session_db(messages, [])+ row_ids = [row['_row_id'] for row in db.get_messages_as_conversation('s', include_row_ids=True)]+ receipt = _persisted_turn(agent, [], {'final_response': 'steered reply', 'messages': messages}, 0)++ assert receipt['complete'] is False+ assert receipt['user_row_ids'] == [row_ids[0], row_ids[2]]+ # An uncommitted steer row would shift every later pairing: publish no list at all.+ messages.insert(3, {'role': 'user', 'content': 'not flushed'})+ assert 'user_row_ids' not in _persisted_turn(agent, [], {'final_response': 'steered reply', 'messages': messages}, 0)++@pytest.mark.asyncioasync def test_authority_completion_publishes_the_turn_receipt(tmp_path, monkeypatch):from gateway import session_finite@@ -92,7 +114,9 @@ async def test_authority_completion_publishes_the_turn_receipt(tmp_path, monkeypawait 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 receipt names the client submission whose turn it is: the viewer that sent it binds its+ # optimistic prompt (`user-<submission_id>`) to the stored row, as main's submit ack does.+ assert complete['persisted_turn'] == {**receipt, 'submission_id': 'r'}# 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 framesdiff --git a/tests/tui_gateway/test_submit_time_user_row.py b/tests/tui_gateway/test_submit_time_user_row.pyindex ac55d3a0037..52f24664b55 100644--- a/tests/tui_gateway/test_submit_time_user_row.py+++ b/tests/tui_gateway/test_submit_time_user_row.py@@ -133,6 +133,7 @@ def test_completion_receipt_covers_only_committed_current_turn_rows(monkeypatch,"row_ids": [row["_row_id"] for row in rows[-2:]],"final_assistant_row_id": rows[-1]["_row_id"],"complete": True,+ "user_row_ids": [rows[-2]["_row_id"]],}# Compression can discard an already-streamed segment even while the old prefix survives.agent.context_compressor = SimpleNamespace(compression_count=1)@@ -143,7 +144,8 @@ def test_completion_receipt_covers_only_committed_current_turn_rows(monkeypatch,current[-1]["content"] = "not flushed"partial, _, _ = server._complete_turn_payload(session, st, None, 80)assert partial["persisted_turn"] == {- "user_row_id": rows[-2]["_row_id"], "row_ids": [rows[-2]["_row_id"]], "complete": False}+ "user_row_id": rows[-2]["_row_id"], "row_ids": [rows[-2]["_row_id"]], "complete": False,+ "user_row_ids": [rows[-2]["_row_id"]]}# No authoritative current-turn anchor: never infer from matching text or positions in old history.agent._persist_user_message_idx = Nonemissing, _, _ = server._complete_turn_payload(session, st, None, 80)diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex cd1f402fd56..32d18bb55ed 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -184,6 +184,11 @@ class PersistedTurn(Payload):complete: booluser_row_id: int | None = Nonefinal_assistant_row_id: int | None = None+ #: Every rendered user row of the turn in order (prompt, then steer/redirect rows); absent+ #: unless all of them committed. Binds optimistic bubbles a submit receipt could not name.+ user_row_ids: list[int] | None = None+ #: The client submission the turn ran (session authority only; its ack precedes the user row).+ submission_id: str | None = Noneclass MessageCompletePayload(Payload):