Skip to content

The agent that grows with you

fix(tui_gateway): keep superseded model-switch markers from replaying (#123545)

Halldrix427854076420
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 68835128168..bb4406f4775 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1236,6 +1236,19 @@ class SessionMessagesMixin:
"UPDATE messages SET active = 0 WHERE id = ? AND session_id = ?",
(row_id, session_id))
+ def deactivate_messages_by_display_kind(self, session_id: str, display_kind: str) -> int:
+ """Deactivate every live row of one ``display_kind`` (idempotent; returns the affected row count).
+ The durable counterpart to the in-memory strip a self-replacing pivot performs: the in-memory path
+ drops the prior entry so N pivots leave one, but a durable append has no such step, so every switch
+ left another active row and all of them replayed on resume. Rows are preserved (inactive), never
+ deleted — the same contract as :meth:`deactivate_message`, keyed by class instead of by id.
+ """
+ if not session_id or not display_kind:
+ return 0
+ return self._write_rowcount(
+ "UPDATE messages SET active = 0 WHERE session_id = ? AND display_kind = ? AND active = 1",
+ (session_id, _scrub_surrogates(display_kind)))
+
def _display_dedupe_key(self, row) -> Tuple[Any, ...]:
"""Historical display identity, including normalized live content from user handoff carriers."""
dedupe_content = row["content"]
diff --git a/tests/tui_gateway/test_submit_row_session_target.py b/tests/tui_gateway/test_submit_row_session_target.py
index 3ab18487b0f..b7a476c5771 100644
--- a/tests/tui_gateway/test_submit_row_session_target.py
+++ b/tests/tui_gateway/test_submit_row_session_target.py
@@ -167,6 +167,69 @@ def test_model_switch_marker_lands_in_the_live_session(monkeypatch, tmp_path):
db.close()
+def test_model_switch_markers_do_not_accumulate_across_switches(monkeypatch, tmp_path):
+ """The in-memory path is self-replacing: each switch strips the prior marker so N switches leave ONE
+ marker, not N re-sent on every API call (#65891). The DURABLE write had no counterpart, so N switches
+ left N active rows that all replay on resume — the invariant held in memory only. Filed in the live
+ session (see the test above), those rows are exactly the reporter's 130 stray markers."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ with session["history_lock"]:
+ session["running"] = True
+ server._start_inflight_turn(session, "earlier turn")
+ assert server._ensure_session_db_row(session) is not False
+ agent = _flush_agent(db, key)
+ session["agent"] = agent
+ for i in range(3):
+ server._append_model_switch_marker(session, model=f"model-{i}", provider="test-provider")
+ prefix = server._MODEL_SWITCH_MARKER_PREFIX
+ # LIVE rows only (get_messages defaults to active=1), and full content: the marker prefix is
+ # longer than the _rows() helper's 48-char preview.
+ live = [r for r in db.get_messages(key) if prefix in str(r.get("content") or "")]
+ assert len(live) == 1, (
+ f"3 switches must leave 1 live durable marker, not {len(live)}: "
+ f"{[str(r.get('content'))[:60] for r in live]}")
+ # The superseded rows are preserved inactive, never deleted (same contract as deactivate_message).
+ kept = [r for r in db.get_messages(key, include_inactive=True)
+ if prefix in str(r.get("content") or "")]
+ assert len(kept) == 3, f"superseded markers must be kept inactive, not deleted: {len(kept)}"
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_message_react_targets_the_row_in_the_session_that_owns_it(monkeypatch, tmp_path):
+ """``message.react`` with ``newest_role`` resolves the row via ``latest_message_row_id``, which filters
+ on one session_id. On a rotated session the newest user row lives in the continuation, so a stale
+ ``session_key`` reacts to the PARENT's last user row — the previous turn — or 404s when the parent
+ has no text row. Same defect class as the submit row: an off-turn write addressed by a key a
+ rotation invalidated (#123545)."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key, session, agent, child = _rotated_session(monkeypatch, db)
+ try:
+ # The continuation's newest user row is the rotated turn's own submit row.
+ db.append_message(child, "user", content="the turn the user just reacted to")
+ # The parent still holds the PREVIOUS turn's last user row.
+ db.append_message(key, "user", content="the previous turn")
+
+ got = server.handle_request({"id": "r1", "method": "message.react", "params": {
+ "session_id": sid, "newest_role": "user", "emoji": "thumbsup"}})
+ assert "result" in got, got
+ want = db._read_one("SELECT id FROM messages WHERE session_id = ? AND content = ?",
+ (child, "the turn the user just reacted to"))
+ assert want is not None
+ row_id = int(got["result"]["row_id"])
+ assert row_id == want[0], (
+ f"reaction landed on row {row_id} (session "
+ f"{db._read_one('SELECT session_id FROM messages WHERE id = ?', (row_id,))[0]}), "
+ f"not the newest user row {want[0]} in the live session {child}")
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
def test_unrotated_session_keeps_writing_to_session_key(monkeypatch, tmp_path):
"""The ordinary case is unchanged: no rotation, the row lands under session_key as before."""
db = SessionDB(db_path=tmp_path / "state.db")
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 17a1780abcc..a75ee625bb8 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -10464,6 +10464,9 @@ def test_config_set_model_switches_agent_without_touching_env(monkeypatch):
{"session_id": session_id, "role": role, "content": content}
)
+ def deactivate_messages_by_display_kind(self, _session_id, _display_kind):
+ return 0
+
agent = Agent()
db = SessionDB()
agent._session_db = db
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 584f435f51a..b96ad5739fa 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1243,12 +1243,16 @@ def _(rid, params: dict, session: dict) -> dict:
with _session_db(session) as db:
if db is None:
return _db_unavailable_error(rid, code=5007)
+ # The row lookup and the reaction are both session-qualified, and the newest live row lives in
+ # the session the agent writes to — which a compression rotation moves off session_key mid-session
+ # (#123545). Same stale-key hazard as the submit row.
+ row_session = _submit_row_target_key(session)
try:
if row_id is None:
- row_id = db.latest_message_row_id(session["session_key"], role=newest_role)
+ row_id = db.latest_message_row_id(row_session, role=newest_role)
if row_id is None:
return _err(rid, 4040, "no message to react to yet")
- reactions = db.set_message_reaction(session["session_key"], int(row_id), emoji, author=author)
+ reactions = db.set_message_reaction(row_session, int(row_id), emoji, author=author)
except Exception as e:
return _err(rid, 5007, str(e))
if reactions is None:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 0a24fe2c18c..517c389e7ac 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1806,10 +1806,14 @@ def _append_model_switch_marker(session: dict | None, *, model: str, provider: s
# Same stale-key hazard as the submit row: this durable pivot must land in the session the
# live agent writes to, or a model switch between turns on a rotated session files the notice
# under a parent the conversation no longer reads from (#123545).
+ target = _submit_row_target_key(session)
+ # The in-memory strip above keeps one marker; the durable rows need the same invariant or N
+ # switches leave N active rows that all replay on resume (#65891 kept it in memory only).
+ db.deactivate_messages_by_display_kind(target, "model_switch")
from agent.message_metadata import stamp_message_uid
entry["_row_id"] = db.append_message(
- session_id=_submit_row_target_key(session), role="user", content=marker,
- display_kind="model_switch", message_uid=stamp_message_uid(entry))
+ session_id=target, role="user", content=marker, display_kind="model_switch",
+ message_uid=stamp_message_uid(entry))
entry[_DB_PERSISTED_MARKER] = True
except Exception:
logger.debug("failed to persist model switch marker", exc_info=True)
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 8d5a40142d2..68e1c88e533 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -551,9 +551,10 @@ def _submit_row_target_key(session: dict) -> str:
against this handle (``_persist_live_session_system_prompt``). Do NOT re-resolve through the lineage
here: ``resolve_resume_session_id`` returns the deepest node that has MESSAGES, so the freshly-minted
child of a just-published rotation resolves back to the parent and the fix would no-op exactly when
- it is needed. The choice is made ONCE here and recorded on the staged dict (``_session_id``) so
- every later addresser of that row — the @-expansion rewrite, the queue merge, the drain deactivation
- — reads the same key instead of re-deriving one that a rotation can invalidate mid-turn.
+ it is needed. The choice is made ONCE here and recorded on the staged dict under
+ ``_SUBMIT_ROW_SESSION_KEY`` so every later addresser of that row — the @-expansion rewrite, the
+ queue merge, the drain deactivation — reads the same key instead of re-deriving one that a rotation
+ can invalidate mid-turn.
"""
return str(getattr(session.get("agent"), "session_id", None) or "") or str(session.get("session_key") or "")