Skip to content

The agent that grows with you

fix(tui_gateway): re-place every queued row at drain, not just the dispatched one

DavidMetcalfec6e0f2498ec0
diff --git a/tests/tui_gateway/test_queued_prompt_persistence.py b/tests/tui_gateway/test_queued_prompt_persistence.py
index 45837eb0160..d9ca27041e6 100644
--- a/tests/tui_gateway/test_queued_prompt_persistence.py
+++ b/tests/tui_gateway/test_queued_prompt_persistence.py
@@ -196,3 +196,41 @@ def test_drained_turn_adopts_the_replaced_row_and_writes_no_duplicate(monkeypatc
finally:
server._sessions.pop(sid, None)
db.close()
+
+
+def test_partial_drain_never_puts_a_later_prompt_before_an_earlier_one(monkeypatch, tmp_path):
+ """Two non-mergeable (image-bearing) prompts accepted mid-turn; only the FIRST drains, then the
+ process dies (the in-memory queue is lost). Acceptance order must still hold in the transcript:
+ the second prompt must never render before the first. Without queue-wide re-placement at each
+ drain, the second prompt's accept-time row stays ahead of the in-flight reply while the first's
+ heals past it — permanently rendering the later prompt before the earlier one."""
+ db = SessionDB(db_path=tmp_path / "state.db")
+ sid, key = _desktop_session(monkeypatch, db)
+ session = server._sessions[sid]
+ try:
+ server._ensure_session_db_row(session) # the lazy row a real first submit would have written
+ db.append_message(key, "user", content="prompt A") # turn A's row
+ _busy(session)
+ session["attached_images"] = ["/tmp/b.png"]
+ assert server._handle_busy_submit("r1", sid, session, "prompt B QUEUED-B", "ws-1",
+ queued=True, display_kind=None)["result"]["status"] == "queued"
+ session["attached_images"] = ["/tmp/c.png"]
+ assert server._handle_busy_submit("r2", sid, session, "prompt C QUEUED-C", "ws-1",
+ queued=True, display_kind=None)["result"]["status"] == "queued"
+ db.append_message(key, "assistant", content="reply A") # turn A concludes
+ with session["history_lock"]:
+ session["running"] = False
+ server._clear_inflight_turn(session)
+ monkeypatch.setattr(server, "_run_prompt_submit",
+ lambda rid, s, sess, text, **kw: _run_turn(sess, db, key, text, "reply B"))
+ assert server._drain_queued_prompt("r3", sid, session) is True # drains B only
+ # The crash: the queue (and C's turn intent) is gone with the process.
+ session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ rendered = "".join(str(r["content"]) for r in _active_rows(db, key))
+ assert "prompt B QUEUED-B" in rendered and "prompt C QUEUED-C" in rendered # durable, both kept
+ assert rendered.index("prompt B QUEUED-B") < rendered.index("prompt C QUEUED-C"), \
+ "a later-accepted prompt rendered before an earlier one after a partial drain"
+ 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 258aac47851..95909546529 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -315,7 +315,7 @@ def _persist_queued_user_row(session: dict, envelope: dict, display_kind: str |
envelope["_queued_display_kind"] = display_kind
-def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> None:
+def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> 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
@@ -328,13 +328,13 @@ def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> None:
"""
early = queued.get("_submit_user_row")
if not (isinstance(early, dict) and isinstance(early.get("_row_id"), int)):
- return # no accept-time row (write failed / pre-feature envelope): the turn persists as before
+ 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"))
fresh = session.get("_submit_user_row")
if not (isinstance(fresh, dict) and isinstance(fresh.get("_row_id"), int)):
- return # re-append wrote nothing: keep the accept-time row active
+ return None # re-append wrote nothing: keep the accept-time row active
queued["_submit_user_row"] = fresh # the envelope follows the live row (a retry drains cleanly)
with _session_db(session) as db:
if db is None:
@@ -345,6 +345,7 @@ def _replace_queued_user_row_for_turn(session: dict, queued: dict) -> None:
# Both rows briefly active merges in projection but never loses the message; deleting or
# losing text would be worse.
logger.debug("queued-prompt row re-placement deactivate failed", exc_info=True)
+ return fresh
def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False,
@@ -431,11 +432,24 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
kwargs: dict = {"queued_prompt_generation": queue_generation}
if queued.get("image_paths"):
kwargs["image_paths"] = queued["image_paths"]
- # Re-place the accept-time row (if any) at the transcript END before the turn's rows follow it,
- # and slot the fresh row for adoption. Under history_lock so a concurrent submit can't interleave
+ # Re-place the accept-time rows (if any) at the transcript END before the turn's rows follow
+ # them, and slot the dispatching envelope's fresh row for adoption. EVERY queued envelope is
+ # re-placed in acceptance order: a later-accepted prompt's row must never sit behind while an
+ # earlier one heals past it, or a crash between drains would permanently render the later
+ # 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"]:
- _replace_queued_user_row_for_turn(session, queued)
+ dispatch_row = _replace_queued_user_row_for_turn(session, queued)
+ still_queued = (([session["queued_prompt"]] if session.get("queued_prompt") else [])
+ + list(session.get("queued_prompts") or []))
+ for envelope in still_queued:
+ _replace_queued_user_row_for_turn(session, envelope)
+ # The single adoption slot must hold the DISPATCHING envelope's row (the loop above leaves
+ # the last processed one there) or the turn would adopt the wrong prompt's row.
+ if dispatch_row is not None:
+ session["_submit_user_row"] = dispatch_row
+ else:
+ session.pop("_submit_user_row", None)
# The compute-host frame has no author field, so only the inline runner receives it.
author_kwargs = {"turn_author": queued["turn_author"]} if queued.get("turn_author") else {}
dispatch_failed = False
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index c26a1649138..c95a0d84892 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -345,7 +345,7 @@ 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):
+def _write_submit_user_row(session: dict, text: Any, display_kind: str | 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