fix(tui_gateway): retain failed turns as replayable inflight snapshots

A turn that ended in error cleared inflight_turn and emitted its terminal
frame in the same breath. If the client was disconnected during that window
(the exact case for a failure like a network drop), the frame went to the
detached drop-transport and the in-memory state was already gone — the
desktop reconnected to a session with no trace of the failure.

Failed turns now retain a compact error snapshot (user prompt, partial
assistant text, error, recoverable) that session.resume's inflight payload
carries to a reconnecting client. Covers all three loss sites: the
returned-error result path, the turn exception path (which now closes with
the same status:"error" message.complete frame shape instead of a bare
error event), and agent-init failure. The snapshot lives until the next
turn starts or the session closes; _run_prompt_submit replaces a retained
error leftover instead of appending onto it.

Co-authored-by: Reza Sayar <rsayar@uvic.ca>
This commit is contained in:
Brooklyn Nicholson 2026-07-24 23:31:49 -05:00
parent ca35663013
commit 57b351d368
2 changed files with 414 additions and 14 deletions

View file

@ -0,0 +1,291 @@
"""Failed turns must retain a replayable ``inflight`` snapshot.
A turn that ended in error used to clear ``inflight_turn`` and emit its
terminal frame in the same breath. If the client was disconnected during that
window, the frame went to the detached drop-transport and the in-memory state
was already gone — the desktop reconnected to a session with no trace of the
failure (stuck spinner or a silently missing turn).
Contract pinned here:
* ``_fail_inflight_turn`` keeps the user prompt, partial assistant text, and
error semantics; ``_inflight_snapshot`` exposes status/error/recoverable.
* The returned-error path (``run_conversation()`` returning ``error``) retains
the snapshot — not just the exception path.
* The exception path closes the turn with a terminal ``message.complete``
(``status: "error"``, same shape as the returned-error path) instead of a
bare ``error`` event.
* ``session.resume``'s live payload carries the retained snapshot.
* A retained failure never leaks into the next turn's inflight state.
"""
from __future__ import annotations
import threading
import types
import pytest
from tui_gateway import server
class _InlineThread:
"""Run the turn synchronously so tests observe its final state."""
def __init__(self, target=None, daemon=None, args=(), kwargs=None):
self._target = target
self._args = args
self._kwargs = kwargs or {}
def start(self):
if self._target is not None:
self._target(*self._args, **self._kwargs)
def is_alive(self):
return False
def join(self, timeout=None):
return None
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": False,
"attached_images": [],
"image_counter": 0,
"cols": 80,
"slash_worker": None,
"show_reasoning": False,
"tool_progress_mode": "all",
"inflight_turn": None,
**extra,
}
@pytest.fixture()
def emits(monkeypatch):
captured: list = []
monkeypatch.setattr(
server,
"_emit",
lambda event, sid, payload=None: captured.append((event, sid, payload)),
)
return captured
@pytest.fixture()
def turn_env(monkeypatch, tmp_path):
"""Neutralize the turn pipeline's environment-heavy side paths."""
monkeypatch.setattr(server.threading, "Thread", _InlineThread)
monkeypatch.setattr(server, "_wire_callbacks", lambda sid: None)
monkeypatch.setattr(server, "_sync_agent_model_with_config", lambda sid, session: None)
monkeypatch.setattr(server, "_session_cwd", lambda session: str(tmp_path))
monkeypatch.setattr(server, "_register_session_cwd", lambda session: None)
monkeypatch.setattr(server, "_tts_stream_begin", lambda: None)
monkeypatch.setattr(server, "_sync_session_key_after_compress", lambda *a, **k: None)
monkeypatch.setattr(server, "_get_usage", lambda agent: {})
def _events(captured, name):
return [payload for event, _sid, payload in captured if event == name]
# ── Unit: retention helpers ───────────────────────────────────────────
def test_fail_inflight_turn_retains_partial_and_error():
session = _session()
server._start_inflight_turn(session, "do the thing")
server._append_inflight_delta(session, "partial answer")
server._fail_inflight_turn(session, RuntimeError("provider exploded"))
snapshot = server._inflight_snapshot(session)
assert snapshot is not None
assert snapshot["user"] == "do the thing"
assert snapshot["assistant"] == "partial answer"
assert snapshot["streaming"] is False
assert snapshot["error"] == "provider exploded"
assert snapshot["status"] == "error"
assert snapshot["recoverable"] is True
def test_snapshot_returned_for_error_only_turn():
"""An init failure has no user/assistant text yet — the error alone must
survive the emptiness check, or resume shows nothing."""
session = _session()
server._fail_inflight_turn(session, "agent initialization failed")
snapshot = server._inflight_snapshot(session)
assert snapshot is not None
assert snapshot["error"] == "agent initialization failed"
def test_healthy_snapshot_carries_no_error_keys():
session = _session()
server._start_inflight_turn(session, "hi")
server._append_inflight_delta(session, "hello")
snapshot = server._inflight_snapshot(session)
assert snapshot == {"assistant": "hello", "streaming": True, "user": "hi"}
# ── Returned-error path (run_conversation returns an error result) ────
def test_returned_error_result_retains_snapshot_and_emits_terminal_frame(
emits, turn_env
):
agent = types.SimpleNamespace(
session_id="session-key",
run_conversation=lambda *a, **k: {
"final_response": "",
"error": "provider 402: billing wall",
"failed": True,
},
clear_interrupt=lambda: None,
)
session = _session(agent=agent, running=True)
server._start_inflight_turn(session, "do the thing")
server._run_prompt_submit("rid", "sid", session, "do the thing")
completes = _events(emits, "message.complete")
assert len(completes) == 1
payload = completes[0]
assert payload["status"] == "error"
assert payload["error"] == "provider 402: billing wall"
assert payload["recoverable"] is True
# The retained snapshot survives the finally block for resume replay.
snapshot = server._inflight_snapshot(session)
assert snapshot is not None
assert snapshot["status"] == "error"
assert snapshot["error"] == "provider 402: billing wall"
assert snapshot["user"] == "do the thing"
assert session["running"] is False
def test_completed_turn_still_clears_inflight(emits, turn_env):
agent = types.SimpleNamespace(
session_id="session-key",
run_conversation=lambda *a, **k: {"final_response": "all done"},
clear_interrupt=lambda: None,
)
session = _session(agent=agent, running=True)
server._start_inflight_turn(session, "do the thing")
server._run_prompt_submit("rid", "sid", session, "do the thing")
completes = _events(emits, "message.complete")
assert len(completes) == 1
assert completes[0]["status"] == "complete"
assert "error" not in completes[0]
assert server._inflight_snapshot(session) is None
# ── Exception path ─────────────────────────────────────────────────────
def test_exception_closes_turn_with_terminal_complete_and_partial(emits, turn_env):
def _boom(message, stream_callback=None, **kwargs):
if stream_callback is not None:
stream_callback("half an ans")
raise RuntimeError("connection reset mid-stream")
agent = types.SimpleNamespace(
session_id="session-key",
run_conversation=_boom,
clear_interrupt=lambda: None,
)
session = _session(agent=agent, running=True)
server._start_inflight_turn(session, "do the thing")
server._run_prompt_submit("rid", "sid", session, "do the thing")
# Terminal frame, not a bare error event.
assert not _events(emits, "error")
completes = _events(emits, "message.complete")
assert len(completes) == 1
payload = completes[0]
assert payload["status"] == "error"
assert payload["error"] == "connection reset mid-stream"
assert payload["recoverable"] is True
assert payload["partial"] is True
assert payload["text"] == "half an ans"
snapshot = server._inflight_snapshot(session)
assert snapshot is not None
assert snapshot["assistant"] == "half an ans"
assert snapshot["error"] == "connection reset mid-stream"
assert session["running"] is False
# ── Resume replay (the reason retention exists) ───────────────────────
def test_live_session_payload_exposes_retained_failure(emits, turn_env, monkeypatch):
agent = types.SimpleNamespace(
session_id="session-key",
run_conversation=lambda *a, **k: {
"final_response": "",
"error": "budget exhausted",
"failed": True,
},
clear_interrupt=lambda: None,
)
session = _session(agent=agent, running=True)
server._start_inflight_turn(session, "long job")
server._run_prompt_submit("rid", "sid", session, "long job")
# What session.resume's live fast path hands a reconnecting client.
monkeypatch.setattr(server, "_get_db", lambda: None)
payload = server._live_session_payload("sid", session)
assert payload["running"] is False
inflight = payload.get("inflight")
assert inflight is not None
assert inflight["status"] == "error"
assert inflight["error"] == "budget exhausted"
assert inflight["user"] == "long job"
# ── Retained failure must not leak into the next turn ─────────────────
def test_next_turn_replaces_retained_error_snapshot(emits, turn_env):
seen_inflight_user: list = []
def _run_ok(message, **kwargs):
# Capture what the inflight turn looks like while the new turn runs.
turn = server._inflight_snapshot(_run_ok.session)
seen_inflight_user.append(turn and turn["user"])
return {"final_response": "fresh answer"}
agent = types.SimpleNamespace(
session_id="session-key",
run_conversation=_run_ok,
clear_interrupt=lambda: None,
)
session = _session(agent=agent, running=True)
_run_ok.session = session
# Leftover retained failure from a previous turn.
server._start_inflight_turn(session, "old failed prompt")
server._fail_inflight_turn(session, "previous turn failed")
server._run_prompt_submit("rid", "sid", session, "new prompt")
# The new turn must have started a fresh inflight turn, not inherited the
# failed one (the retained dict used to satisfy the isinstance guard).
assert seen_inflight_user == ["new prompt"]
snapshot = server._inflight_snapshot(session)
assert snapshot is None
completes = _events(emits, "message.complete")
assert len(completes) == 1
assert completes[0]["status"] == "complete"

View file

@ -6114,6 +6114,35 @@ def _clear_inflight_turn(session: dict) -> None:
session["inflight_turn"] = None
def _fail_inflight_turn(session: dict, error: Any) -> None:
"""Mark the in-flight turn terminal-error but keep it replayable.
Normal completion clears ``inflight_turn`` because the response is now in
canonical history. Failures are different: the terminal frame can be lost
on a WS disconnect, and the failed turn may never have been committed.
Retaining a compact error snapshot lets ``session.resume`` replay the
user's prompt, any partial assistant text, and the error itself instead of
leaving the client stranded on a spinner or hydrating from stale DB state.
The snapshot lives until the next turn starts (``_start_inflight_turn``
overwrites it) or the session closes.
Caller must hold ``session["history_lock"]``.
"""
message = str(error) if not isinstance(error, BaseException) else (str(error) or type(error).__name__)
now = time.time()
turn = session.get("inflight_turn")
if not isinstance(turn, dict):
turn = {"assistant": "", "user": "", "started_at": now}
turn["assistant"] = str(turn.get("assistant") or "")
turn["user"] = str(turn.get("user") or "")
turn["error"] = message or "turn failed"
turn["status"] = "error"
turn["recoverable"] = True
turn["streaming"] = False
turn["updated_at"] = now
session["inflight_turn"] = turn
def _enqueue_prompt(session: dict, text: Any, transport: Any) -> None:
"""Stash a message to run as the very next turn once the live one ends.
@ -6278,13 +6307,57 @@ def _inflight_snapshot(session: dict) -> dict | None:
user = str(turn.get("user") or "").strip()
assistant = str(turn.get("assistant") or "")
streaming = bool(turn.get("streaming"))
if not user and not assistant and not streaming:
error = str(turn.get("error") or "").strip()
if not user and not assistant and not streaming and not error:
return None
return {
snapshot = {
"assistant": assistant,
"streaming": streaming,
"user": user,
}
if error:
# Retained failed turn (see _fail_inflight_turn): carry the error
# semantics so a resuming client can rebuild the failed-turn bubble
# instead of rendering the partial text as a healthy reply.
snapshot["error"] = error
snapshot["status"] = str(turn.get("status") or "error")
snapshot["recoverable"] = bool(turn.get("recoverable"))
return snapshot
def _emit_terminal_turn_error(sid: str, session: dict, error: Any) -> None:
"""Close a failed turn with a terminal ``message.complete`` frame.
Emits the same ``status: "error"`` frame shape the returned-error path in
``_run_prompt_submit`` already produces (so TUI/desktop handling is
uniform), and retains the failed turn via ``_fail_inflight_turn`` so a
client that missed this frame (disconnect window) can recover it from
``session.resume``'s ``inflight`` payload.
"""
with session["history_lock"]:
_fail_inflight_turn(session, error)
turn = session.get("inflight_turn") or {}
message = str(turn.get("error") or "turn failed")
partial = str(turn.get("assistant") or "")
cols = int(session.get("cols", 80))
text = partial or f"Error: {message}"
agent = session.get("agent")
payload = {
"text": text,
"usage": _get_usage(agent) if agent is not None else {},
"status": "error",
"error": message,
"recoverable": True,
}
if partial:
payload["partial"] = True
try:
rendered = render_message(text, cols)
except Exception:
rendered = ""
if rendered:
payload["rendered"] = rendered
_emit("message.complete", sid, payload)
def _queued_prompt_snapshot(session: dict) -> dict | None:
@ -10340,18 +10413,18 @@ def _(rid, params: dict) -> dict:
def run_after_agent_ready() -> None:
err = _wait_agent(session, rid)
if err:
_emit(
"error",
# Terminal frame + retained snapshot (not a bare "error" event +
# cleared inflight): if the client is disconnected right now, the
# retained snapshot is the only way resume can show this failure.
_emit_terminal_turn_error(
sid,
{
"message": (err.get("error") or {}).get(
"message", "agent initialization failed"
)
},
session,
(err.get("error") or {}).get("message", "agent initialization failed"),
)
with session["history_lock"]:
session["running"] = False
_clear_inflight_turn(session)
session["last_active"] = time.time()
_emit("session.info", sid, _session_info(session.get("agent"), session))
return
with session["history_lock"]:
if session.get("_turn_cancel_requested") or not session.get("running"):
@ -10852,7 +10925,10 @@ def _run_prompt_submit(
history_version = int(session.get("history_version", 0))
images = list(session.get("attached_images", []))
session["attached_images"] = []
if not isinstance(session.get("inflight_turn"), dict):
inflight = session.get("inflight_turn")
# A retained failed turn (see _fail_inflight_turn) is a stale leftover
# by the time a new turn starts — replace it, never append onto it.
if not isinstance(inflight, dict) or inflight.get("status") == "error":
_start_inflight_turn(session, text)
agent = session["agent"]
if hasattr(agent, "clear_interrupt"):
@ -10869,6 +10945,9 @@ def _run_prompt_submit(
goal_followup = None # set by the post-turn goal hook below
tts_queue = None # streaming-TTS feed for this turn (voice mode)
one_turn_restore = session.pop("one_turn_model_restore", None)
# True once a failed turn's snapshot was retained for resume replay —
# tells the finally below to skip the normal inflight clear.
turn_error_retained = False
try:
from tools.approval import (
reset_current_session_key,
@ -11195,7 +11274,23 @@ def _run_prompt_submit(
if rendered:
payload["rendered"] = rendered
with session["history_lock"]:
_clear_inflight_turn(session)
if status == "error":
# Returned-error result (provider 4xx, budget, etc.): retain
# the failed turn for resume replay instead of clearing it.
# If this terminal frame is lost to a disconnect, resume's
# inflight payload is the only carrier of the failure.
_fail_inflight_turn(
session,
result.get("error") if isinstance(result, dict) else raw,
)
turn_error_retained = True
else:
_clear_inflight_turn(session)
if status == "error":
payload["error"] = str(
(result.get("error") if isinstance(result, dict) else "") or raw
)
payload["recoverable"] = True
_emit("message.complete", sid, payload)
# ── /goal continuation (Ralph-style loop) ─────────────────
@ -11357,7 +11452,20 @@ def _run_prompt_submit(
print(
f"[gateway-turn] {type(e).__name__}: {e}", file=sys.stderr, flush=True
)
_emit("error", sid, {"message": str(e)})
try:
# Close the turn with the same terminal error frame shape as
# the returned-error path (uniform client handling), retaining
# the failed turn for resume replay.
_emit_terminal_turn_error(sid, session, e)
turn_error_retained = True
except Exception as emit_exc:
print(
f"[gateway-turn] terminal error emit failed: "
f"{type(emit_exc).__name__}: {emit_exc}",
file=sys.stderr,
flush=True,
)
_emit("error", sid, {"message": str(e)})
finally:
if tts_queue is not None:
tts_queue.put(None) # end-of-text sentinel — flush + finish speaking
@ -11383,7 +11491,8 @@ def _run_prompt_submit(
with session["history_lock"]:
session["running"] = False
session["last_active"] = time.time()
_clear_inflight_turn(session)
if not turn_error_retained:
_clear_inflight_turn(session)
_emit("session.info", sid, _session_info(agent, session))
# A user prompt that arrived mid-turn (interrupt + queue) wins over