Skip to content

The agent that grows with you

fix(tui_gateway): retire a never-drained busy-queue accept row on cold reopen (#125577)

Yuan Liead1a7dc7899
diff --git a/hermes_state_common.py b/hermes_state_common.py
index 409a8c458bb..517e386873e 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -65,6 +65,15 @@ def _sql_literal(text: str) -> str:
return "'" + text.replace("'", "''") + "'"
+# ``display_metadata`` flag stamped on the user row a busy-queue accept writes (#111868/#121374
+# accept-time durability). The in-memory queue drain re-places an unmarked row at the transcript
+# end and deactivates this one; a backend restart discards the queue with nothing left to retire
+# the accept-time row, so ``reopen_session`` deactivates still-marked rows (#125577) — the marker
+# is exactly what distinguishes a never-drained accept row from a dispatched-then-interrupted
+# turn's row (which #123532 deliberately keeps active).
+QUEUED_PROMPT_METADATA_KEY = "_queued_prompt"
+
+
def _sql_json_extract(expression: str, path: str) -> str:
"""Build a non-throwing JSON marker lookup for a JSON TEXT column."""
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index cbfb5b954a9..ba175bddb4b 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -19,7 +19,7 @@ from hermes_state_errors import SessionActiveWriteGuardError
from hermes_state_common import (
_LISTABLE_CHILD_SQL, _PREVIEW_ELIGIBLE_SQL, _PREVIEW_RAW_SELECT, _RECOVERABLE_END_REASONS,
_RECOVERABLE_END_REASONS_SQL, _RESET_CHILD_SQL, _RESET_END_REASONS, _legacy_reset_child_sql, _non_continuation_child_sql,
- _shape_preview,
+ _shape_preview, QUEUED_PROMPT_METADATA_KEY,
_sql_in_window, _sql_json_extract, _sql_session_last_active, _sql_session_last_active_by_id,
escape_like as _escape_like, _SQL_IN_CHUNK, _id_chunks, _placeholders as _session_ids_placeholders,
)
@@ -514,6 +514,18 @@ class SessionSessionsMixin:
The guard compares against the parent's started_at, not its current ended_at: a parent that was
reopened and re-ended later still owns reset children from its earlier boundaries."""
def _do(conn):
+ # Retire busy-queue accept rows that never drained (#125577): a restart discarded the
+ # in-memory queue, so nothing re-placed/deactivated the row written at accept time and
+ # alternation repair would glue the never-run prompt into the previous turn's user
+ # message. The drain's replacement row carries no marker, so still-marked == never
+ # drained; a dispatched-then-interrupted turn's row is never marked (its discard is
+ # handled in-process, #123532). Deactivated, never deleted — the row stays as history.
+ conn.execute(
+ "UPDATE messages SET active = 0 "
+ f"WHERE session_id = ? AND role = 'user' AND active = 1 "
+ f"AND COALESCE({_sql_json_extract('display_metadata', '$.' + QUEUED_PROMPT_METADATA_KEY)}, 0) = 1",
+ (session_id,),
+ )
conn.execute(
"UPDATE sessions AS child SET model_config = json_set("
"COALESCE(child.model_config, '{}'), '$._reset_from', child.parent_session_id) "
diff --git a/tests/tui_gateway/test_queued_prompt_restart_retire.py b/tests/tui_gateway/test_queued_prompt_restart_retire.py
new file mode 100644
index 00000000000..75fdf5f9394
--- /dev/null
+++ b/tests/tui_gateway/test_queued_prompt_restart_retire.py
@@ -0,0 +1,90 @@
+"""A restart discards the in-memory busy-queue, but the accept-time user row it wrote stays
+active — the next cold resume's alternation repair glues the never-run prompt into the previous
+turn's user message (#125577).
+
+The fix marks the accept-time row (``display_metadata._queued_prompt``) and ``reopen_session``
+deactivates still-marked rows: the drain's replacement row is unmarked, so still-marked after a
+restart == never drained. Rows are deactivated, never deleted, the same marking the drain uses.
+"""
+
+import types
+
+from hermes_state import SessionDB
+from tui_gateway import server
+
+
+def _desktop_session(monkeypatch, db):
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ monkeypatch.setattr(server, "_schedule_agent_build", lambda _sid: None)
+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)
+ monkeypatch.setattr(server, "_register_session_cwd", lambda _session: None)
+ resp = server.handle_request({"id": "c", "method": "session.create", "params": {"cols": 96, "source": "desktop"}})
+ assert "result" in resp, resp
+ sid = resp["result"]["session_id"]
+ server._sessions[sid]["agent"] = types.SimpleNamespace()
+ return sid, resp["result"]["stored_session_id"]
+
+
+def _busy(session, in_flight="prompt A"):
+ with session["history_lock"]:
+ session["running"] = True
+ server._start_inflight_turn(session, in_flight)
+
+
+def _active_rows(db, key):
+ return db.get_messages_as_conversation(key, repair_alternation=True, include_row_ids=True)
+
+
+def _accept_busy_prompt_a_concludes(db, sid, key, queued_text="queued prompt B RESTART-MARKER"):
+ """Turn A runs, B is accepted busy (accept-time row written), turn A concludes — then the
+ backend dies BEFORE the queue drains. Raw: [user A, user B(queued), assistant A]."""
+ session = server._sessions[sid]
+ server._ensure_session_db_row(session)
+ db.append_message(key, "user", content="prompt A")
+ _busy(session)
+ resp = server._handle_busy_submit("r1", sid, session, queued_text, "ws-1", queued=True, display_kind=None)
+ assert resp["result"]["status"] == "queued"
+ db.append_message(key, "assistant", content="reply A") # turn A concludes; the drain never runs
+
+
+def test_restart_retires_the_never_drained_accept_row(monkeypatch, tmp_path):
+ """RED for the bug: with the queue gone (restart), nothing retired the accept-time row and the
+ repaired projection returned 'prompt A\n\nqueued prompt B' absorbed into turn A's user message."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ try:
+ _accept_busy_prompt_a_concludes(db, sid, key)
+ # The restart's cold attach: a NEW handle on the same file, then the reopen ritual every
+ # resume path (TUI/Desktop hydration, CLI, oneshot) runs before reading the transcript.
+ fresh = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ fresh.reopen_session(key)
+ repaired = fresh.get_messages_as_conversation(key, repair_alternation=True, include_row_ids=True)
+ assert [(r["role"], r["content"]) for r in repaired] == [
+ ("user", "prompt A"), ("assistant", "reply A")]
+ finally:
+ fresh.close()
+ # The never-run prompt is retired (inactive), never deleted: durable history keeps it.
+ every = db.get_messages_as_conversation(key, include_inactive=True, include_row_ids=True)
+ retired = [r for r in every if "RESTART-MARKER" in str(r["content"])]
+ assert len(retired) == 1
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_resume_does_not_retire_drained_or_plain_rows(monkeypatch, tmp_path):
+ """The dispatched queued row (re-placed unmarked by the drain) and ordinary user rows survive
+ reopen_session — only still-marked never-drained accept rows are retired."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ try:
+ server._ensure_session_db_row(server._sessions[sid])
+ db.append_message(key, "user", content="plain prompt")
+ db.append_message(key, "assistant", content="plain reply")
+ db.reopen_session(key)
+ assert [(r["role"], r["content"]) for r in _active_rows(db, key)] == [
+ ("user", "plain prompt"), ("assistant", "plain reply")]
+ finally:
+ server._sessions.pop(sid, None)
+ db.close()
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index 05e88d97c76..3003ab86966 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -319,14 +319,19 @@ def _persist_queued_user_row(session: dict, envelope: dict, display_kind: str |
return
staged["content"] = envelope["text"]
return
- staged = _write_submit_user_row(session, envelope.get("text"), display_kind)
+ # ``display_metadata`` marker: ``reopen_session`` retires still-marked rows after a restart
+ # discarded the in-memory queue (#125577); the drain's replacement row is unmarked.
+ from hermes_state_common import QUEUED_PROMPT_METADATA_KEY
+ staged = _write_submit_user_row(
+ session, envelope.get("text"), display_kind,
+ accept_metadata={QUEUED_PROMPT_METADATA_KEY: True})
if staged is not None:
envelope["_submit_user_row"] = staged
if display_kind:
envelope["_queued_display_kind"] = display_kind
-def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> dict | None:
+def _replace_queued_user_row_for_turn(session: dict, queued: dict, is_dispatching: bool = False) -> dict | None:
"""Re-place a queued prompt's accept-time row at the transcript END before dispatching its turn.
The accept-time write lands BEFORE the in-flight turn's assistant rows (raw ``[uA, uB, aA]``), and
@@ -342,7 +347,15 @@ def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> dict | Non
return None # no accept-time row (write failed / pre-feature envelope): the turn persists as before
# Append the replacement FIRST: if that write fails nothing is deactivated, the accept-time row
# stays active (the message stays visible) and the turn's crash persist persists it as before.
- _persist_submit_user_row(session, queued.get("text"), queued.get("_queued_display_kind"))
+ # The DISPATCHING envelope's replacement carries no marker (its turn adopts the row immediately);
+ # still-queued envelopes keep the never-drained marker (#125577) so a restart between drains
+ # retires the row rather than gluing the never-run prompt into the previous turn.
+ if is_dispatching:
+ _persist_submit_user_row(session, queued.get("text"), queued.get("_queued_display_kind"))
+ else:
+ from hermes_state_common import QUEUED_PROMPT_METADATA_KEY
+ _persist_submit_user_row(session, queued.get("text"), queued.get("_queued_display_kind"),
+ accept_metadata={QUEUED_PROMPT_METADATA_KEY: True})
fresh = session.get("_submit_user_row")
if not (isinstance(fresh, dict) and isinstance(fresh.get("_row_id"), int)):
return None # re-append wrote nothing: keep the accept-time row active
@@ -450,7 +463,7 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
# prompt before the earlier one. Under history_lock so a concurrent submit can't interleave
# its own row write between the re-append and the deactivation.
with session["history_lock"]:
- dispatch_row = _replace_queued_user_row_for_turn(session, queued)
+ dispatch_row = _replace_queued_user_row_for_turn(session, queued, is_dispatching=True)
still_queued = (([session["queued_prompt"]] if session.get("queued_prompt") else [])
+ list(session.get("queued_prompts") or []))
for envelope in still_queued:
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 2afacb0c863..94aade17a09 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -6,6 +6,8 @@ install time (method_ctx.bind_module), so they reference server.py globals bare.
from __future__ import annotations
import contextlib
+from typing import Any
+
from tui_gateway import git_probe
from .method_ctx import bind_module
@@ -501,11 +503,14 @@ def _persist_branch_seed(session: dict) -> None:
_workdir_reraise_disk_full(exc, "branch seed persist failed")
-def _write_submit_user_row(session: dict, text: Any, display_kind: str | None) -> dict | None:
+def _write_submit_user_row(session: dict, text: Any, display_kind: str | None,
+ accept_metadata: dict | None = None) -> dict | None:
"""Write the submitted user turn to the transcript and RETURN the durable dict (stamped
``_DB_PERSISTED_MARKER``/``_row_id``) WITHOUT slotting it on the session. The write half of
:func:`_persist_submit_user_row`, shared by the busy-queue accept (which attaches the dict to
the queue envelope, never the shared session slot a possibly-still-staged in-flight turn owns).
+ ``accept_metadata`` merges into ``display_metadata`` (the busy-queue accept's never-drained
+ marker, retired by ``reopen_session`` — #125577).
Returns None when nothing was written (no key / non-text / store unavailable / failed write)."""
key = session.get("session_key")
if not key or not isinstance(text, str) or not text.strip():
@@ -515,13 +520,16 @@ def _write_submit_user_row(session: dict, text: Any, display_kind: str | None) -
staged = stamp_message_timestamp({"role": "user", "content": text})
if display_kind:
staged["display_kind"] = display_kind
+ if accept_metadata:
+ staged["display_metadata"] = {**accept_metadata}
with _session_db(session) as db:
if db is None:
return None
try:
staged["_row_id"] = db.append_message(
key, "user", content=text, display_kind=display_kind, timestamp=staged["timestamp"],
- message_uid=stamp_message_uid(staged)) # the live dict the turn adopts carries the row's uid
+ message_uid=stamp_message_uid(staged), # the live dict the turn adopts carries the row's uid
+ display_metadata=staged.get("display_metadata"))
except Exception as exc:
_workdir_reraise_disk_full(exc, "submit-time user row persist failed")
return None
@@ -529,15 +537,17 @@ def _write_submit_user_row(session: dict, text: Any, display_kind: str | None) -
return staged
-def _persist_submit_user_row(session: dict, text: Any, display_kind: str | None) -> None:
+def _persist_submit_user_row(session: dict, text: Any, display_kind: str | None,
+ accept_metadata: dict | None = None) -> None:
"""Write the submitted user turn at send time, before the agent build and turn: the agent's own
crash persist only runs once the build finished, so quitting a frozen app during a slow first build
left a session row with no message (#111868). The dict is staged on the session already stamped
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."""
+ the turn's crash persist then writes the row as before. ``accept_metadata`` marks a row that
+ belongs to a still-QUEUED envelope (#125577); a dispatching turn's row is never marked."""
session.pop("_submit_user_row", None) # a failed/unsupported write must not acknowledge an older send
- if (staged := _write_submit_user_row(session, text, display_kind)) is not None:
+ if (staged := _write_submit_user_row(session, text, display_kind, accept_metadata)) is not None:
session["_submit_user_row"] = staged