Skip to content

The agent that grows with you

fix(gateway): acknowledge persisted prompt and reply identities

brooklyn!36b4f7cc2d9e
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index dd59b883a0a..b078c3eb945 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2330,6 +2330,7 @@ export interface PromptSubmitParams {
export interface PromptSubmitResult {
status?: PromptSubmitStatus | null
voice_stopped?: boolean | null
+ user_row_id?: number | null
survivor_user_row_ids?: (number | null)[] | null
survivor_row_id_map?: Record<string, number | null> | null
turn_isolation?: boolean | null
@@ -4144,6 +4145,7 @@ export interface MessageCompletePayload {
recoverable?: boolean | null
error_surface?: ErrorSurface | null
partial?: boolean | null
+ persisted_turn?: PersistedTurn | null
}
/** ``prompt_turn._result_status``. */
export type TurnStatus = 'complete' | 'error' | 'interrupted'
@@ -4167,6 +4169,13 @@ export interface ErrorSurface {
resets_at?: number | null
[key: string]: unknown
}
+/** Committed SQLite row addresses for the agent's current-turn suffix. Missing ids are unproven, never negative acknowledgements. ``complete`` permits retiring the whole local turn only when the original turn boundary, every row and final body are still accounted for; compaction, redirects and partial writes conservatively leave it false. Row ids are scoped to the owning profile's store, as in ``SessionMessage.row_id``. */
+export interface PersistedTurn {
+ row_ids: number[]
+ complete: boolean
+ user_row_id?: number | null
+ final_assistant_row_id?: number | null
+}
/** ``server._status_update`` and the direct emitters (goal / loop / heartbeat / process). */
export interface StatusUpdatePayload {
kind: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index e1430078c72..09f8b6c353e 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -16328,6 +16328,17 @@
],
"default": null,
"title": "Partial"
+ },
+ "persisted_turn": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/PersistedTurn"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
}
},
"title": "MessageCompletePayload",
@@ -17922,6 +17933,53 @@
"title": "PendingApproval",
"type": "object"
},
+ "PersistedTurn": {
+ "additionalProperties": false,
+ "description": "Committed SQLite row addresses for the agent's current-turn suffix. Missing ids are\nunproven, never negative acknowledgements. ``complete`` permits retiring the whole local\nturn only when the original turn boundary, every row and final body are still accounted\nfor; compaction, redirects and partial writes conservatively leave it false. Row ids are\nscoped to the owning profile's store, as in ``SessionMessage.row_id``.",
+ "properties": {
+ "row_ids": {
+ "items": {
+ "type": "integer"
+ },
+ "title": "Row Ids",
+ "type": "array"
+ },
+ "complete": {
+ "title": "Complete",
+ "type": "boolean"
+ },
+ "user_row_id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "User Row Id"
+ },
+ "final_assistant_row_id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Final Assistant Row Id"
+ }
+ },
+ "required": [
+ "row_ids",
+ "complete"
+ ],
+ "title": "PersistedTurn",
+ "type": "object"
+ },
"PetCancelParams": {
"additionalProperties": false,
"properties": {
@@ -23858,6 +23916,18 @@
"default": null,
"title": "Voice Stopped"
},
+ "user_row_id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "User Row Id"
+ },
"survivor_user_row_ids": {
"anyOf": [
{
diff --git a/tests/tui_gateway/test_submit_time_user_row.py b/tests/tui_gateway/test_submit_time_user_row.py
index 8d8e41efdd3..40fd6e3e72b 100644
--- a/tests/tui_gateway/test_submit_time_user_row.py
+++ b/tests/tui_gateway/test_submit_time_user_row.py
@@ -50,6 +50,36 @@ def test_user_message_is_durable_at_submit_before_any_agent_turn(monkeypatch, tm
db.close()
+def test_submit_ack_binds_the_written_row_even_if_worker_consumes_staging(monkeypatch, tmp_path):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+
+ class InlineThread:
+ def __init__(self, target, **kwargs):
+ self.target = target
+
+ def start(self):
+ self.target()
+
+ monkeypatch.setattr(server.threading, "Thread", InlineThread)
+ monkeypatch.setattr(server, "_start_agent_build", lambda *args: None)
+ monkeypatch.setattr(server, "_restart_completed_failed_agent_build", lambda *args: False)
+ monkeypatch.setattr(server, "_run_after_agent_ready", lambda *args: session.pop("_submit_user_row", None))
+ try:
+ replies = []
+ for _ in range(2):
+ session["running"] = False
+ replies.append(server.handle_request({"id": "p", "method": "prompt.submit", "params": {
+ "session_id": sid, "text": "same prompt"}})["result"])
+ rows = db.get_messages_as_conversation(key, include_row_ids=True)
+ assert [reply.get("user_row_id") for reply in replies] == [row["_row_id"] for row in rows]
+ assert replies[0]["user_row_id"] != replies[1]["user_row_id"]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
def test_turn_adopts_the_submit_row_and_writes_no_duplicate(monkeypatch, tmp_path):
db = SessionDB(db_path=tmp_path / "state.db")
sid, key = _desktop_session(monkeypatch, db)
@@ -77,6 +107,57 @@ def test_turn_adopts_the_submit_row_and_writes_no_duplicate(monkeypatch, tmp_pat
db.close()
+def test_completion_receipt_covers_only_committed_current_turn_rows(monkeypatch, tmp_path):
+ from tui_gateway.prompt_turn import _TurnRun
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ monkeypatch.setattr(server, "_get_usage", lambda agent: {})
+ try:
+ server._ensure_session_db_row(session)
+ agent = _flush_agent(db, key)
+ old = [{"role": "user", "content": "again"}, {"role": "assistant", "content": "same"}]
+ agent._flush_messages_to_session_db(old, [])
+ current = [{"role": "user", "content": "again"}, {"role": "assistant", "content": "same"}]
+ messages = old + current
+ agent._persist_user_message_idx = len(old)
+ agent.context_compressor = SimpleNamespace(compression_count=0)
+ st = _TurnRun(agent, None, None, False, history=old, compression_count=0,
+ result={"messages": messages, "final_response": "same"})
+ agent._flush_messages_to_session_db(messages, old)
+ payload, _, _ = server._complete_turn_payload(session, st, None, 80)
+ rows = db.get_messages_as_conversation(key, include_row_ids=True)
+ assert payload.get("persisted_turn") == {
+ "user_row_id": rows[-2]["_row_id"],
+ "row_ids": [row["_row_id"] for row in rows[-2:]],
+ "final_assistant_row_id": rows[-1]["_row_id"],
+ "complete": True,
+ }
+ # Compression can discard an already-streamed segment even while the old prefix survives.
+ agent.context_compressor = SimpleNamespace(compression_count=1)
+ compressed, _, _ = server._complete_turn_payload(session, st, None, 80)
+ assert compressed["persisted_turn"]["complete"] is False
+ # The row address alone does not assert that a subsequently mutated body was committed.
+ current[-1].pop("_db_persisted")
+ 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}
+ # No authoritative current-turn anchor: never infer from matching text or positions in old history.
+ agent._persist_user_message_idx = None
+ missing, _, _ = server._complete_turn_payload(session, st, None, 80)
+ assert "persisted_turn" not in missing
+ # A preflight failure may return only old history while the agent still carries its old cursor.
+ agent._persist_user_message_idx = 0
+ st.result["messages"] = old
+ stale, _, _ = server._complete_turn_payload(session, st, None, 80)
+ assert "persisted_turn" not in stale
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
def test_failed_build_drops_the_staged_row_and_a_later_turn_never_adopts_it(monkeypatch, tmp_path):
"""The submit-time row is the durable record of THAT send only. A turn that ends before the agent runs
(build failed / bounded wait expired) must drop the staging dict, and a later turn without a matching
diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.py
index 8e9c5fa971b..7408c883cd5 100644
--- a/tui_gateway/contracts/events.py
+++ b/tui_gateway/contracts/events.py
@@ -167,6 +167,19 @@ class BillingBlock(Payload):
unverified: bool | None = None
+class PersistedTurn(Payload):
+ """Committed SQLite row addresses for the agent's current-turn suffix. Missing ids are
+ unproven, never negative acknowledgements. ``complete`` permits retiring the whole local
+ turn only when the original turn boundary, every row and final body are still accounted
+ for; compaction, redirects and partial writes conservatively leave it false. Row ids are
+ scoped to the owning profile's store, as in ``SessionMessage.row_id``."""
+
+ row_ids: list[int]
+ complete: bool
+ user_row_id: int | None = None
+ final_assistant_row_id: int | None = None
+
+
class MessageCompletePayload(Payload):
"""``prompt_turn._complete_turn_payload`` / ``session_auto_continue._emit_terminal_turn_error`` /
``agent_callbacks._mirror_subagent_to_child`` (child watch mirror: ``text`` only) /
@@ -185,6 +198,7 @@ class MessageCompletePayload(Payload):
recoverable: bool | None = None
error_surface: ErrorSurface | None = None
partial: bool | None = None
+ persisted_turn: PersistedTurn | None = None
event("message.complete", MessageCompletePayload, doc="The turn ended: final text, usage and outcome.")
diff --git a/tui_gateway/contracts/prompt_voice.py b/tui_gateway/contracts/prompt_voice.py
index ab24f1c8f22..d257e0a25ed 100644
--- a/tui_gateway/contracts/prompt_voice.py
+++ b/tui_gateway/contracts/prompt_voice.py
@@ -65,6 +65,9 @@ class PromptSubmitResult(Result):
status: PromptSubmitStatus | None = None
voice_stopped: bool | None = None
+ # The row written for THIS accepted input, captured before the worker can consume it.
+ # Absent on queued/steered/redirected inputs and whenever persistence is not yet proven.
+ user_row_id: int | None = None
survivor_user_row_ids: list[int | None] | None = None
survivor_row_id_map: dict[str, int | None] | None = None
turn_isolation: bool | None = None
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 18b21cbc2b4..aefcf692321 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -683,6 +683,10 @@ def _(rid, params: dict) -> dict:
isolated_response["error"].get("message", "unknown error"))
if (err := _persist_session_row_for_submit(rid, session, text, display_kind)) is not None:
return err
+ # Capture before starting the worker: it consumes the staging dict and may finish before the RPC returns.
+ staged_user = session.get("_submit_user_row") or {}
+ if isinstance(staged_user.get("_row_id"), int):
+ survivor_fields["user_row_id"] = staged_user["_row_id"]
# A completed FAILED build must not wedge the session: rebuild, don't replay it.
if not _restart_completed_failed_agent_build(sid, session, session.get("agent_ready")):
_start_agent_build(sid, session)
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index fa93f43580d..32cad0497ea 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -487,6 +487,7 @@ class _TurnRun:
thinking_started: bool = False
history: list = dataclasses.field(default_factory=list)
history_version: int = 0
+ compression_count: int | None = None
run_kwargs: Any = None
error_retained: bool = False
error_detail: str = ""
@@ -623,6 +624,7 @@ def _invoke_agent(
"""Wire the streaming callbacks and run the conversation into ``st.result``.
``text`` is the turn's raw submit, matched against the row staged by prompt.submit."""
agent = st.agent
+ st.compression_count = getattr(getattr(agent, "context_compressor", None), "compression_count", None)
# Bot Chat mirrors gateway.stream_consumer: deltas are withheld while the streamed buffer
# could still resolve to a silence marker ("NO"->"NO_REPLY"), so a bare marker is never
# shown and then retracted (the client keeps streamed text when message.complete is "").
@@ -754,6 +756,53 @@ def _absorb_turn_result(
return status_note
+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
+
+
def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None, cols: int):
"""``(payload, raw, status)`` for message.complete; retains/clears the inflight turn and
settles the hosted-room terminal receipt."""
@@ -773,6 +822,8 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,
if _is_bot_mode_session(session):
raw = _bot_mode_delivery_text(raw, successful=status == "complete")
payload = {"text": raw, "usage": _get_usage(agent), "status": status}
+ if receipt := _persisted_turn_receipt(st, raw, status):
+ payload["persisted_turn"] = receipt
if last_reasoning:
payload["reasoning"] = last_reasoning
if status_note:
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index e7953475729..92461151abd 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -352,6 +352,7 @@ def _persist_submit_user_row(session: dict, text: Any, display_kind: str | None)
durable (the shape ``quiet_single_query`` re-stages an unanswered DM in) so the turn adopts it via
``_stage_turn_user_message`` and the flush writes no second row. A failed write stages nothing:
the turn's crash persist then writes the row as before."""
+ session.pop("_submit_user_row", None) # a failed/unsupported write must not acknowledge an older send
key = session.get("session_key")
if not key or not isinstance(text, str) or not text.strip():
return