Skip to content

The agent that grows with you

fix(tui-gateway): queue busy-mode follow-ups while compression is in flight

Austin Picketta6578fcaa5b6
diff --git a/tests/tui_gateway/test_busy_compression_demotion.py b/tests/tui_gateway/test_busy_compression_demotion.py
new file mode 100644
index 00000000000..295b81f6252
--- /dev/null
+++ b/tests/tui_gateway/test_busy_compression_demotion.py
@@ -0,0 +1,173 @@
+"""Compression in flight demotes busy-mode steer/interrupt to queue (#61042).
+
+A follow-up delivered to the provider mid-compression aborts the compression
+(``explicit_interrupt``) — the user's message kills the turn that would have
+answered it. The channel-side busy path already demoted interrupt→queue for
+this reason (gateway/run_busy.py, #56391); these tests pin the same contract
+for the local RPC busy path (prompt.submit / session.steer / session.redirect)
+so TUI, Desktop and classic chat share the Discord-gateway behavior: the
+follow-up queues and drains when compression finishes.
+"""
+
+from __future__ import annotations
+
+import threading
+import types
+
+from tui_gateway import server
+
+
+def _session(agent=None, **extra):
+ return {
+ "agent": agent if agent is not None else types.SimpleNamespace(),
+ "session_key": "session-key",
+ "history": [],
+ "history_lock": threading.Lock(),
+ "history_version": 0,
+ "running": True,
+ "transport": None,
+ "attached_images": [],
+ **extra,
+ }
+
+
+# ── _session_compression_in_flight ────────────────────────────────────────
+
+def _patch_db(monkeypatch, holder):
+ class _Db:
+ def get_compression_lock_holder(self, sid):
+ return holder
+
+ import contextlib
+
+ @contextlib.contextmanager
+ def _fake_db(session):
+ yield _Db()
+
+ monkeypatch.setattr(server, "_session_db", _fake_db)
+
+
+def test_compression_in_flight_true_when_lock_held(monkeypatch):
+ _patch_db(monkeypatch, holder="compressor-1")
+ session = _session()
+ session["agent"].session_id = "session-key"
+
+ assert server._session_compression_in_flight(session) is True
+
+
+def test_compression_in_flight_false_when_lock_free(monkeypatch):
+ _patch_db(monkeypatch, holder=None)
+
+ assert server._session_compression_in_flight(_session()) is False
+
+
+def test_compression_in_flight_false_when_db_errors(monkeypatch):
+ import contextlib
+
+ @contextlib.contextmanager
+ def _boom(session):
+ raise RuntimeError("db gone")
+ yield # pragma: no cover
+
+ monkeypatch.setattr(server, "_session_db", _boom)
+
+ # A failed check must fail OPEN (no demotion): compression protection is
+ # best-effort here, unlike ownership which fails closed.
+ assert server._session_compression_in_flight(_session()) is False
+
+
+# ── _handle_busy_submit demotion ──────────────────────────────────────────
+
+def test_busy_interrupt_mode_queues_while_compressing(monkeypatch):
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: True)
+ seen = []
+
+ def _boom(text):
+ seen.append(text)
+ return True
+
+ agent = types.SimpleNamespace(_supports_active_turn_redirect=True, redirect=_boom)
+ session = _session(agent=agent)
+
+ resp = server._handle_busy_submit("r1", "sid", session, "follow-up", "ws-1")
+
+ assert resp["result"]["status"] == "queued"
+ assert seen == [] # never redirected — the compression survives
+ assert session["queued_prompt"]["text"] == "follow-up"
+
+
+def test_busy_steer_mode_queues_while_compressing(monkeypatch):
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "steer")
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: True)
+ seen = []
+ agent = types.SimpleNamespace(steer=lambda text: seen.append(text) or True)
+ session = _session(agent=agent)
+
+ resp = server._handle_busy_submit("r1", "sid", session, "follow-up", "ws-1")
+
+ assert resp["result"]["status"] == "queued"
+ assert seen == []
+ assert session["queued_prompt"]["text"] == "follow-up"
+
+
+def test_busy_interrupt_mode_still_redirects_without_compression(monkeypatch):
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: False)
+ seen = []
+ agent = types.SimpleNamespace(
+ _supports_active_turn_redirect=True,
+ redirect=lambda text: seen.append(text) or True,
+ )
+ session = _session(agent=agent)
+
+ resp = server._handle_busy_submit("r1", "sid", session, "correction", "ws-1")
+
+ assert resp["result"]["status"] == "redirected"
+ assert seen == ["correction"]
+
+
+def test_busy_queued_drain_forces_queue_regardless(monkeypatch):
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: False)
+ session = _session()
+ session["queued_prompt"] = {"text": "earlier", "transport": "ws-1"}
+
+ resp = server._handle_busy_submit("r1", "sid", session, "next", "ws-1", queued=True)
+
+ assert resp["result"]["status"] == "queued"
+
+
+# ── session.steer / session.redirect demotion ─────────────────────────────
+
+def test_session_steer_queues_while_compressing(monkeypatch):
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: True)
+ seen = []
+ agent = types.SimpleNamespace(steer=lambda text: seen.append(text) or True)
+ session = _session(agent=agent)
+ monkeypatch.setitem(server._sessions, "sid", session)
+ try:
+ resp = server.handle_request(
+ {"id": "r1", "method": "session.steer", "params": {"session_id": "sid", "text": "follow-up"}})
+ finally:
+ server._sessions.pop("sid", None)
+
+ assert resp["result"]["status"] == "queued"
+ assert seen == []
+ assert session["queued_prompt"]["text"] == "follow-up"
+
+
+def test_session_redirect_queues_while_compressing(monkeypatch):
+ monkeypatch.setattr(server, "_session_compression_in_flight", lambda session: True)
+ seen = []
+ agent = types.SimpleNamespace(_supports_active_turn_redirect=True, redirect=lambda t: seen.append(t) or True)
+ session = _session(agent=agent)
+ monkeypatch.setitem(server._sessions, "sid", session)
+ try:
+ resp = server.handle_request(
+ {"id": "r1", "method": "session.redirect", "params": {"session_id": "sid", "text": "follow-up"}})
+ finally:
+ server._sessions.pop("sid", None)
+
+ assert resp["result"]["status"] == "queued"
+ assert seen == []
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 60cfd9ec22d..a591a96b971 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -2210,6 +2210,15 @@ def _correction_method(name: str, verb: str, accepted_status: str, supported, un
_enqueue_prompt(session, text, current_transport() or _stdio_transport)
session["last_active"] = time.time()
return _ok(rid, {"status": "queued", "text": text})
+ # Compression in flight: queue instead of steering/redirecting. A correction that
+ # reaches the provider mid-compression aborts the compression (explicit_interrupt)
+ # — the follow-up kills the turn that would answer it (#61042). Queued here, it
+ # drains when compression finishes (the Discord-gateway contract; mirrors the
+ # interrupt→queue demotion in gateway/run_busy.py for the channel busy path).
+ if _session_compression_in_flight(session):
+ _enqueue_prompt(session, text, current_transport() or _stdio_transport)
+ session["last_active"] = time.time()
+ return _ok(rid, {"status": "queued", "text": text})
if not supported(agent):
return _err(rid, 4010, unsupported)
# An idle agent accepts steer() but only the next turn drains it, spliced after an old tool
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index 442038b0741..f4825f6c07e 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -245,6 +245,34 @@ def _ac_try_correction(rid, session: dict, agent: Any, method: str, plain_text:
return _ok(rid, {"status": status})
+def _session_compression_in_flight(session: dict) -> bool:
+ """True when a compression lock is held for this session's durable id.
+
+ Context compression is interrupt-protected (#23975), but a correction that reaches the
+ provider mid-compression still aborts it with ``explicit_interrupt`` — the user's
+ follow-up kills the very turn that would answer it (#61042). The channel-side busy
+ path demotes interrupt→queue for the same reason (gateway/run_busy.py
+ ``_session_has_compression_in_flight``, #56391); this is the local-RPC twin. Both
+ blocking reads run off the event loop so a large state.db never freezes the dispatcher.
+ """
+ agent = session.get("agent")
+ sid = str(getattr(agent, "session_id", "") or "") or str(session.get("session_key") or "")
+ if not sid:
+ return False
+ try:
+ with _session_db(session) as db:
+ get_holder = getattr(db, "get_compression_lock_holder", None)
+ if not callable(get_holder):
+ return False
+ holder = get_holder(sid)
+ except Exception:
+ logger.debug("compression in-flight check failed for session %s", sid, exc_info=True)
+ return False
+ # Production returns Optional[str]. Reject non-strings so a MagicMock auto-attr cannot
+ # look like a held lock and needlessly demote every submit (see #96953).
+ return isinstance(holder, str) and bool(holder)
+
+
def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False,
turn_author: dict | None = None) -> dict | None:
"""Apply ``display.busy_input_mode`` to a mid-turn prompt instead of rejecting it (rejection made clients busy-retry
@@ -253,6 +281,11 @@ def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any,
after" message must NEVER become a live correction."""
mode = "queue" if queued else _load_busy_input_mode()
agent = session.get("agent")
+ # Compression in flight demotes steer/interrupt to queue: a correction delivered
+ # mid-compression aborts the compression instead of waiting for it (#61042). The
+ # follow-up drains when compression finishes — the Discord-gateway contract.
+ if mode in ("steer", "interrupt") and _session_compression_in_flight(session):
+ mode = "queue"
with session["history_lock"]:
if not session.get("running"):
return None # turn ended since prompt.submit's busy check; caller retries on the idle session