The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tui): session_auto_continue — unify steer/redirect correction path, flatten queue scrub
Teknium46423af83725
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex 7c263d15579..d4313c21a38 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -12,11 +12,11 @@ from .method_ctx import HandlerRegistry, bind_module_registry = HandlerRegistry()-# A concluded turn (success, handled error, interrupt) clears its durable marker-# (turn_marker.py) in _run_prompt_submit's finally; only a process death leaves it-# behind, so a marker at session.resume proves the turn never finished AND the-# client never saw a terminal frame. Fresh: re-submit automatically (as the-# messaging gateway does). Stale: clear it and let the partial transcript speak.+# A concluded turn (success, handled error, interrupt) clears its durable marker (turn_marker.py)+# in _run_prompt_submit's finally; only a process death leaves it behind, so a marker at+# session.resume proves the turn never finished AND the client never saw a terminal frame. Fresh:+# re-submit automatically (as the messaging gateway does). Stale: clear it and let the partial+# transcript speak._AUTO_CONTINUE_ENABLED_DEFAULT = True_AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT = 15@@ -36,9 +36,7 @@ def _auto_continue_config() -> tuple[bool, float, int]:return (is_truthy_value(cfg.get("enabled"), default=_AUTO_CONTINUE_ENABLED_DEFAULT),max(0.0, minutes) * 60.0,- _coerce_int_config_value(- cfg.get("max_attempts"), _AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT, min_value=0- ),+ _coerce_int_config_value(cfg.get("max_attempts"), _AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT, min_value=0),)@@ -51,10 +49,10 @@ def _session_home(session: dict) -> Path:def _retire_turn_marker(session: dict, *keys: str) -> None:"""Drop the crash marker for a turn whose outcome is about to reach the client.- Called right before the terminal frame, not at turn-thread end: post-turn work- (titles, memory sync, goal hooks) outlives the client's answer, and quitting in- that window would leave a marker that re-runs a finished turn on next launch.- Extra ``keys`` cover a session_key that compression rotated mid-turn.+ Called right before the terminal frame, not at turn-thread end: post-turn work (titles, memory+ sync, goal hooks) outlives the client's answer, and quitting in that window would leave a marker+ that re-runs a finished turn on next launch. Extra ``keys`` cover a session_key that compression+ rotated mid-turn."""home = _session_home(session)for key in dict.fromkeys((*keys, str(session.get("session_key") or ""))):@@ -63,8 +61,8 @@ def _retire_turn_marker(session: dict, *keys: str) -> None:def _auto_continue_note(prompt: str) -> str:- # Same opening as the gateway's recovery notes (transcript tooling recognizes- # both). The prompt is embedded: a hard crash persists nothing else of the turn.+ # Same opening as the gateway's recovery notes (transcript tooling recognizes both). The prompt+ # is embedded: a hard crash persists nothing else of the turn.return (f"{_AUTO_CONTINUE_NOTE_PREFIX} — the app or its backend process ""stopped before the turn could finish. Some of the work may already "@@ -81,19 +79,22 @@ def _ac_release_turn(session: dict, *, unschedule: bool = False) -> None:session["_auto_continue_scheduled"] = False+def _ac_dispatch_failed(what: str, exc: BaseException) -> None:+ print(f"[tui_gateway] {what} dispatch failed: {type(exc).__name__}: {exc}", file=sys.stderr)++def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) -> dict | None:"""Kick off a continuation turn for a crash-interrupted session.- Called from session.resume's cold paths once the live record is registered.- Returns a descriptor for the resume payload when scheduled, else None. The turn- runs on a background thread after the deferred agent build via the normal- _run_prompt_submit path, so the client that just resumed streams it live.+ Called from session.resume's cold paths once the live record is registered. Returns a descriptor+ for the resume payload when scheduled, else None. The turn runs on a background thread after the+ deferred agent build via the normal _run_prompt_submit path, so the client that just resumed+ streams it live."""- # Hosted room turns are recovered by their durable task/lease state machine;- # generic auto-continue would bypass its execution generation and duplicate work.+ # Hosted room turns are recovered by their durable task/lease state machine; generic+ # auto-continue would bypass its execution generation and duplicate work.if session.get("source") == "bot_room":return None-home = _session_home(session)marker = read_turn_marker(home, session_key)if marker is None:@@ -129,17 +130,17 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->returnsession["running"] = Truesession["last_active"] = time.time()- # Ownership admission BEFORE message.start: a sibling backend sharing this- # HERMES_HOME may have written the marker and still be mid-turn. Leave the- # marker so a later resume retries once the owner finishes or dies.+ # Ownership admission BEFORE message.start: a sibling backend sharing this HERMES_HOME may+ # have written the marker and still be mid-turn. Leave the marker so a later resume retries+ # once the owner finishes or dies.if _ensure_active_session_slot(sid, session) is not None:logger.info("auto-continue for %s refused: session has another live owner", session_key)_ac_release_turn(session, unschedule=True)returnwith session["history_lock"]:- # Marker inputs read back by _run_prompt_submit: count the attempt (crash- # breaker) and re-record the ORIGINAL prompt (no nested notes). Set here,- # not at schedule time, so a bail above leaves nothing for a racing user turn.+ # Marker inputs read back by _run_prompt_submit: count the attempt (crash breaker) and+ # re-record the ORIGINAL prompt (no nested notes). Set here, not at schedule time, so a+ # bail above leaves nothing for a racing user turn.session["_auto_continue_attempt"] = attemptsession["_auto_continue_prompt"] = marker["prompt"]try:@@ -147,13 +148,12 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->_emit("message.start", sid)_run_prompt_submit(rid, sid, session, text, display_kind="auto_continue")except Exception as exc:- print(f"[tui_gateway] auto-continue dispatch failed: {type(exc).__name__}: {exc}", file=sys.stderr)+ _ac_dispatch_failed("auto-continue", exc)_ac_release_turn(session)threading.Thread(target=kickoff, daemon=True).start()logger.info(- "auto-continue scheduled for session %s (attempt %d, interrupted %.0fs ago)",- session_key, attempt, age,+ "auto-continue scheduled for session %s (attempt %d, interrupted %.0fs ago)", session_key, attempt, age)return {"attempt": attempt, "interrupted_at": marker["started_at"]}@@ -161,10 +161,10 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->def _enqueue_prompt(session: dict, text: Any, transport: Any, image_paths: list[str] | None = None) -> None:"""Stash a message to run as the very next turn once the live one ends.- Text-only arrivals share a slot and merge losslessly (like the consecutive-user- merge in ``repair_message_sequence``); image-bearing ones stay separate envelopes- so attachment ownership/chronology survive. ``transport`` is pinned so the drained- turn streams back to its sender even if the session transport is rebound.+ Text-only arrivals share a slot and merge losslessly (like the consecutive-user merge in+ ``repair_message_sequence``); image-bearing ones stay separate envelopes so attachment+ ownership/chronology survive. ``transport`` is pinned so the drained turn streams back to its+ sender even if the session transport is rebound."""image_paths = list(image_paths or [])# Scrub live-turn self-duplicates first so the text merge below can't glue@@ -173,7 +173,7 @@ def _enqueue_prompt(session: dict, text: Any, transport: Any, image_paths: list[# Never queue a text-only self-copy of the live prompt: draining it would restart it.if not image_paths and isinstance(text, str):turn = session.get("inflight_turn")- original = (str(turn.get("user") or "").strip() if isinstance(turn, dict) else "")+ original = str(turn.get("user") or "").strip() if isinstance(turn, dict) else ""if original and text.strip() == original:returnqueued = {"text": text, "transport": transport}@@ -181,35 +181,28 @@ def _enqueue_prompt(session: dict, text: Any, transport: Any, image_paths: list[queued["image_paths"] = image_pathsexisting = session.get("queued_prompt")if (- existing- and isinstance(existing.get("text"), str)- and isinstance(text, str)- and not existing.get("image_paths")- and not image_paths- and not session.get("queued_prompts")+ existing and isinstance(existing.get("text"), str) and isinstance(text, str)+ and not existing.get("image_paths") and not image_paths and not session.get("queued_prompts")):prev = existing["text"]existing["text"] = f"{prev}\n\n{text}" if prev and text else (prev or text)- return- if existing:+ elif existing:session.setdefault("queued_prompts", []).append(queued)- return- session["queued_prompt"] = queued+ else:+ session["queued_prompt"] = queueddef _sanitize_queued_entry_vs_inflight_user(entry: Any, original: str) -> dict | None:"""Drop (``None``) or rewrite a queue envelope that re-carries the live user text.- Text-only self-duplicates are dropped; a merged slot ``"{original}\\n\\n{later}"``- is rewritten to ``later`` so the correction survives without re-firing the- original. Image-bearing envelopes are left alone (chronology is load-bearing).+ Text-only self-duplicates are dropped; a merged slot ``"{original}\\n\\n{later}"`` is rewritten+ to ``later`` so the correction survives without re-firing the original. Image-bearing envelopes+ are left alone (chronology is load-bearing)."""- if not original or not isinstance(entry, dict):- return entry if isinstance(entry, dict) else None- if entry.get("image_paths"):- return entry+ if not isinstance(entry, dict):+ return Nonetext = entry.get("text")- if not isinstance(text, str):+ if not original or entry.get("image_paths") or not isinstance(text, str):return entrystripped = text.strip()if not stripped or stripped == original:@@ -219,35 +212,25 @@ def _sanitize_queued_entry_vs_inflight_user(entry: Any, original: str) -> dict |prefix = original + sepif text.startswith(prefix):rest = text[len(prefix) :].strip()- if not rest or rest == original:- return None- return {**entry, "text": rest}+ return None if not rest or rest == original else {**entry, "text": rest}return entrydef _drop_queued_duplicates_of_inflight_user(session: dict) -> None:"""Remove server-queue copies of the live turn's original user text.- A mid-turn ``prompt.submit`` of the same text can be queued while redirect is- unavailable (build window, tool boundary); after a later redirect it must not- drain and restart the original as a fresh turn. Unrelated follow-ups stay.+ A mid-turn ``prompt.submit`` of the same text can be queued while redirect is unavailable+ (build window, tool boundary); after a later redirect it must not drain and restart the original+ as a fresh turn. Unrelated follow-ups stay."""turn = session.get("inflight_turn")- if not isinstance(turn, dict):- return- original = str(turn.get("user") or "").strip()+ original = str(turn.get("user") or "").strip() if isinstance(turn, dict) else ""if not original:return-head = session.get("queued_prompt")- rest = list(session.get("queued_prompts") or [])- kept: list[dict] = []- for entry in ([head] if head else []) + rest:- cleaned = _sanitize_queued_entry_vs_inflight_user(entry, original)- if cleaned is not None:- kept.append(cleaned)-- _ac_set_queue(session, kept)+ entries = ([head] if head else []) + list(session.get("queued_prompts") or [])+ cleaned = (_sanitize_queued_entry_vs_inflight_user(entry, original) for entry in entries)+ _ac_set_queue(session, [c for c in cleaned if c is not None])def _ac_set_queue(session: dict, entries: list) -> None:@@ -262,15 +245,13 @@ def _ac_set_queue(session: dict, entries: list) -> None:def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:"""Interrupt a busy turn on a worker thread, never under ``history_lock``.- Some providers can't apply ``interrupt()`` until a blocking tool/network call- returns; doing it inline stalled ``session.resume`` and the queued prompt.- At most one interrupt worker per session so repeated steering can't leak threads.+ Some providers can't apply ``interrupt()`` until a blocking tool/network call returns; doing it+ inline stalled ``session.resume`` and the queued prompt. At most one interrupt worker per session+ so repeated steering can't leak threads."""use_agent = agent is not None and hasattr(agent, "interrupt")- use_compute_host = not use_agent and _session_uses_compute_host(session)- if not use_agent and not use_compute_host:+ if not use_agent and not _session_uses_compute_host(session):return-with session["history_lock"]:if session.get("_busy_interrupt_pending"):return@@ -291,27 +272,31 @@ def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:threading.Thread(target=interrupt, daemon=True, name=f"busy-interrupt-{sid}").start()-def _ac_record_inflight_correction(session: dict, plain_text: str) -> None:- """Record an accepted steer/redirect; scrub stale self-duplicates so the- live turn's original text is not re-fired from the queue after settle."""+def _ac_try_correction(rid, session: dict, agent: Any, method: str, plain_text: str, status: str) -> dict | None:+ """Apply ``agent.<method>(plain_text)`` (steer/redirect); on acceptance record the correction, scrub+ stale self-duplicates so the live turn's original text is not re-fired after settle, and return+ the ``status`` reply. None → caller falls through to the queue path."""+ try:+ if not getattr(agent, method)(plain_text):+ return None+ except Exception:+ return Nonewith session["history_lock"]:_record_inflight_correction(session, plain_text)_drop_queued_duplicates_of_inflight_user(session)session["last_active"] = time.time()+ return _ok(rid, {"status": status})-def _handle_busy_submit(- rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False-) -> dict | None:- """Apply ``display.busy_input_mode`` to a prompt that lands mid-turn instead of- rejecting it with ``session busy`` (rejection made clients busy-retry and- silently drop sends when teardown outlived their deadline).+def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False) -> dict | None:+ """Apply ``display.busy_input_mode`` to a prompt that lands mid-turn instead of rejecting it with+ ``session busy`` (rejection made clients busy-retry and silently drop sends when teardown+ outlived their deadline).- Modes: ``interrupt`` (default) → redirect the live turn, falling back to hard- interrupt + queue for older agents; ``queue`` → queue only; ``steer`` → inject- after the current atomic action. ``queued=True`` (client queue drain) forces- queue mode: a "run after" message must NEVER become a live-turn correction,- even when the drain loses the settle race against a still-unwinding turn.+ Modes: ``interrupt`` (default) → redirect the live turn, falling back to hard interrupt + queue+ for older agents; ``queue`` → queue only; ``steer`` → inject after the current atomic action.+ ``queued=True`` (client queue drain) forces queue mode: a "run after" message must NEVER become a+ live-turn correction, even when the drain loses the settle race against a still-unwinding turn."""mode = "queue" if queued else _load_busy_input_mode()agent = session.get("agent")@@ -325,31 +310,23 @@ def _handle_busy_submit(session["attached_images"] = []text_only = not image_paths and _is_text_only_busy_payload(text)plain_text = _coerce_message_text(text).strip() if text_only else ""- if mode == "steer" and text_only and plain_text and agent is not None and hasattr(agent, "steer"):- try:- if agent.steer(plain_text):- _ac_record_inflight_correction(session, plain_text)- return _ok(rid, {"status": "steered"})- except Exception:- pass # fall through to queue- # Text-only corrections redirect in place when supported; media payloads and- # older agents fall through to the proven interrupt + queue path.- if (- mode == "interrupt"- and text_only- and plain_text- and agent is not None- and getattr(agent, "_supports_active_turn_redirect", False) is True- and hasattr(agent, "redirect")- ):- try:- if agent.redirect(plain_text):- _ac_record_inflight_correction(session, plain_text)- return _ok(rid, {"status": "redirected"})- except Exception:- pass # preserve the proven interrupt + queue fallback below- # Queue before asking the live turn to stop. Never call a provider/compute-host- # method under history_lock: an interrupt can wait behind the op it cancels.+ if plain_text and agent is not None:+ if mode == "steer" and hasattr(agent, "steer"):+ resp = _ac_try_correction(rid, session, agent, "steer", plain_text, "steered")+ if resp is not None:+ return resp+ # Text-only corrections redirect in place when supported; media payloads and older agents+ # fall through to the proven interrupt + queue path.+ if (+ mode == "interrupt"+ and getattr(agent, "_supports_active_turn_redirect", False) is True+ and hasattr(agent, "redirect")+ ):+ resp = _ac_try_correction(rid, session, agent, "redirect", plain_text, "redirected")+ if resp is not None:+ return resp+ # Queue before asking the live turn to stop. Never call a provider/compute-host method under+ # history_lock: an interrupt can wait behind the op it cancels.with session["history_lock"]:if not session.get("running"):if image_paths:@@ -357,11 +334,10 @@ def _handle_busy_submit(return None_enqueue_prompt(session, text, transport, image_paths=image_paths)session["last_active"] = time.time()-- # Attachments need their own model invocation: queue without cancelling so the- # user gets both results in order. ``steer`` must NEVER escalate to a hard- # interrupt: it would kill the live turn AND drop ``AIAgent._pending_steer``,- # destroying earlier accepted steers; steer fall-throughs stay FIFO-queued.+ # Attachments need their own model invocation: queue without cancelling so the user gets both+ # results in order. ``steer`` must NEVER escalate to a hard interrupt: it would kill the live+ # turn AND drop ``AIAgent._pending_steer``, destroying earlier accepted steers; steer+ # fall-throughs stay FIFO-queued.if mode == "interrupt" and not image_paths:_interrupt_busy_session(sid, session, agent)return _ok(rid, {"status": "queued"})@@ -370,8 +346,8 @@ def _handle_busy_submit(def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:"""Fire a queued next-turn prompt if one is waiting and the session is idle.- True when dispatched: the caller skips lower-priority follow-ups this cycle- (the user's message wins). Claim-under-lock like the goal-continuation re-fire.+ True when dispatched: the caller skips lower-priority follow-ups this cycle (the user's message+ wins). Claim-under-lock like the goal-continuation re-fire."""with session["history_lock"]:if session.get("_closing"):@@ -390,15 +366,11 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:use_compute_host = _session_uses_compute_host(session)with session["history_lock"]:if int(session.get("_queued_prompt_generation", 0)) != queue_generation:- # Generation bump cancelled the claim (Stop, compress re-anchor, …): don't- # dispatch, but restore the envelope (claimed head first, then whatever- # advanced into the slot) so a legitimate follow-up isn't dropped.- rest: list = []+ # Generation bump cancelled the claim (Stop, compress re-anchor, …): don't dispatch, but+ # restore the envelope (claimed head first, then whatever advanced into the slot) so a+ # legitimate follow-up isn't dropped.advanced = session.get("queued_prompt")- if advanced:- rest.append(advanced)- rest.extend(session.get("queued_prompts") or [])- _ac_set_queue(session, [queued, *rest])+ _ac_set_queue(session, [queued, *([advanced] if advanced else []), *(session.get("queued_prompts") or [])])session["running"] = Falsereturn Truekwargs: dict = {"queued_prompt_generation": queue_generation}@@ -418,7 +390,7 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:else:_run_prompt_submit(rid, sid, session, queued["text"], **kwargs)except Exception as exc:- print(f"[tui_gateway] queued prompt dispatch failed: {type(exc).__name__}: {exc}", file=sys.stderr)+ _ac_dispatch_failed("queued prompt", exc)_ac_release_turn(session)dispatch_failed = Trueif dispatch_failed:@@ -440,23 +412,20 @@ def _inflight_snapshot(session: dict) -> dict | None:if not user and not assistant and not streaming and not error:return Nonesnapshot = {"assistant": assistant, "streaming": streaming, "user": user}- raw_corrections = turn.get("corrections") or []raw_offsets = turn.get("correction_offsets") or []correction_pairs = [(str(c), raw_offsets[i] if i < len(raw_offsets) else None)- for i, c in enumerate(raw_corrections)- if str(c).strip()+ for i, c in enumerate(turn.get("corrections") or []) if str(c).strip()]if correction_pairs:- # Mid-turn redirects alongside (not over) the original prompt so resume can- # rebuild every user bubble; offsets only when every correction has one so- # clients can trust the pairing.+ # Mid-turn redirects alongside (not over) the original prompt so resume can rebuild every+ # user bubble; offsets only when every correction has one so clients can trust the pairing.snapshot["corrections"] = [c for c, _ in correction_pairs]if all(isinstance(offset, int) and offset >= 0 for _, offset in correction_pairs):snapshot["correction_offsets"] = [int(offset) for _, offset in correction_pairs] # type: ignore[arg-type]if error:- # Retained failed turn (_fail_inflight_turn): a resuming client must rebuild- # the failed bubble, not render the partial text as a healthy reply.+ # Retained failed turn (_fail_inflight_turn): a resuming client must rebuild the failed+ # bubble, not render the partial text as a healthy reply.snapshot["error"] = errorsnapshot["status"] = str(turn.get("status") or "error")snapshot["recoverable"] = bool(turn.get("recoverable"))@@ -469,23 +438,21 @@ def _inflight_snapshot(session: dict) -> dict | None:def _emit_terminal_turn_error(sid: str, session: dict, error: Any, error_surface: Optional[dict] = None, *, retire_marker: bool = True) -> None:- """Close a failed turn with the same ``status: "error"`` ``message.complete``- frame as ``_run_prompt_submit``'s returned-error path, retaining the turn via- ``_fail_inflight_turn`` so a client that missed the frame recovers it from- ``session.resume``'s ``inflight``. Callers that know the failing layer pass- ``error_surface``; exception callers leave it None and it is classified here.+ """Close a failed turn with the same ``status: "error"`` ``message.complete`` frame as+ ``_run_prompt_submit``'s returned-error path, retaining the turn via ``_fail_inflight_turn`` so a+ client that missed the frame recovers it from ``session.resume``'s ``inflight``. Callers that+ know the failing layer pass ``error_surface``; exception callers leave it None and it is+ classified here."""agent = session.get("agent")- # {layer, code, retryable} descriptor so the desktop can say "Provider error" /- # "Gateway error" with matching recovery actions. Advisory: never raises.+ # {layer, code, retryable} descriptor so the desktop can say "Provider error" / "Gateway error"+ # with matching recovery actions. Advisory: never raises.if error_surface is None and isinstance(error, BaseException):try:from agent.error_surface import build_error_surface_from_exceptionerror_surface = build_error_surface_from_exception(- error,- provider=str(getattr(agent, "provider", "") or ""),- model=str(getattr(agent, "model", "") or ""),+ error, provider=str(getattr(agent, "provider", "") or ""), model=str(getattr(agent, "model", "") or ""))except Exception:error_surface = None@@ -519,9 +486,8 @@ def _emit_terminal_turn_error(def _restore_agent_history_after_turn_error(session: dict, agent) -> bool:- """Keep a failed turn's working transcript: ``AIAgent`` persists its messages- independently, so after a raise the next prompt must see them, not the- pre-turn snapshot."""+ """Keep a failed turn's working transcript: ``AIAgent`` persists its messages independently, so+ after a raise the next prompt must see them, not the pre-turn snapshot."""agent_messages = getattr(agent, "_session_messages", None)if not isinstance(agent_messages, list):return False@@ -532,8 +498,8 @@ def _restore_agent_history_after_turn_error(session: dict, agent) -> bool:def _queued_prompt_snapshot(session: dict) -> dict | None:- """The accepted next-turn prompt without its transport handle, for the- live-session projection (Desktop may reconnect while it is still queued)."""+ """The accepted next-turn prompt without its transport handle, for the live-session projection+ (Desktop may reconnect while it is still queued)."""queued = session.get("queued_prompt")if not isinstance(queued, dict):return None