Skip to content

The agent that grows with you

fix(tui_gateway): catch a live record up from the store when it lost its row ids

Austin Pickettf389bddd118d
diff --git a/tests/tui_gateway/test_out_of_band_history_adoption.py b/tests/tui_gateway/test_out_of_band_history_adoption.py
index 84717521ea3..eda19678942 100644
--- a/tests/tui_gateway/test_out_of_band_history_adoption.py
+++ b/tests/tui_gateway/test_out_of_band_history_adoption.py
@@ -1,8 +1,15 @@
"""Regression for #42962: a turn another surface (Telegram, cron) appended to a live desktop/TUI session must
-reach the model on the next local prompt, not only the repainted transcript."""
+reach the model on the next local prompt, not only the repainted transcript.
+
+Second half (#81951): the same reconciliation must not hinge on the live record's in-memory ``_row_id``
+stamps. A record whose history was rebuilt from provider-format messages carries none, and the gateway's
+concurrent rows were then silently dropped — the UI showed the full transcript while the provider request
+held only the early snapshot.
+"""
import contextlib
import threading
+import types
from hermes_state import SessionDB
from tui_gateway import server
@@ -69,3 +76,141 @@ def test_compaction_epochs(tmp_path, monkeypatch):
assert [m["content"] for m in session["history"]] == ["summary of MANGO", "Repeat it", "MANGO", "KIWI", "OK"]
assert session["history"][0].get("_compressed_summary") and session["history_version"] == 1
+
+
+# ── #81951: the live record that lost its durable stamps ─────────────────────
+
+def _seed_exchange(db, n: int, *, session_id: str = "s1") -> None:
+ """One well-formed exchange, so alternation repair is a no-op on the lineage."""
+ call = [{"id": f"c{n}", "type": "function", "function": {"name": "terminal", "arguments": "{}"}}]
+ db.append_message(session_id, "user", f"ask{n}", timestamp=float(n * 10))
+ db.append_message(session_id, "assistant", "", timestamp=float(n * 10 + 1), tool_calls=call)
+ db.append_message(session_id, "tool", f"probe{n}", timestamp=float(n * 10 + 2),
+ tool_call_id=f"c{n}", tool_name="terminal")
+ db.append_message(session_id, "assistant", f"answer{n}", timestamp=float(n * 10 + 3))
+
+
+def _hydrated_record(db, *, stamped: bool) -> dict:
+ """The desktop's live record as hydration leaves it: the first exchange, row ids or not."""
+ history = db.get_messages_as_conversation("s1", repair_alternation=True, include_row_ids=True)
+ if not stamped:
+ for message in history:
+ message.pop("_row_id", None)
+ return {"session_key": "s1", "history": history, "history_lock": threading.Lock(), "history_version": 0}
+
+
+def _gateway_appends(db, turns: int = 10) -> None:
+ for n in range(1, turns + 1):
+ _seed_exchange(db, n)
+
+
+def _immediate_thread(monkeypatch) -> None:
+ class _ImmediateThread:
+ def __init__(self, target=None, daemon=None, **_kwargs):
+ self._target = target
+
+ def start(self):
+ self._target()
+
+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)
+
+
+def test_desktop_prompt_carries_gateway_rows_appended_after_hydration(tmp_path, monkeypatch):
+ """The reported shape: desktop hydrated the first exchange, the gateway appended ten more, and the
+ next desktop prompt must send the whole conversation — not the early snapshot — to the provider."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=True)
+ _gateway_appends(db)
+
+ seen = {}
+
+ class _Agent:
+ def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):
+ seen["history"] = list(conversation_history or [])
+ return {"final_response": "ok", "messages": [
+ *(conversation_history or []), {"role": "user", "content": prompt},
+ {"role": "assistant", "content": "ok"}]}
+
+ session["agent"] = _Agent()
+ server._sessions["sid-81951"] = session
+ _bind_db(monkeypatch, db)
+ _immediate_thread(monkeypatch)
+ monkeypatch.setattr(server, "_get_usage", lambda _a: {})
+ monkeypatch.setattr(server, "render_message", lambda _t, _c: "")
+ monkeypatch.setattr(server, "_emit", lambda *a: None)
+ try:
+ resp = server.handle_request({"id": "1", "method": "prompt.submit",
+ "params": {"session_id": "sid-81951", "text": "continue on desktop"}})
+ assert resp.get("result"), resp
+ finally:
+ server._sessions.pop("sid-81951", None)
+
+ contents = [m.get("content") for m in seen["history"]]
+ assert contents[:4] == ["ask0", "", "probe0", "answer0"]
+ assert [c for c in contents if isinstance(c, str) and c.startswith("answer")] == [
+ f"answer{n}" for n in range(11)]
+
+
+def test_unstamped_live_record_is_caught_up_from_the_store(tmp_path, monkeypatch):
+ """No durable row ids in memory: the store-ahead fallback still folds the gateway's rows in."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=False)
+ _bind_db(monkeypatch, db)
+ _gateway_appends(db)
+
+ server._adopt_out_of_band_turns(session)
+
+ assert session["history"][-1]["content"] == "answer10"
+ assert len(session["history"]) == 44 and session["history_version"] == 1
+ # Adopted rows are stamped, so the row-id path is authoritative again on the next turn.
+ server._adopt_out_of_band_turns(session)
+ assert len(session["history"]) == 44 and session["history_version"] == 1
+
+
+def test_unstamped_record_that_diverged_from_the_store_is_left_alone(tmp_path, monkeypatch):
+ """A local rewrite the store has not caught up with must never be clobbered by the store tail."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=False)
+ _bind_db(monkeypatch, db)
+ _gateway_appends(db)
+ session["history"][0]["content"] = "locally edited ask" # head no longer matches the store
+
+ server._adopt_out_of_band_turns(session)
+
+ assert session["history"][0]["content"] == "locally edited ask"
+ assert len(session["history"]) == 4 and session["history_version"] == 0
+
+
+def test_unstamped_record_is_untouched_when_the_store_is_not_ahead(tmp_path, monkeypatch):
+ """A not-yet-flushed local tail (store shorter) is the fresher record — adopt nothing."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=False)
+ _bind_db(monkeypatch, db)
+ session["history"] = list(session["history"]) + [{"role": "user", "content": "typed but unflushed"}]
+
+ server._adopt_out_of_band_turns(session)
+
+ assert session["history"][-1]["content"] == "typed but unflushed"
+ assert session["history_version"] == 0
+
+
+def test_unstamped_seeded_history_equal_to_the_store_is_untouched(tmp_path, monkeypatch):
+ """A seeded/branched record writes its rows before the first turn: heads match, lengths equal, no-op."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=False)
+ _bind_db(monkeypatch, db)
+ before = list(session["history"])
+
+ server._adopt_out_of_band_turns(session)
+
+ assert session["history"] == before and session["history_version"] == 0
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index e938bcc3776..a6ca0e1223b 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -507,12 +507,15 @@ def _adopt_out_of_band_turns(session: dict) -> None:
this turn's own user row, which ``_persist_submit_user_row`` already wrote (#111868). When a foreign
row is a compaction summary the other surface rewrote the transcript under us, so the in-memory history
is stale from the root and is re-hydrated from the DB the way ``session.resume`` does. Nothing stamped
- yet (seeded branch before its first turn) means nothing to adopt; a cold resume arrives stamped."""
+ yet (seeded branch before its first turn) means nothing to adopt; a cold resume arrives stamped — but a
+ record whose list was rebuilt from provider-format messages carries no stamp at all, so the row-id
+ boundary cannot key on anything and the store-ahead fallback takes over (#81951)."""
with session["history_lock"]:
history, version = list(session.get("history") or ()), int(session.get("history_version", 0))
seen = max((rid for m in history if isinstance(m, dict) and (rid := _message_row_id(m)) is not None),
default=None)
if seen is None:
+ _adopt_store_tail_without_row_ids(session, history, version)
return
ceiling = _message_row_id(session.get("_submit_user_row") or {})
@@ -544,6 +547,40 @@ def _adopt_out_of_band_turns(session: dict) -> None:
session["history_version"] = version + 1
+def _adopt_store_tail_without_row_ids(session: dict, history: list, version: int) -> None:
+ """Catch a live record up with the store when its in-memory messages carry NO durable ``_row_id``.
+
+ ``_adopt_out_of_band_turns`` keys off the highest ``_row_id`` in memory; a record whose list was
+ rebuilt from provider-format messages (a failed turn's ``agent._session_messages``, the unstamped
+ shape ``_resolve_truncate_row_id`` heals for rewind — #82959) carries none. A writer in ANOTHER
+ process (the messaging gateway appending to the same session while the desktop's serve record holds
+ it) was then silently dropped and the next provider request truncated to the early snapshot while
+ the UI showed the full transcript (#81951).
+
+ With no row ids there is no boundary to key on, so adoption is gated on proof instead: the durable
+ lineage must be STRICTLY longer and its head must equal the in-memory view entry for entry. A
+ seeded/branched record writes its rows to the store before the first turn (heads match, equal
+ lengths — no-op) and a diverged view (prefix mismatch, e.g. a rewind that has not landed locally) is
+ left untouched, so the guard that keeps the stamped path safe is preserved. An empty in-memory
+ history has no head to prove against and is left alone, exactly as the stamped path leaves it.
+ """
+ rows = _load_durable_truncation_history(session, repair_alternation=True) or []
+ if not history or len(rows) <= len(history):
+ return
+ if not all(isinstance(mem, dict) and mem.get("role") == stored.get("role")
+ and mem.get("content") == stored.get("content")
+ for mem, stored in zip(history, rows)):
+ return
+ tail = canonicalize_replay_history(rows[len(history):])
+ if not tail:
+ return
+ with session["history_lock"]:
+ if int(session.get("history_version", 0)) != version:
+ return # a local rewrite landed meanwhile; the next turn re-derives
+ session["history"] = history + tail
+ session["history_version"] = version + 1
+
+
def _install_has_prior_sessions(session: dict) -> bool:
"""True when this install already has session rows beyond the current one.