Skip to content

The agent that grows with you

fix(tui_gateway): keep the unstamped catch-up below this turn's own user row

Austin Pickett8f7443747e53
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 eda19678942..89f021f86ef 100644
--- a/tests/tui_gateway/test_out_of_band_history_adoption.py
+++ b/tests/tui_gateway/test_out_of_band_history_adoption.py
@@ -9,7 +9,6 @@ held only the early snapshot.
import contextlib
import threading
-import types
from hermes_state import SessionDB
from tui_gateway import server
@@ -115,15 +114,8 @@ def _immediate_thread(monkeypatch) -> None:
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)
-
+def _desktop_prompt(db, session, monkeypatch, text: str = "continue on desktop") -> list:
+ """Drive ``prompt.submit`` on ``session``; returns the ``conversation_history`` the model was given."""
seen = {}
class _Agent:
@@ -142,17 +134,45 @@ def test_desktop_prompt_carries_gateway_rows_appended_after_hydration(tmp_path,
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"}})
+ "params": {"session_id": "sid-81951", "text": text}})
assert resp.get("result"), resp
finally:
server._sessions.pop("sid-81951", None)
+ return seen["history"]
+
+
+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)
+
+ contents = [m.get("content") for m in _desktop_prompt(db, session, monkeypatch)]
- 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_desktop_prompt_does_not_adopt_its_own_user_row(tmp_path, monkeypatch):
+ """Through ``prompt.submit`` the store already holds THIS turn's user row when adoption runs
+ (``_persist_submit_user_row``); the fallback must stop below it like the stamped path does, or the
+ model sees the prompt twice and the live history keeps both copies."""
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ _seed_exchange(db, 0)
+ session = _hydrated_record(db, stamped=False)
+ _gateway_appends(db, turns=1)
+
+ contents = [m.get("content") for m in _desktop_prompt(db, session, monkeypatch)]
+
+ assert contents == ["ask0", "", "probe0", "answer0", "ask1", "", "probe1", "answer1"]
+ assert [m["content"] for m in session["history"]].count("continue on desktop") == 1
+
+
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")
@@ -202,8 +222,8 @@ def test_unstamped_record_is_untouched_when_the_store_is_not_ahead(tmp_path, mon
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."""
+def test_unstamped_history_equal_to_the_store_is_untouched(tmp_path, monkeypatch):
+ """Heads match and lengths are equal: nothing appended out of band, no-op."""
db = SessionDB(tmp_path / "state.db")
db.create_session("s1", source="desktop")
_seed_exchange(db, 0)
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index a6ca0e1223b..aeb2c38736f 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -514,13 +514,13 @@ def _adopt_out_of_band_turns(session: dict) -> None:
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 {})
def _below_ceiling(rid) -> bool:
return isinstance(rid, int) and (ceiling is None or rid < ceiling)
+ if seen is None:
+ _adopt_store_tail_without_row_ids(session, history, version, _below_ceiling)
+ return
def _foreign(rid) -> bool:
return _below_ceiling(rid) and rid > seen
@@ -547,24 +547,24 @@ 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:
+def _adopt_store_tail_without_row_ids(session: dict, history: list, version: int, below_ceiling) -> 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).
+ rebuilt from provider-format 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.
+ lineage (below this turn's own user row, which ``_persist_submit_user_row`` already wrote and the turn
+ appends itself) must be STRICTLY longer and its head must equal the in-memory view entry for entry.
+ A diverged view (prefix mismatch, e.g. a rewind that has not landed locally), a store that is not
+ ahead (an unflushed local tail is the fresher record) and an empty in-memory history (no head to
+ prove against) are left alone, the same guards that keep the stamped path safe.
"""
- rows = _load_durable_truncation_history(session, repair_alternation=True) or []
+ rows = [m for m in _load_durable_truncation_history(session, repair_alternation=True) or []
+ if below_ceiling(_message_row_id(m))]
if not history or len(rows) <= len(history):
return
if not all(isinstance(mem, dict) and mem.get("role") == stored.get("role")