Skip to content

The agent that grows with you

fix(tui_gateway): next prompt sees turns another surface appended to the session (#42962)

kshitijk4poor83f6c77ae8b3
diff --git a/tests/tui_gateway/test_out_of_band_history_adoption.py b/tests/tui_gateway/test_out_of_band_history_adoption.py
new file mode 100644
index 00000000000..f6de8138ded
--- /dev/null
+++ b/tests/tui_gateway/test_out_of_band_history_adoption.py
@@ -0,0 +1,63 @@
+"""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."""
+
+import contextlib
+import threading
+
+from hermes_state import SessionDB
+from tui_gateway import server
+
+
+def _bind_db(monkeypatch, db):
+ @contextlib.contextmanager
+ def _owner_db(session):
+ yield db
+ monkeypatch.setattr(server, "_session_db", _owner_db)
+
+
+def _seed(tmp_path):
+ db = SessionDB(tmp_path / "state.db")
+ db.create_session("s1", source="desktop")
+ db.append_message("s1", "user", "My codeword is MANGO.", timestamp=1.0)
+ db.append_message("s1", "assistant", "OK", timestamp=2.0)
+ # What the agent's own flush leaves in memory: the rows stamped with their durable ids.
+ history = db.get_messages_as_conversation("s1", include_row_ids=True)
+ return db, {"session_key": "s1", "history": history, "history_lock": threading.Lock(), "history_version": 0}
+
+
+def test_next_turn_adopts_rows_another_writer_appended(tmp_path, monkeypatch):
+ db, session = _seed(tmp_path)
+ _bind_db(monkeypatch, db)
+ # A Telegram turn lands on the same session while the desktop is idle; its reply repeats an
+ # earlier one verbatim, so a text anchor would have mis-cut here — the row id boundary must not.
+ db.append_message("s1", "user", "My second codeword is KIWI.", timestamp=3.0)
+ db.append_message("s1", "assistant", "OK", timestamp=4.0)
+ # This turn's own prompt is already durable at submit (#111868) and must NOT be adopted as foreign.
+ own = db.append_message("s1", "user", "List every codeword.", timestamp=5.0)
+ session["_submit_user_row"] = {"role": "user", "content": "List every codeword.", "_row_id": own}
+
+ server._adopt_out_of_band_turns(session)
+
+ assert [m["content"] for m in session["history"]] == [
+ "My codeword is MANGO.", "OK", "My second codeword is KIWI.", "OK"]
+ assert session["history_version"] == 1
+ # Adopted rows are stamped: a second pass (next turn) finds nothing new.
+ server._adopt_out_of_band_turns(session)
+ assert len(session["history"]) == 4 and session["history_version"] == 1
+
+
+def test_compaction_resequenced_rows_are_not_adopted_again(tmp_path, monkeypatch):
+ """archive_and_compact re-inserts the carried messages as fresh rows while the in-memory dicts keep the
+ archived originals' ids (only the persisted marker is restamped); an unflushed local row carries no id.
+ Neither may be read back into history as if another surface had written it."""
+ db, session = _seed(tmp_path)
+ _bind_db(monkeypatch, db)
+ compacted = [{"role": "assistant", "content": "summary of MANGO", "_compressed_summary": True},
+ dict(session["history"][-1])] # carried tail keeps _row_id 2
+ db.archive_and_compact("s1", compacted, tail_count=1)
+ session["history"] = compacted + [{"role": "user", "content": "unflushed local turn"}]
+
+ server._adopt_out_of_band_turns(session)
+
+ assert [m["content"] for m in session["history"]] == ["summary of MANGO", "OK", "unflushed local turn"]
+ assert session["history_version"] == 0
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index fb55232711e..a24ef9cd711 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -487,6 +487,52 @@ class _TurnRun:
receipt_attempted: bool = False
+def _adopt_out_of_band_turns(session: dict) -> None:
+ """Fold turns another surface appended to this session (Telegram reply, cron run) into the model-facing
+ history before the turn snapshots it. The desktop already repaints them from the DB (#86588); without
+ this the next prompt still ran on the in-memory history and the model never saw them (#42962).
+ Foreign rows are the active rows between the highest ``_row_id`` the agent's own flushes stamped onto
+ the in-memory messages (``sync_flushed_message_markers``) and this turn's own user row, which
+ ``_persist_submit_user_row`` already wrote (#111868). Nothing stamped yet (seeded branch before its
+ first turn) means nothing to adopt; a cold resume arrives stamped."""
+ 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 or not (rows := _load_durable_truncation_history(session, repair_alternation=False)):
+ return
+ ceiling = _message_row_id(session.get("_submit_user_row") or {})
+ foreign = [m for m in rows if (rid := _message_row_id(m)) is not None and rid > seen
+ and (ceiling is None or rid < ceiling)]
+ tail = canonicalize_replay_history(_strip_in_memory_overlap(foreign, history))
+ if not tail:
+ return
+ with session["history_lock"]:
+ if int(session.get("history_version", 0)) != version:
+ return # /compress, a rewind or a pivot marker landed meanwhile; the next turn re-derives
+ session["history"] = history + tail
+ session["history_version"] = version + 1
+
+
+def _strip_in_memory_overlap(candidates: list[dict], history: list) -> list[dict]:
+ """A compaction re-inserts the carried messages as fresh rows (new ids, ``archive_and_compact``) while
+ the in-memory dicts keep the archived originals' ``_row_id``; those rows sit above the boundary but are
+ already in memory. Drop the longest candidate prefix that equals the durable in-memory tail message for
+ message — a foreign turn starts with a user row after our assistant reply, so it never aligns."""
+ from agent.context_compressor import _DB_PERSISTED_MARKER
+
+ def _key(msg: dict) -> tuple:
+ return (msg.get("role"), _coerce_message_text(msg.get("content")))
+ durable = [m for m in history if isinstance(m, dict)]
+ while durable and not (durable[-1].get(_DB_PERSISTED_MARKER) or _message_row_id(durable[-1]) is not None):
+ durable.pop() # an unflushed local row has no persisted copy to collide with
+ recent = [_key(m) for m in durable[-len(candidates):]] if candidates else []
+ for k in range(min(len(candidates), len(recent)), 0, -1):
+ if [_key(m) for m in candidates[:k]] == recent[-k:]:
+ return candidates[k:]
+ return candidates
+
+
def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images: list[str]):
"""Bind scopes, sync the agent, snapshot history, build the run message; returns
``(prompt, run_message, cols, streamer)`` or None when @-expansion was refused.
@@ -520,6 +566,7 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images
_sync_agent_model_with_config(sid, session)
_sync_agent_compression_with_config(sid, session)
_sync_bot_capabilities(sid, session) # Bot Chat: adopt Settings->Capabilities edits
+ _adopt_out_of_band_turns(session)
st.agent = agent = session["agent"]
# Snapshot after the model sync: a deferred switch's history mutation belongs to this turn.
with session["history_lock"]: