Skip to content

The agent that grows with you

refactor(tui): drop unused HandlerRegistry seeds, compact payload/snapshot assembly

Teknium5d3c6754434e
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index 6fdfbcf3e85..494fbf5e285 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -5,9 +5,7 @@ busy-submit handling. Bodies are rebound onto server.py's globals at install tim
from __future__ import annotations
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
# 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
@@ -373,10 +371,8 @@ def _inflight_snapshot(session: dict) -> dict | None:
turn = session.get("inflight_turn")
if not isinstance(turn, dict):
return None
- user = str(turn.get("user") or "").strip()
- assistant = str(turn.get("assistant") or "")
- streaming = bool(turn.get("streaming"))
- error = str(turn.get("error") or "").strip()
+ user, assistant = str(turn.get("user") or "").strip(), str(turn.get("assistant") or "")
+ streaming, error = bool(turn.get("streaming")), str(turn.get("error") or "").strip()
if not user and not assistant and not streaming and not error:
return None
snapshot = {"assistant": assistant, "streaming": streaming, "user": user}
@@ -427,20 +423,16 @@ def _emit_terminal_turn_error(
partial = str(turn.get("assistant") or "")
cols = int(session.get("cols", 80))
text = partial or f"Error: {message}"
- payload = {
- "text": text, "usage": _get_usage(agent) if agent is not None else {}, "status": "error",
- "error": message, "recoverable": True,
- }
- if error_surface:
- payload["error_surface"] = error_surface
- if partial:
- payload["partial"] = True
try:
rendered = render_message(text, cols)
except Exception:
rendered = ""
- if rendered:
- payload["rendered"] = rendered
+ payload = {
+ "text": text, "usage": _get_usage(agent) if agent is not None else {}, "status": "error",
+ "error": message, "recoverable": True,
+ **({"error_surface": error_surface} if error_surface else {}),
+ **({"partial": True} if partial else {}), **({"rendered": rendered} if rendered else {}),
+ }
if retire_marker:
_retire_turn_marker(session)
_emit("message.complete", sid, payload)
diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.py
index f1ab7f606d9..668232f950f 100644
--- a/tui_gateway/session_compression.py
+++ b/tui_gateway/session_compression.py
@@ -9,9 +9,7 @@ from __future__ import annotations
import contextlib
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
def _tui_compression_config_signature(cfg: dict | None) -> tuple:
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index 5d6024c9755..5652220ae5b 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -7,9 +7,7 @@ from __future__ import annotations
import contextlib
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
def _notif_locked_sessions(fn, default):
@@ -530,11 +528,17 @@ def _async_delegation_display_metadata(evt: dict) -> dict:
return metadata
-def _wire_agent_terminal_output() -> None:
- """Idempotently route background-process output (`agent.terminal.output` chunks) and
- `process_registry.request_close_terminal` (`terminal.close`, drops a tab without killing the process)
- to the window owning the process (its gateway session), keyed by process id. `_emit` is
- `_stdout_lock`-guarded, so the registry's reader threads may call it."""
+_desktop_ui_wired = False
+
+
+def _wire_desktop_sinks() -> None:
+ """Idempotently wire process-registry and desktop-tool sinks to renderer events. Background-process
+ output (`agent.terminal.output` chunks) and `process_registry.request_close_terminal`
+ (`terminal.close`, drops a tab without killing the process) route to the window owning the process
+ (its gateway session), keyed by process id; desktop-only tools (open_preview, close_preview,
+ focus_pane) hand back the turn's ``HERMES_UI_SESSION_ID`` as ``sid`` so the event routes to the
+ window that asked. `_emit` is `_stdout_lock`-guarded, so registry reader / tool threads may call it."""
+ global _desktop_ui_wired
from tools.process_registry import process_registry
def _owner_sid_for_process(session) -> str:
@@ -553,24 +557,13 @@ def _wire_agent_terminal_output() -> None:
process_registry.on_close = lambda session, process_id: _emit(
"terminal.close", _owner_sid_for_process(session) if session is not None else "", {"process_id": process_id}
)
-
-
-_desktop_ui_wired = False
-
-
-def _wire_desktop_ui() -> None:
- """Bridge desktop-only tools (open_preview, close_preview, focus_pane) to renderer events. Idempotent.
- The tool hands back the turn's ``HERMES_UI_SESSION_ID`` as ``sid`` so the event routes to the window
- that asked (``_emit`` is ``_stdout_lock``-guarded; tool thread may call it)."""
- global _desktop_ui_wired
- if _desktop_ui_wired:
- return
- try:
- from tools import desktop_ui
- except Exception:
- return
- desktop_ui.set_emitter(lambda sid, event, payload: _emit(event, sid, payload))
- _desktop_ui_wired = True
+ if not _desktop_ui_wired:
+ try:
+ from tools import desktop_ui
+ except Exception:
+ return
+ desktop_ui.set_emitter(lambda sid, event, payload: _emit(event, sid, payload))
+ _desktop_ui_wired = True
# (stop_event, thread) for every poller started in this process, pruned of dead threads on each spawn.
@@ -581,8 +574,7 @@ _notification_pollers: list = []
def _start_notification_poller(sid: str, session: dict) -> threading.Event:
"""Start the background notification poller for a TUI session (thread name is greppable)."""
- _wire_agent_terminal_output()
- _wire_desktop_ui()
+ _wire_desktop_sinks()
stop = threading.Event()
t = threading.Thread(
target=_notification_poller_loop, args=(stop, sid, session), daemon=True, name=f"tui-notif-poller-{sid}"
diff --git a/tui_gateway/synthetic_turn.py b/tui_gateway/synthetic_turn.py
index 6c1fd45c599..93231557e86 100644
--- a/tui_gateway/synthetic_turn.py
+++ b/tui_gateway/synthetic_turn.py
@@ -14,6 +14,7 @@ rides in the prompt text as a JSON object; any other prompt falls back to env /
from __future__ import annotations
+import contextlib
import json
import os
import threading
@@ -23,6 +24,21 @@ from typing import Any, Callable, Optional
from tui_gateway._env import env_float as _env_float, env_int as _env_int
+# Per-turn intensity spec: (key, caster, default source). ``chunk`` is pure-Python ops per
+# interrupt-check chunk (small enough that an interrupt lands within ms, large enough to stay hot on
+# the GIL); ``delta_interval_s`` is the streamed-delta cadence (each delta is a loop wakeup
+# marshalling a frame); ``tokens_per_delta`` drives the 100K+-token heavy-turn proxy; ``sleep_s`` is
+# an optional per-chunk sleep for a mixed regime (0 = pure burn; --dry-run uses a short duration, NOT
+# a sleep, so it still exercises the real seam).
+_SPEC_FIELDS = (
+ ("duration_s", float, lambda: _env_float("HERMES_ISO_CERTIFY_DURATION_S", 8.0)),
+ ("chunk", int, lambda: _env_int("HERMES_ISO_CERTIFY_CHUNK", 20_000)),
+ ("delta_interval_s", float, lambda: _env_float("HERMES_ISO_CERTIFY_DELTA_S", 0.05)),
+ ("tokens_per_delta", int, lambda: _env_int("HERMES_ISO_CERTIFY_TPD", 512)),
+ ("sleep_s", float, lambda: 0.0),
+)
+
+
def synth_turn_armed() -> bool:
"""True when the synthetic-turn test seam is armed via env."""
return os.environ.get("HERMES_ISO_CERTIFY_SYNTH_TURN") == "1"
@@ -74,26 +90,10 @@ class SyntheticHeavyAgent:
def _parse_spec(message: Any) -> dict[str, Any]:
spec: dict[str, Any] = {}
if isinstance(message, str) and message.strip().startswith("{"):
- try:
+ with contextlib.suppress(ValueError, TypeError):
parsed = json.loads(message.strip())
- except (ValueError, TypeError):
- parsed = None
- if isinstance(parsed, dict):
- spec = parsed
- return {
- # Wall-clock seconds of GIL-holding compute.
- "duration_s": float(spec.get("duration_s", _env_float("HERMES_ISO_CERTIFY_DURATION_S", 8.0))),
- # Pure-Python ops per interrupt-check chunk: small enough that an interrupt lands within
- # ms, large enough to stay hot on the GIL.
- "chunk": int(spec.get("chunk", _env_int("HERMES_ISO_CERTIFY_CHUNK", 20_000))),
- # Streamed-delta cadence: each delta is a loop wakeup marshalling a frame.
- "delta_interval_s": float(spec.get("delta_interval_s", _env_float("HERMES_ISO_CERTIFY_DELTA_S", 0.05))),
- # Notional output tokens per delta (drives the 100K+-token heavy-turn proxy).
- "tokens_per_delta": int(spec.get("tokens_per_delta", _env_int("HERMES_ISO_CERTIFY_TPD", 512))),
- # Optional per-chunk sleep for a mixed regime (0 = pure burn). --dry-run uses a short
- # duration, NOT a sleep, so it still exercises the real seam.
- "sleep_s": float(spec.get("sleep_s", 0.0)),
- }
+ spec = parsed if isinstance(parsed, dict) else {}
+ return {key: cast(spec.get(key, default())) for key, cast, default in _SPEC_FIELDS}
def run_conversation(
self,
diff --git a/tui_gateway/turn_marker.py b/tui_gateway/turn_marker.py
index ae938120a93..7a65b23baa5 100644
--- a/tui_gateway/turn_marker.py
+++ b/tui_gateway/turn_marker.py
@@ -120,14 +120,9 @@ def read_turn_marker(home: Path | str, session_key: str) -> dict[str, Any] | Non
try:
with _lock:
entry = _load(_marker_path(home)).get(session_key)
- except Exception:
- return None
- if not isinstance(entry, dict):
- return None
- prompt = str(entry.get("prompt") or "")
- if not prompt.strip():
- return None
- try:
+ prompt = str(entry.get("prompt") or "") if isinstance(entry, dict) else ""
+ if not prompt.strip():
+ return None
return {"attempts": max(0, int(entry.get("attempts") or 0)), "prompt": prompt, "started_at": _started_at(entry)}
- except (TypeError, ValueError):
+ except Exception:
return None