Skip to content

The agent that grows with you

refactor(tui): compact tool_progress/ws/session_history/transport (-13% LOC, wire-neutral)

Tekniumd41d546d0e64
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
index 1a786cf1903..2cd5637f735 100644
--- a/tui_gateway/session_history.py
+++ b/tui_gateway/session_history.py
@@ -6,10 +6,7 @@ Bodies are rebound onto server.py's globals (method_ctx.bind_module) and referen
from __future__ import annotations
-
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
def _active_image_routing_identity(agent: Any) -> tuple[str, str]:
@@ -23,12 +20,11 @@ def _build_image_ref_message(user_text: str, image_paths: list[str]) -> str:
"""Reference attached images by path so the agent analyzes them in-loop with ``vision_analyze``.
Pre-analyzing with the auxiliary vision model blocked submit 60-90s per photo and poisoned
auto-titles with the description."""
- parts = [
+ prefix = "\n\n".join(
f"[The user attached an image: {p.name}]\n[Examine it with the vision_analyze tool using image_url: {p}]"
for p in map(Path, image_paths) if p.exists()
- ]
+ )
text = user_text or ""
- prefix = "\n\n".join(parts)
if prefix:
return f"{prefix}\n\n{text}" if text else prefix
return text or "What do you see in this image?"
@@ -36,7 +32,7 @@ def _build_image_ref_message(user_text: str, image_paths: list[str]) -> str:
def _build_persist_message_with_image_refs(user_text: str, image_paths: list[str]) -> str:
"""Persisted form of the user's message: ``@image:<path>`` directives (the desktop renders them
- as images). ``_build_image_ref_message``'s ``image_url:`` hint is model-only, never persisted.
+ as images); ``_build_image_ref_message``'s ``image_url:`` hint is model-only, never persisted.
Caption first, directives last: session previews are the first 60 chars of the first user
message, so a leading directive would label the session with a truncated path."""
from agent.context_references import format_reference_value
@@ -68,8 +64,7 @@ def _history_part_image_url(part: dict) -> str:
"""The URL carried by an image part (``image_url`` dict or str), else ""."""
image_url = part.get("image_url")
if isinstance(image_url, dict):
- candidate = image_url.get("url")
- return candidate if isinstance(candidate, str) else ""
+ image_url = image_url.get("url")
return image_url if isinstance(image_url, str) else ""
@@ -90,18 +85,12 @@ def _history_dict_text(content: dict, *, image_urls: bool) -> str:
def _content_display_text(content: Any) -> str:
- if content is None:
- return ""
- if isinstance(content, str):
- return content
- if isinstance(content, (int, float)):
- return str(content)
if isinstance(content, list):
parts = (_content_display_text(part).strip() for part in content)
return "\n".join(text for text in parts if text)
if isinstance(content, dict):
return _history_dict_text(content, image_urls=False)
- return str(content)
+ return "" if content is None else str(content)
def _coerce_message_text(content: Any) -> str:
@@ -109,12 +98,6 @@ def _coerce_message_text(content: Any) -> str:
Image parts keep their URL inline so the desktop's ``extractEmbeddedImages`` and the resume payload
agree with the cached message (else the inline image flashed, then vanished); other structured
shapes become a bracketed placeholder so resume doesn't drop the message."""
- if content is None:
- return ""
- if isinstance(content, str):
- return content
- if isinstance(content, (int, float)):
- return str(content)
if isinstance(content, list):
chunks: list[str] = []
for part in content:
@@ -141,30 +124,23 @@ def _coerce_message_text(content: Any) -> str:
return "".join(chunks)
if isinstance(content, dict):
return _history_dict_text(content, image_urls=True)
- return str(content)
+ return "" if content is None else str(content)
-_TEXT_ONLY_BUSY_PART_KINDS = _HISTORY_TEXT_KINDS
+def _history_text_only_part(part: dict) -> bool:
+ kind = part.get("type")
+ return kind in _HISTORY_TEXT_KINDS or (kind is None and isinstance(part.get("text"), str))
def _is_text_only_busy_payload(content: Any) -> bool:
"""True when a busy submit carries only plain text, not attachments/media."""
- if content is None:
- return False
if isinstance(content, (str, int, float)):
return True
if isinstance(content, list):
return bool(content) and all(
isinstance(part, str) or (isinstance(part, dict) and _history_text_only_part(part)) for part in content
)
- if isinstance(content, dict):
- return _history_text_only_part(content)
- return False
-
-
-def _history_text_only_part(part: dict) -> bool:
- kind = part.get("type")
- return kind in _TEXT_ONLY_BUSY_PART_KINDS or (kind is None and isinstance(part.get("text"), str))
+ return isinstance(content, dict) and _history_text_only_part(content)
def _is_display_hidden_marker(role: str | None, text: str) -> bool:
@@ -215,12 +191,12 @@ def _legacy_display_kind(role: str, text: str) -> str | None:
_HISTORY_REASONING_KEYS = ("reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items")
+_HISTORY_ROLES = frozenset({"user", "assistant", "tool", "system"})
def _history_to_messages(history: list[dict]) -> list[dict]:
messages = []
tool_call_args = {}
-
for m in history:
if not isinstance(m, dict):
continue
@@ -228,10 +204,8 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
if m is None:
continue
role = m.get("role")
- if role not in {"user", "assistant", "tool", "system"}:
- continue
# display_kind="hidden": model-facing scaffolding the "[System:" sniff does not catch.
- if m.get("display_kind") == "hidden":
+ if role not in _HISTORY_ROLES or m.get("display_kind") == "hidden":
continue
content_text = _coerce_message_text(m.get("content"))
if _is_display_hidden_marker(role, content_text):
@@ -279,8 +253,8 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
msg["display_kind"] = "skill_invocation"
if role == "assistant":
for key in _HISTORY_REASONING_KEYS:
- if key in m and m.get(key) is not None:
- msg[key] = m.get(key)
+ if m.get(key) is not None:
+ msg[key] = m[key]
# Display-only timeline metadata (model switches, delegation events).
display_kind = m.get("display_kind") or _legacy_display_kind(role, content_text)
if display_kind:
@@ -288,7 +262,6 @@ def _history_to_messages(history: list[dict]) -> list[dict]:
if m.get("display_metadata"):
msg["display_metadata"] = m["display_metadata"]
messages.append(msg)
-
return messages
@@ -297,17 +270,13 @@ def _coerce_seed_history(value: Any) -> list[dict]:
return []
history = []
for item in value:
- if not isinstance(item, dict):
- continue
- role = item.get("role")
- if role not in ("user", "assistant", "system"):
+ if not isinstance(item, dict) or item.get("role") not in ("user", "assistant", "system"):
continue
content = item.get("content")
if content is None:
content = item.get("text")
- if not isinstance(content, str) or not content.strip():
- continue
- history.append({"role": role, "content": content})
+ if isinstance(content, str) and content.strip():
+ history.append({"role": item["role"], "content": content})
return history
@@ -339,10 +308,8 @@ def _record_inflight_correction(session: dict, text: Any) -> None:
"""Record an accepted mid-turn correction on the live turn — appended, never written over ``user``,
so a resuming client can rebuild BOTH bubbles."""
correction = _inflight_text(text)
- if not correction:
- return
turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
+ if not correction or not isinstance(turn, dict):
return
turn = dict(turn)
turn["corrections"] = [*(turn.get("corrections") or []), correction]
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index 25a51158ff7..81457a49dfc 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -1,21 +1,16 @@
"""Tool lifecycle callbacks (tool.start/complete/progress events), verbose-text capping/redaction, todo-state projection.
-Bodies are rebound onto server.py's globals at install time (see
-method_ctx.bind_module), so they reference server.py globals bare.
+Bodies are rebound onto server.py's globals at install time (method_ctx.bind_module), so they
+reference server.py globals bare.
"""
from __future__ import annotations
+from .method_ctx import bind_module
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
-
-
-# Verbose tool text is capped to the Ink render budget (a hair more, so the
-# "[omitted …]" label stays informative): unbounded output fed a render-tree
-# blowup that OOM-killed the TUI parent. Full output stays in the agent context
-# and the SQLite session, untouched.
+# Verbose tool text is capped to the Ink render budget (a hair more, so the "[omitted …]" label
+# stays informative): unbounded output fed a render-tree blowup that OOM-killed the TUI parent.
+# Full output stays in the agent context and the SQLite session, untouched.
_TUI_VERBOSE_TEXT_MAX_CHARS = 1_000
_TUI_VERBOSE_TEXT_MAX_LINES = 16
@@ -23,12 +18,8 @@ _TODO_TOOL_NAMES = ("todo_list", "todo") # legacy alias: pre-rename replays
def _cap_tui_verbose_text(text: str) -> str:
- if (
- len(text) <= _TUI_VERBOSE_TEXT_MAX_CHARS
- and text.count("\n") < _TUI_VERBOSE_TEXT_MAX_LINES
- ):
+ if len(text) <= _TUI_VERBOSE_TEXT_MAX_CHARS and text.count("\n") < _TUI_VERBOSE_TEXT_MAX_LINES:
return text
-
idx = len(text)
start = 0
for _ in range(_TUI_VERBOSE_TEXT_MAX_LINES):
@@ -37,24 +28,17 @@ def _cap_tui_verbose_text(text: str) -> str:
start = 0
break
start = idx + 1
-
line_start = start
start = max(line_start, len(text) - _TUI_VERBOSE_TEXT_MAX_CHARS)
if start > line_start:
next_break = text.find("\n", start)
if 0 <= next_break < len(text) - 1:
start = next_break + 1
-
tail = text[start:].lstrip()
omitted_chars = max(0, len(text) - len(tail))
omitted_lines = text[:start].count("\n")
- if omitted_lines:
- label = (
- "[showing verbose tail; omitted " f"{omitted_lines} lines / {omitted_chars} chars]\n"
- )
- else:
- label = f"[showing verbose tail; omitted {omitted_chars} chars]\n"
- return f"{label}{tail}"
+ omitted = f"{omitted_lines} lines / {omitted_chars} chars" if omitted_lines else f"{omitted_chars} chars"
+ return f"[showing verbose tail; omitted {omitted}]\n{tail}"
def _redact_tui_verbose_text(text: str) -> str:
@@ -105,32 +89,30 @@ def _count_list(obj: object, *path: str) -> int | None:
return len(cur) if isinstance(cur, list) else None
+# tool name -> (count-from-result, verb, singular, plural) for the tool.complete summary line.
+_SUMMARY_COUNTERS = {
+ "web_search": (lambda d: _count_list(d, "data", "web"), "Did", "search", "searches"),
+ "web_extract": (lambda d: _count_list(d, "results") or _count_list(d, "data", "results"), "Extracted", "page", "pages"),
+}
+
+
def _tool_summary(name: str, result: str, duration_s: float | None) -> str | None:
try:
data = json.loads(result)
except Exception:
data = None
-
+ if not isinstance(data, dict):
+ return None
dur = _fmt_tool_duration(duration_s)
suffix = f" in {dur}" if dur else ""
- text = None
-
- if name == "web_search" and isinstance(data, dict):
- n = _count_list(data, "data", "web")
- if n is not None:
- text = f"Did {n} {'search' if n == 1 else 'searches'}"
-
- elif name == "web_extract" and isinstance(data, dict):
- n = _count_list(data, "results") or _count_list(data, "data", "results")
- if n is not None:
- text = f"Extracted {n} {'page' if n == 1 else 'pages'}"
-
- if isinstance(data, dict) and data.get("fallback_warning"):
- warning = str(data.get("fallback_warning") or "").strip()
- if warning:
- return f"{warning}{suffix}"
-
- return f"{text}{suffix}" if text else None
+ warning = str(data.get("fallback_warning") or "").strip()
+ if warning:
+ return f"{warning}{suffix}"
+ entry = _SUMMARY_COUNTERS.get(name)
+ n = entry[0](data) if entry else None
+ if n is None:
+ return None
+ return f"{entry[1]} {n} {entry[2] if n == 1 else entry[3]}{suffix}"
def _normalize_todo_state(value: object) -> dict | None:
@@ -142,9 +124,8 @@ def _normalize_todo_state(value: object) -> dict | None:
except (TypeError, ValueError):
return None
todos = list(value["todos"])
- # Unused TodoStore snapshot() is {todos: [], revision: 0}: attaching it on
- # resume stamps a client watermark and blocks unversioned tool.start merges.
- # An empty list at revision >= 1 is a real clear.
+ # Unused TodoStore snapshot() is {todos: [], revision: 0}: attaching it on resume stamps a
+ # client watermark and blocks unversioned tool.start merges. Empty at revision >= 1 is a real clear.
if not todos and revision == 0:
return None
return {"todos": todos, "revision": revision}
@@ -163,18 +144,13 @@ def _session_todo_state(session: dict) -> dict | None:
"""Return the newest live/cached todo snapshot for a runtime session."""
cached = _normalize_todo_state(session.get("todo_state"))
live = None
- agent = session.get("agent")
- store = getattr(agent, "_todo_store", None)
- snapshot = getattr(store, "snapshot", None)
+ snapshot = getattr(getattr(session.get("agent"), "_todo_store", None), "snapshot", None)
if callable(snapshot):
try:
live = _normalize_todo_state(snapshot())
except Exception:
logger.debug("failed to read live todo state", exc_info=True)
-
- if live is not None and (
- cached is None or live["revision"] >= cached["revision"]
- ):
+ if live is not None and (cached is None or live["revision"] >= cached["revision"]):
cached = live
if cached is not None:
session["todo_state"] = cached
@@ -190,36 +166,27 @@ def _attach_todo_state(payload: dict, session: dict) -> dict:
def _todo_state_from_history(history) -> dict | None:
- """Latest todo snapshot from an already-loaded transcript, for resume paths
- that answer before an AIAgent (and its live TodoStore) exists: the newest
- tool result paired with an assistant ``todo`` call IS the durable snapshot."""
+ """Latest todo snapshot from a loaded transcript, for resume paths that answer before an AIAgent
+ (and its live TodoStore) exists: the newest tool result paired with an assistant ``todo`` call
+ IS the durable snapshot."""
if not isinstance(history, list) or not history:
return None
try:
from tools.todo_tool import MAX_TODO_RESULT_CHARS
- todo_call_ids: set[str] = set()
- for msg in history:
- if not isinstance(msg, dict):
- continue
- for call in msg.get("tool_calls") or []:
- if (call.get("function") or {}).get("name") in _TODO_TOOL_NAMES:
- cid = call.get("id")
- if cid:
- todo_call_ids.add(cid)
+ todo_call_ids = {
+ call.get("id")
+ for msg in history if isinstance(msg, dict)
+ for call in msg.get("tool_calls") or []
+ if (call.get("function") or {}).get("name") in _TODO_TOOL_NAMES and call.get("id")
+ }
if not todo_call_ids:
return None
for msg in reversed(history):
- if not isinstance(msg, dict) or msg.get("role") != "tool":
- continue
- if msg.get("tool_call_id") not in todo_call_ids:
+ if not isinstance(msg, dict) or msg.get("role") != "tool" or msg.get("tool_call_id") not in todo_call_ids:
continue
content = msg.get("content", "")
- if (
- not isinstance(content, str)
- or len(content) > MAX_TODO_RESULT_CHARS
- or '"todos"' not in content
- ):
+ if not isinstance(content, str) or len(content) > MAX_TODO_RESULT_CHARS or '"todos"' not in content:
continue
try:
return _normalize_todo_state(json.loads(content))
@@ -234,25 +201,17 @@ def _todo_state_from_history(history) -> dict | None:
def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
session = _sessions.get(sid)
if session is not None:
- try:
+ with contextlib.suppress(Exception):
from agent.display import capture_local_edit_snapshot
snapshot = capture_local_edit_snapshot(name, args)
if snapshot is not None:
session.setdefault("edit_snapshots", {})[tool_call_id] = snapshot
- except Exception:
- pass
session.setdefault("tool_started_at", {})[tool_call_id] = time.time()
if _tool_progress_enabled(sid) or _tool_lifecycle_required_for_ui(name):
- payload: dict[str, object] = {
- "tool_id": tool_call_id,
- "name": name,
- "context": _tool_ctx(name, args),
- }
- # Full args here (not just the 80-char `context` preview) so the desktop's
- # expanded tool row is complete while the tool runs; tool.complete ships
- # them again. args.todos may be a partial merge — tool.complete is the
- # source of truth for todos.
+ payload: dict[str, object] = {"tool_id": tool_call_id, "name": name, "context": _tool_ctx(name, args)}
+ # Full args (not just the 80-char `context` preview) so the desktop's expanded tool row is
+ # complete while the tool runs. args.todos may be a partial merge — tool.complete is the truth.
if args:
payload["args"] = args
if _session_verbose(sid):
@@ -265,8 +224,7 @@ def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict):
def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result: str):
payload = {"tool_id": tool_call_id, "name": name, "args": args}
session = _sessions.get(sid)
- snapshot = None
- started_at = None
+ snapshot = started_at = None
if session is not None:
snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None)
started_at = session.setdefault("tool_started_at", {}).pop(tool_call_id, None)
@@ -291,20 +249,12 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
payload.update(todo_state)
if session is not None:
_cache_todo_state(session, todo_state)
- try:
+ with contextlib.suppress(Exception):
from agent.display import render_edit_diff_with_delta
rendered: list[str] = []
- if render_edit_diff_with_delta(
- name,
- result,
- function_args=args,
- snapshot=snapshot,
- print_fn=rendered.append,
- ):
+ if render_edit_diff_with_delta(name, result, function_args=args, snapshot=snapshot, print_fn=rendered.append):
payload["inline_diff"] = "\n".join(rendered)
- except Exception:
- pass
if (
_tool_progress_enabled(sid)
or payload.get("inline_diff")
@@ -312,17 +262,16 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
or name in _TODO_TOOL_NAMES
):
_emit("tool.complete", sid, payload)
- # Task state is application data, not tool-progress chrome: a dedicated
- # full-snapshot event lets every client reconcile without parsing tool args.
+ # Task state is application data, not tool-progress chrome: a dedicated full-snapshot event
+ # lets every client reconcile without parsing tool args.
if todo_state is not None:
_emit("todo.updated", sid, todo_state)
# ── _on_tool_progress dispatch ─────────────────────────────────────────────
-# Each handler takes (sid, name, preview, kw). `tool.started` is dropped on
-# purpose: _on_tool_start already emits the authoritative tool.start with the
-# stable id and args; an id-less duplicate row makes the desktop live view
-# diverge from hydrated history.
+# Each handler takes (sid, name, preview, kw). `tool.started` is dropped on purpose: _on_tool_start
+# already emits the authoritative tool.start with the stable id and args; an id-less duplicate row
+# makes the desktop live view diverge from hydrated history.
def _progress_output_risk(sid, name, preview, kw):
@@ -345,12 +294,9 @@ def _progress_reasoning(sid, name, preview, kw):
def _progress_moa_reference(sid, name, preview, kw):
- # MoA reference-model output, rendered as a labelled block before the
- # aggregator's response. `name` is the slot label, `preview` the text.
- ref_payload: dict[str, object] = {
- "label": str(name),
- "text": str(preview or ""),
- }
+ # MoA reference-model output, rendered as a labelled block before the aggregator's response.
+ # `name` is the slot label, `preview` the text.
+ ref_payload: dict[str, object] = {"label": str(name), "text": str(preview or "")}
if kw.get("moa_index") is not None:
ref_payload["index"] = kw.get("moa_index")
if kw.get("moa_count") is not None:
@@ -363,8 +309,7 @@ def _progress_moa_aggregating(sid, name, preview, kw):
def _progress_moa_progress(sid, name, preview, kw):
- # Drives the status-bar `MOA: 2/3 refs done`; both counters required so the
- # client renders deterministically.
+ # Drives the status-bar `MOA: 2/3 refs done`; both counters required for deterministic rendering.
refs_done = kw.get("moa_refs_done")
refs_total = kw.get("moa_refs_total")
if refs_done is None or refs_total is None:
@@ -380,74 +325,69 @@ def _progress_moa_phase(sid, name, preview, kw):
if not phase:
return
phase_payload: dict[str, object] = {"phase": str(phase)}
- refs_done = kw.get("moa_refs_done")
- refs_total = kw.get("moa_refs_total")
- if refs_done is not None:
- phase_payload["refs_done"] = int(refs_done)
- if refs_total is not None:
- phase_payload["refs_total"] = int(refs_total)
+ for key, out in (("moa_refs_done", "refs_done"), ("moa_refs_total", "refs_total")):
+ if kw.get(key) is not None:
+ phase_payload[out] = int(kw[key])
if name:
phase_payload["aggregator"] = str(name)
_emit("moa.phase", sid, phase_payload)
-# Per-branch rollups emitted on subagent.complete.
-_SUBAGENT_INT_FIELDS = ("input_tokens", "output_tokens", "reasoning_tokens", "api_calls")
+def _not_none(v):
+ return v is not None
+
+
+def _str_list(v):
+ return [str(x) for x in v]
+
+
+def _int_or_skip(v):
+ # Per-branch rollups tolerate junk from older emitters: unparsable -> field omitted.
+ try:
+ return int(v)
+ except (TypeError, ValueError):
+ return None
+
+
+# Optional subagent.* payload fields in WIRE ORDER: (source key, present-when, coerce). Identity
+# fields are all optional: older emitters omit them and the TUI spawn tree falls back to flat
+# rendering. `tool_name`/`text` are fed from the positional name/preview.
+_SUBAGENT_FIELDS = (
+ ("subagent_id", bool, str), ("parent_id", bool, str), ("child_session_id", bool, str),
+ ("delegation_id", bool, str), ("depth", _not_none, int), ("model", bool, str),
+ ("tool_count", _not_none, int), ("toolsets", bool, _str_list),
+ ("input_tokens", _not_none, _int_or_skip), ("output_tokens", _not_none, _int_or_skip),
+ ("reasoning_tokens", _not_none, _int_or_skip), ("api_calls", _not_none, _int_or_skip),
+ ("files_read", bool, _str_list), ("files_written", bool, _str_list),
+ ("output_tail", bool, list), # list of dicts
+ ("tool_name", bool, str), ("text", bool, str), ("status", bool, str), ("summary", bool, str),
+ ("duration_seconds", _not_none, float),
+)
def _progress_subagent(sid, name, preview, kw, event_type):
- # Identity fields are all optional: older emitters omit them and the TUI
- # spawn tree falls back to flat rendering.
payload = {
"goal": str(kw.get("goal") or ""), "task_count": int(kw.get("task_count") or 1),
"task_index": int(kw.get("task_index") or 0),
}
- for key in ("subagent_id", "parent_id", "child_session_id", "delegation_id"):
- if kw.get(key):
- payload[key] = str(kw[key])
- if kw.get("depth") is not None:
- payload["depth"] = int(kw["depth"])
- if kw.get("model"):
- payload["model"] = str(kw["model"])
- if kw.get("tool_count") is not None:
- payload["tool_count"] = int(kw["tool_count"])
- if kw.get("toolsets"):
- payload["toolsets"] = [str(t) for t in kw["toolsets"]]
- for int_key in _SUBAGENT_INT_FIELDS:
- val = kw.get(int_key)
- if val is not None:
- try:
- payload[int_key] = int(val)
- except (TypeError, ValueError):
- pass
- for key in ("files_read", "files_written"):
- if kw.get(key):
- payload[key] = [str(p) for p in kw[key]]
- if kw.get("output_tail"):
- payload["output_tail"] = list(kw["output_tail"]) # list of dicts
- if name:
- payload["tool_name"] = str(name)
- if preview:
- payload["text"] = str(preview)
- if kw.get("status"):
- payload["status"] = str(kw["status"])
- if kw.get("summary"):
- payload["summary"] = str(kw["summary"])
- if kw.get("duration_seconds") is not None:
- payload["duration_seconds"] = float(kw["duration_seconds"])
+ source = {**kw, "tool_name": name, "text": preview}
+ for key, present, coerce in _SUBAGENT_FIELDS:
+ if present(source.get(key)):
+ val = coerce(source[key])
+ if val is not None:
+ payload[key] = val
if preview and event_type == "subagent.tool":
payload["tool_preview"] = str(preview)
payload["text"] = str(preview)
- # subagent.text is the child's per-token reply, relayed solely to feed a
- # watch window's live mirror (keyed off the child sid); on the parent it's
- # hundreds of ignored frames, so skip that emit.
+ # subagent.text is the child's per-token reply, relayed solely to feed a watch window's live
+ # mirror (keyed off the child sid); on the parent it's hundreds of ignored frames, so skip it.
if event_type != "subagent.text":
_emit(event_type, sid, payload)
_mirror_subagent_to_child(event_type, payload)
-# event_type -> (handler, requires) where `requires` names the arg that must be
-# truthy for the row to be emitted at all ("name" / "preview" / None).
+# event_type -> (handler, requires) where `requires` names the arg that must be truthy for the
+# row to be emitted at all ("name" / "preview" / None).
_PROGRESS_HANDLERS = {
"tool.output_risk": (_progress_output_risk, "name"),
"reasoning.available": (_progress_reasoning, "preview"),
@@ -458,12 +398,8 @@ _PROGRESS_HANDLERS = {
def _on_tool_progress(
- sid: str,
- event_type: str,
- name: str | None = None,
- preview: str | None = None,
- _args: dict | None = None,
- **_kwargs,
+ sid: str, event_type: str, name: str | None = None, preview: str | None = None,
+ _args: dict | None = None, **_kwargs,
):
if not _tool_progress_enabled(sid):
return
diff --git a/tui_gateway/transport.py b/tui_gateway/transport.py
index ce93e518a3d..dcb171de4c3 100644
--- a/tui_gateway/transport.py
+++ b/tui_gateway/transport.py
@@ -1,23 +1,11 @@
"""Transport abstraction for the tui_gateway JSON-RPC server.
-Historically the gateway wrote every JSON frame directly to real stdout. This
-module decouples the I/O sink from the handler logic so the same dispatcher
-can be driven over stdio (``tui_gateway.entry``) or WebSocket
-(``tui_gateway.ws``) without duplicating code.
-
-A :class:`Transport` is anything that can accept a JSON-serialisable dict and
-forward it to its peer. The active transport for the current request is
-tracked in a :class:`contextvars.ContextVar` so handlers — including those
-dispatched onto the worker pool — route their writes to the right peer.
-
-Backward compatibility
-----------------------
-``tui_gateway.server.write_json`` still works without any transport bound.
-When nothing is on the contextvar and no session-level transport is found,
-it falls back to the module-level :class:`StdioTransport`, which wraps the
-original ``_real_stdout`` + ``_stdout_lock`` pair. Tests that monkey-patch
-``server._real_stdout`` continue to work because the stdio transport resolves
-the stream lazily through a callback.
+A :class:`Transport` accepts a JSON-serialisable dict and forwards it to its peer, so the same
+dispatcher runs over stdio (``tui_gateway.entry``) or WebSocket (``tui_gateway.ws``). The active
+transport for the current request lives in a ``ContextVar`` so handlers dispatched onto the worker
+pool route writes to the right peer. ``server.write_json`` works with nothing bound: it falls back
+to the module-level :class:`StdioTransport`, which resolves ``_real_stdout`` lazily through a
+callback so tests that monkey-patch ``server._real_stdout`` keep working.
"""
from __future__ import annotations
@@ -30,37 +18,20 @@ import os
import threading
from typing import Any, Callable, Optional, Protocol, runtime_checkable
-# Errno values that mean "the peer is gone" rather than "the host has a
-# real I/O problem". Anything outside this set re-raises so it surfaces
-# in the crash log instead of looking like a clean disconnect.
+# Errno values that mean "the peer is gone" rather than "the host has a real I/O problem". Anything
+# outside this set re-raises so it surfaces in the crash log instead of looking like a clean disconnect.
_PEER_GONE_ERRNOS = frozenset({
- errno.EPIPE, # write to closed pipe (POSIX)
- errno.ECONNRESET, # peer reset the connection
- errno.EBADF, # fd closed under us
- errno.ESHUTDOWN, # transport endpoint shut down
- getattr(errno, "WSAECONNRESET", -1), # win32 mapping (no-op on POSIX)
- getattr(errno, "WSAESHUTDOWN", -1),
+ errno.EPIPE, errno.ECONNRESET, errno.EBADF, errno.ESHUTDOWN,
+ getattr(errno, "WSAECONNRESET", -1), getattr(errno, "WSAESHUTDOWN", -1), # win32 (no-op on POSIX)
} - {-1})
logger = logging.getLogger(__name__)
-# Optional knob: when true, StdioTransport does not call ``stream.flush``
-# after writing. Use this on environments where a half-closed pipe (TUI
-# Node parent quit while the gateway is still emitting events) makes
-# flush block long enough to starve the rest of the worker pool.
-#
-# IMPORTANT: Python text stdout is fully buffered when attached to a
-# pipe (the TUI case), so this knob ONLY makes sense when the gateway
-# is launched with ``-u`` or ``PYTHONUNBUFFERED=1``. Without one of
-# those, JSON-RPC frames will accumulate in the buffer and the TUI
-# will hang waiting for ``gateway.ready``. Default stays off so the
-# existing flush-after-write behaviour is unchanged.
-_DISABLE_FLUSH = (os.environ.get("HERMES_TUI_GATEWAY_NO_FLUSH", "") or "").strip().lower() in {
- "1",
- "true",
- "yes",
- "on",
-}
+# When true, StdioTransport skips ``stream.flush`` after writing: on a half-closed pipe (TUI Node
+# parent quit while the gateway still emits) flush can block long enough to starve the worker pool.
+# Python text stdout is fully buffered on a pipe, so this ONLY makes sense with ``-u`` /
+# ``PYTHONUNBUFFERED=1``; otherwise frames accumulate and the TUI hangs waiting for ``gateway.ready``.
+_DISABLE_FLUSH = (os.environ.get("HERMES_TUI_GATEWAY_NO_FLUSH", "") or "").strip().lower() in {"1", "true", "yes", "on"}
@runtime_checkable
@@ -74,11 +45,8 @@ class Transport(Protocol):
"""Release any resources owned by this transport."""
-_current_transport: contextvars.ContextVar[Optional[Transport]] = (
- contextvars.ContextVar(
- "hermes_gateway_transport",
- default=None,
- )
+_current_transport: contextvars.ContextVar[Optional[Transport]] = contextvars.ContextVar(
+ "hermes_gateway_transport", default=None
)
@@ -97,13 +65,33 @@ def reset_transport(token) -> None:
_current_transport.reset(token)
-class StdioTransport:
- """Writes JSON frames to a stream (usually ``sys.stdout``).
+def _peer_gone(exc: Exception, what: str) -> bool:
+ """True when *exc* from a stream write/flush means the peer is gone; re-raise anything else.
- The stream is resolved via a callable so runtime monkey-patches of the
- underlying stream continue to work — this preserves the behaviour the
- existing test suite relies on (``monkeypatch.setattr(server, "_real_stdout", ...)``).
+ ``False`` from :meth:`StdioTransport.write` is the dispatcher's "broken stdout pipe" signal
+ (``entry.py`` exits cleanly on it), so programming errors and real host I/O bugs (non-JSON-safe
+ payloads, UnicodeEncodeError from a misconfigured locale, ENOSPC, EACCES, ...) MUST re-raise so
+ the crash log records them instead of masquerading as a clean disconnect. Peer-gone:
+ ``BrokenPipeError``, ``ValueError("...closed file...")``, ``OSError`` with errno in
+ :data:`_PEER_GONE_ERRNOS`.
"""
+ if isinstance(exc, BrokenPipeError):
+ return True
+ if isinstance(exc, ValueError):
+ if isinstance(exc, UnicodeEncodeError) or "closed file" not in str(exc):
+ raise exc
+ return True
+ if isinstance(exc, OSError):
+ if exc.errno not in _PEER_GONE_ERRNOS:
+ raise exc
+ logger.debug("StdioTransport %s peer gone: %s", what, exc)
+ return True
+ raise exc
+
+
+class StdioTransport:
+ """Writes JSON frames to a stream (usually ``sys.stdout``), resolved via a callable so runtime
+ monkey-patches of the underlying stream keep working."""
__slots__ = ("_stream_getter", "_lock")
@@ -112,71 +100,26 @@ class StdioTransport:
self._lock = lock
def write(self, obj: dict) -> bool:
- """Return ``True`` on success, ``False`` ONLY when the peer is gone.
-
- Returning ``False`` is the dispatcher's "broken stdout pipe" signal
- — ``entry.py`` calls ``sys.exit(0)`` when ``write_json`` reports
- ``False``. So programming errors (non-JSON-safe payloads, encoding
- misconfig, unexpected ValueErrors, host I/O bugs like ENOSPC) MUST
- NOT return ``False``, otherwise a real bug looks like a clean
- disconnect and is harder to diagnose. Those re-raise so the
- existing crash-log infrastructure records the traceback.
-
- Peer-gone branches:
- * ``BrokenPipeError``
- * ``ValueError("...closed file...")``
- * ``OSError`` whose errno is in :data:`_PEER_GONE_ERRNOS`
- (EPIPE / ECONNRESET / EBADF / ESHUTDOWN; plus WSA mappings
- on Windows). Other OSError errnos (ENOSPC, EACCES, ...) are
- real host problems and re-raise.
- """
- # Serialization is OUTSIDE the lock so a large payload can't
- # block other threads emitting their own frames. A non-JSON-safe
- # payload is a programming error: re-raise so the crash log
- # captures it instead of silently exiting via the False path.
+ """Return ``True`` on success, ``False`` ONLY when the peer is gone (see :func:`_peer_gone`)."""
+ # Serialization is OUTSIDE the lock so a large payload can't block other threads emitting
+ # their own frames. A non-JSON-safe payload is a programming error: re-raise.
line = json.dumps(obj, ensure_ascii=False) + "\n"
-
with self._lock:
stream = self._stream_getter()
try:
stream.write(line)
- except BrokenPipeError:
- return False
- except ValueError as e:
- # ValueError("I/O operation on closed file") is the
- # ONLY ValueError that means "peer gone". Anything
- # else — including UnicodeEncodeError, which is a
- # ValueError subclass for misconfigured locales —
- # is a real bug; re-raise so it surfaces in the crash log.
- if isinstance(e, UnicodeEncodeError) or "closed file" not in str(e):
- raise
- return False
- except OSError as e:
- if e.errno not in _PEER_GONE_ERRNOS:
- raise
- logger.debug("StdioTransport write peer gone: %s", e)
- return False
-
- # A flush that *raises* with a peer-gone errno means the
- # dispatcher should exit cleanly. A flush that *hangs* on
- # a half-closed pipe holds the lock until it returns — see
- # ``_DISABLE_FLUSH`` for the "skip flush entirely" escape
- # hatch.
+ except Exception as e:
+ if _peer_gone(e, "write"):
+ return False
+ # A flush that *raises* with a peer-gone errno means the dispatcher should exit cleanly.
+ # A flush that *hangs* on a half-closed pipe holds the lock until it returns — see
+ # ``_DISABLE_FLUSH`` for the "skip flush entirely" escape hatch.
if not _DISABLE_FLUSH:
try:
stream.flush()
- except BrokenPipeError:
- return False
- except ValueError as e:
- if isinstance(e, UnicodeEncodeError) or "closed file" not in str(e):
- raise
- return False
- except OSError as e:
- if e.errno not in _PEER_GONE_ERRNOS:
- raise
- logger.debug("StdioTransport flush peer gone: %s", e)
- return False
-
+ except Exception as e:
+ if _peer_gone(e, "flush"):
+ return False
return True
def close(self) -> None:
@@ -186,10 +129,9 @@ class StdioTransport:
class TeeTransport:
"""Mirrors writes to one primary plus N best-effort secondaries.
- The primary's return value (and exceptions) determine the result —
- secondaries swallow failures so a wedged sidecar never stalls the
- main IO path. Used by the PTY child so every dispatcher emit lands
- on stdio (Ink) AND on a back-WS feeding the dashboard sidebar.
+ The primary's return value (and exceptions) determine the result — secondaries swallow failures
+ so a wedged sidecar never stalls the main IO path. Used by the PTY child so every dispatcher
+ emit lands on stdio (Ink) AND on a back-WS feeding the dashboard sidebar.
"""
__slots__ = ("_primary", "_secondaries")
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 215e501d485..a1d04a9ae48 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -1,17 +1,10 @@
"""WebSocket transport for the tui_gateway JSON-RPC server.
-Reuses :func:`tui_gateway.server.dispatch` verbatim so every RPC method, slash
-command, approval/clarify/sudo flow and agent event flows through the same
-handlers whether the client is Ink over stdio or an iOS/web client over WS.
-
-Wire protocol is identical to stdio: newline-delimited JSON-RPC both ways. The
-server emits ``gateway.ready`` right after accept, then echoes responses/events.
-
-Mounting::
-
- @app.websocket("/api/ws")
- async def ws(ws: WebSocket):
- await handle_ws(ws)
+Reuses :func:`tui_gateway.server.dispatch` verbatim so every RPC method, slash command,
+approval/clarify/sudo flow and agent event flows through the same handlers whether the client is
+Ink over stdio or an iOS/web client over WS. Wire protocol is identical to stdio: newline-delimited
+JSON-RPC both ways; the server emits ``gateway.ready`` right after accept, then echoes
+responses/events. Mount as ``@app.websocket("/api/ws") async def ws(ws): await handle_ws(ws)``.
"""
from __future__ import annotations
@@ -30,10 +23,9 @@ from tui_gateway.event_replay import replay_epoch
_log = logging.getLogger(__name__)
-# Scale-to-zero: tell the (separate) gateway process a dashboard/desktop/TUI
-# client is attached via the mtime of a marker file it reads in its idle
-# predicate. Clients ping every 15s; one write per 5s per process is plenty.
-# See gateway/scale_to_zero.py.
+# Scale-to-zero: tell the (separate) gateway process a dashboard/desktop/TUI client is attached via
+# the mtime of a marker file it reads in its idle predicate (gateway/scale_to_zero.py). Clients ping
+# every 15s; one write per 5s per process is plenty.
_DASHBOARD_CLIENT_TOUCH_MIN_INTERVAL_S = 5.0
_dashboard_client_touched_at = 0.0
_dashboard_client_touch_lock = threading.Lock()
@@ -55,17 +47,16 @@ def _note_dashboard_client_activity(*, force: bool = False) -> None:
_log.debug("dashboard client heartbeat touch failed", exc_info=True)
-# Max seconds a pool-dispatched handler blocks waiting for the loop to flush a
-# WS frame before we give up waiting (the transport is NOT marked dead).
+# Max seconds a pool-dispatched handler blocks waiting for the loop to flush a WS frame before we
+# give up waiting (the transport is NOT marked dead).
_WS_WRITE_TIMEOUT_S = 10.0
_WS_LOG_PAYLOAD_PREVIEW = 240
-# Per-token streaming frames are coalesced: buffered and flushed as a batch on a
-# short timer instead of waking the loop once per token (each wakeup competes
-# with the agent turn for the GIL). Keep this set to genuinely high-frequency,
-# display-only events — anything a client must see promptly (tool/approval/
-# status/completion) is non-streaming and flushes the buffer ahead of itself,
-# so ordering is preserved.
+# Per-token streaming frames are coalesced: buffered and flushed as a batch on a short timer
+# instead of waking the loop once per token (each wakeup competes with the agent turn for the GIL).
+# Keep this set to genuinely high-frequency, display-only events — anything a client must see
+# promptly (tool/approval/status/completion) is non-streaming and flushes the buffer ahead of
+# itself, so ordering is preserved.
_STREAMING_EVENT_TYPES = frozenset({"message.delta", "reasoning.delta", "thinking.delta"})
# Max time a streamed token waits in the buffer (~30 fps; imperceptible).
_TOKEN_COALESCE_S = 0.033
@@ -80,38 +71,31 @@ except ImportError: # pragma: no cover - starlette is a required install path
class WSTransport:
"""Per-connection WS transport.
- ``write`` is safe from any thread *other than* the loop thread owning the
- socket (pool workers marshal onto the loop and block on the future). Called
- from the loop thread itself that would deadlock, so we detect it and
- fire-and-forget; loop-thread callers that need completion use ``write_async``.
+ ``write`` is safe from any thread *other than* the loop thread owning the socket (pool workers
+ marshal onto the loop and block on the future). Called from the loop thread itself it would
+ deadlock, so we detect that and fire-and-forget; loop-thread callers that need completion use
+ ``write_async``.
"""
- def __init__(
- self,
- ws: Any,
- loop: asyncio.AbstractEventLoop,
- *,
- peer: str = "unknown",
- auth_identity: dict | None = None,
- ) -> None:
+ def __init__(self, ws: Any, loop: asyncio.AbstractEventLoop, *, peer: str = "unknown",
+ auth_identity: dict | None = None) -> None:
self._ws = ws
self._loop = loop
self._peer = peer
- #: Server-verified identity from the WS-upgrade credential (dashboard
- #: ticket / internal credential), stamped by ``web_server._ws_auth_reason``.
- #: None for legacy-token/stdio transports. RPC params can never populate
- #: this: it is the only identity authority for browser-controller registration.
+ #: Server-verified identity from the WS-upgrade credential (dashboard ticket / internal
+ #: credential), stamped by ``web_server._ws_auth_reason``. None for legacy-token/stdio
+ #: transports. RPC params can never populate this: it is the only identity authority for
+ #: browser-controller registration.
self.auth_identity = auth_identity
self._closed = False
- # Token-coalescing buffer. The lock guards the buffer + "armed" flag
- # against worker threads calling write(); the timer handle is only ever
- # touched on the loop thread.
+ # Token-coalescing buffer. The lock guards the buffer + "armed" flag against worker threads
+ # calling write(); the timer handle is only ever touched on the loop thread.
self._token_lock = threading.Lock()
self._pending_tokens: list[str] = []
self._token_flush_handle: asyncio.TimerHandle | None = None
self._token_flush_armed = False
- # Socket writes need an async boundary: several batches can be queued on
- # the owning loop while it recovers from a stall.
+ # Socket writes need an async boundary: several batches can be queued on the owning loop
+ # while it recovers from a stall.
self._send_lock = asyncio.Lock()
@staticmethod
@@ -128,8 +112,8 @@ class WSTransport:
except RuntimeError:
on_loop = False
- # Streamed token: buffer it and arm the flush timer; the worker returns
- # immediately. call_soon_threadsafe is safe from a worker or the loop.
+ # Streamed token: buffer it and arm the flush timer; the worker returns immediately.
+ # call_soon_threadsafe is safe from a worker or the loop.
if self._is_streaming_frame(obj):
with self._token_lock:
self._pending_tokens.append(line)
@@ -138,10 +122,9 @@ class WSTransport:
self._loop.call_soon_threadsafe(self._arm_token_flush)
return not self._closed
- # Non-streaming frame: append behind any buffered tokens and flush the
- # whole batch NOW so it can never overtake them. The send is scheduled
- # INSIDE the lock so wire order matches buffer order even if the
- # coalesce timer fires on the loop at the same moment.
+ # Non-streaming frame: append behind any buffered tokens and flush the whole batch NOW so it
+ # can never overtake them. The send is scheduled INSIDE the lock so wire order matches
+ # buffer order even if the coalesce timer fires on the loop at the same moment.
from agent.async_utils import safe_schedule_threadsafe
with self._token_lock:
@@ -159,10 +142,9 @@ class WSTransport:
fut.result(timeout=_WS_WRITE_TIMEOUT_S)
return not self._closed
except concurrent.futures.TimeoutError: # builtin TimeoutError on 3.11+
- # The loop is stalled (GIL-heavy turn, delegation), NOT the socket
- # dead: the send is already scheduled and flushes once the loop
- # breathes. Latching _closed here permanently silenced live windows
- # after one slow write; _safe_send_many latches on a real error.
+ # The loop is stalled (GIL-heavy turn, delegation), NOT the socket dead: the send is
+ # already scheduled and flushes once the loop breathes. Latching _closed here permanently
+ # silenced live windows after one slow write; _safe_send_many latches on a real error.
_log.warning(
"ws write slow (loop stalled >%ss) peer=%s — frame left in flight",
_WS_WRITE_TIMEOUT_S, self._peer,
@@ -170,10 +152,7 @@ class WSTransport:
return not self._closed
except Exception as exc:
self._closed = True
- _log.warning(
- "ws write failed peer=%s error_type=%s error=%s",
- self._peer, type(exc).__name__, exc,
- )
+ _log.warning("ws write failed peer=%s error_type=%s error=%s", self._peer, type(exc).__name__, exc)
return False
def _arm_token_flush(self) -> None:
@@ -183,8 +162,8 @@ class WSTransport:
self._token_flush_handle = self._loop.call_later(_TOKEN_COALESCE_S, self._flush_tokens)
def _flush_tokens(self) -> None:
- """Timer callback (loop thread): send buffered tokens as one batch. Scheduled
- under the lock so wire order is fixed relative to a concurrent ``write``."""
+ """Timer callback (loop thread): send buffered tokens as one batch. Scheduled under the lock
+ so wire order is fixed relative to a concurrent ``write``."""
with self._token_lock:
self._token_flush_handle = None
self._token_flush_armed = False
@@ -193,8 +172,8 @@ class WSTransport:
self._loop.create_task(self._safe_send_many(batch))
async def write_async(self, obj: dict) -> bool:
- """Send from the owning loop; awaits until the frame is on the wire. Buffered
- tokens are flushed ahead of it in the SAME batch so nothing slips between."""
+ """Send from the owning loop; awaits until the frame is on the wire. Buffered tokens are
+ flushed ahead of it in the SAME batch so nothing slips between."""
if self._closed:
return False
with self._token_lock:
@@ -214,13 +193,10 @@ class WSTransport:
return
await self._ws.send_text(line)
except Exception as exc:
- # Latch while holding the writer lock so queued batches observe
- # the failure before touching the socket.
+ # Latch while holding the writer lock so queued batches observe the failure before
+ # touching the socket.
self._closed = True
- _log.warning(
- "ws send failed peer=%s error_type=%s error=%s",
- self._peer, type(exc).__name__, exc,
- )
+ _log.warning("ws send failed peer=%s error_type=%s error=%s", self._peer, type(exc).__name__, exc)
def close(self) -> None:
self._closed = True
@@ -244,11 +220,10 @@ def _ws_peer_label(ws: Any) -> str:
def _disable_nagle(ws: Any) -> None:
"""Disable Nagle + enable TCP keepalive on the raw socket (best-effort).
- Without TCP_NODELAY the kernel coalesces small per-token frames, so a burst
- after the model's think-pause lands in one tick and no client-side smoothing
- can recover the cadence. Without keepalive a silently-dropped client (SSH
- tunnel reset, sleep) leaves the leg half-open forever: receive_text() blocks
- and the disconnect teardown (detach + orphan reap + resume replay) never runs.
+ Without TCP_NODELAY the kernel coalesces small per-token frames, so a burst after the model's
+ think-pause lands in one tick and no client-side smoothing can recover the cadence. Without
+ keepalive a silently-dropped client (SSH tunnel reset, sleep) leaves the leg half-open forever:
+ receive_text() blocks and the disconnect teardown (detach + orphan reap + resume replay) never runs.
"""
try:
scope = getattr(ws, "scope", None) or {}
@@ -271,18 +246,12 @@ def _error_frame(code: int, message: str, req_id: Any) -> dict:
return {"jsonrpc": "2.0", "error": {"code": code, "message": message}, "id": req_id}
-async def handle_ws(
- ws: Any,
- *,
- auth_identity: dict | None = None,
- subprotocol: str | None = None,
-) -> None:
+async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol: str | None = None) -> None:
"""Run one WebSocket session. Wire-compatible with ``tui_gateway.entry``.
- *auth_identity* is the server-minted ``{user_id, provider}`` recorded at
- WS-upgrade auth; stored as ``WSTransport.auth_identity``, the only identity
- authority for browser-controller registration. Callers that omit it
- (harnesses, the embedded TUI child) get a ``None`` transport identity.
+ *auth_identity* is the server-minted ``{user_id, provider}`` recorded at WS-upgrade auth; stored
+ as ``WSTransport.auth_identity``, the only identity authority for browser-controller registration.
+ Callers that omit it (harnesses, the embedded TUI child) get a ``None`` transport identity.
"""
peer = _ws_peer_label(ws)
transport: WSTransport | None = None
@@ -300,50 +269,36 @@ async def handle_ws(
return False
try:
- if subprotocol:
- await ws.accept(subprotocol=subprotocol)
- else:
- await ws.accept()
+ await (ws.accept(subprotocol=subprotocol) if subprotocol else ws.accept())
disconnect_reason = "connected"
- # A client is attached from the moment the upgrade is accepted — mark it
- # before the (possibly slow) ready/skin setup so scale-to-zero sees it.
+ # A client is attached from the moment the upgrade is accepted — mark it before the
+ # (possibly slow) ready/skin setup so scale-to-zero sees it.
_note_dashboard_client_activity(force=True)
_disable_nagle(ws)
_log.info("ws accepted peer=%s", peer)
transport = WSTransport(ws, asyncio.get_running_loop(), peer=peer, auth_identity=auth_identity)
- # resolve_skin() is synchronous I/O + CPU work; run it in the pool so the
- # WS read loop stays free to drain the frontend's initial RPC burst.
+ # resolve_skin() is synchronous I/O + CPU work; run it in the pool so the WS read loop stays
+ # free to drain the frontend's initial RPC burst.
skin_payload = await asyncio.to_thread(server.resolve_skin)
- ready_ok = await transport.write_async(
- {
- "jsonrpc": "2.0",
- "method": "event",
- "params": {
- "type": "gateway.ready",
- # change_events: this backend broadcasts pet/cron/sessions
- # .changed, so clients can demote legacy polls to backstops.
- "payload": {
- "skin": skin_payload,
- "change_events": True,
- "heartbeat": True,
- # Lets reconnecting clients detect a backend restart and
- # reset their per-session seq watermarks (event_replay).
- "replay_epoch": replay_epoch(),
- },
- },
- }
- )
+ # change_events: this backend broadcasts pet/cron/sessions.changed, so clients can demote
+ # legacy polls to backstops. replay_epoch lets reconnecting clients detect a backend restart
+ # and reset their per-session seq watermarks (event_replay).
+ ready_ok = await transport.write_async({
+ "jsonrpc": "2.0", "method": "event",
+ "params": {"type": "gateway.ready", "payload": {
+ "skin": skin_payload, "change_events": True, "heartbeat": True, "replay_epoch": replay_epoch(),
+ }},
+ })
if ready_ok:
- # Live-apply skins Hermes activates mid-conversation, and track this
- # peer for session-less global broadcasts write_json can't route.
+ # Live-apply skins Hermes activates mid-conversation, and track this peer for
+ # session-less global broadcasts write_json can't route.
server._ensure_skin_watcher()
server.register_live_transport(transport)
- # Cross-backend liveness: a heartbeat row lets the startup orphan sweep
- # tell "live but idle backend" from "truly orphaned". Idempotent and
- # once-per-process, like the orphan sweep below (the desktop app and web
- # dashboard reach the agent via this sidecar, not entry.main()).
+ # Cross-backend liveness: a heartbeat row lets the startup orphan sweep tell "live but idle
+ # backend" from "truly orphaned". Idempotent and once-per-process, like the orphan sweep
+ # (the desktop app and web dashboard reach the agent via this sidecar, not entry.main()).
try:
server._start_backend_heartbeat_refresher()
except Exception:
@@ -363,11 +318,7 @@ async def handle_ws(
raw = await ws.receive_text()
_note_dashboard_client_activity()
except _WebSocketDisconnect as exc:
- disconnect_reason = (
- "client_disconnect("
- f"code={getattr(exc, 'code', None)},"
- f"reason={getattr(exc, 'reason', None)})"
- )
+ disconnect_reason = f"client_disconnect(code={getattr(exc, 'code', None)},reason={getattr(exc, 'reason', None)})"
break
except Exception:
disconnect_reason = "receive_failed"
@@ -389,8 +340,7 @@ async def handle_ws(
)
if not await _reply(
_error_frame(-32700, "parse error", None),
- "send_failed_after_parse_error",
- "ws parse-error reply send failed peer=%s", peer,
+ "send_failed_after_parse_error", "ws parse-error reply send failed peer=%s", peer,
):
break
continue
@@ -401,16 +351,14 @@ async def handle_ws(
if req_method == "gateway.ping":
if not await _reply(
{"jsonrpc": "2.0", "result": {"ok": True}, "id": req_id},
- "send_failed_after_heartbeat",
- "ws heartbeat reply send failed peer=%s id=%s", peer, req_id,
+ "send_failed_after_heartbeat", "ws heartbeat reply send failed peer=%s id=%s", peer, req_id,
):
break
continue
- # dispatch() may schedule long handlers on the pool; it returns None
- # then and the worker writes the response itself via transport.write
- # (a separate thread, so that is the safe path). Inline handlers
- # return the response dict, written here from the loop.
+ # dispatch() may schedule long handlers on the pool; it returns None then and the worker
+ # writes the response itself via transport.write (a separate thread, so that is the safe
+ # path). Inline handlers return the response dict, written here from the loop.
try:
resp = await asyncio.to_thread(server.dispatch, req, transport)
except Exception:
@@ -424,8 +372,7 @@ async def handle_ws(
break
continue
if resp is not None and not await _reply(
- resp,
- "send_failed_after_response",
+ resp, "send_failed_after_response",
"ws response send failed peer=%s id=%s method=%s", peer, req_id, req_method,
):
break
@@ -434,12 +381,11 @@ async def handle_ws(
if transport is not None:
server.unregister_live_transport(transport)
- # Owner-safely park browser controllers this transport registered (a
- # reconnect with the same identity may deliver a terminal result for
- # in-flight work; no new dispatch is admitted while offline).
- # Offloaded: disconnect takes the controller's send_lock, which a
- # worker-thread dispatch may hold while blocking on THIS loop to
- # transmit (result(timeout=10)); inline would park the loop behind it.
+ # Owner-safely park browser controllers this transport registered (a reconnect with the
+ # same identity may deliver a terminal result for in-flight work; no new dispatch is
+ # admitted while offline). Offloaded: disconnect takes the controller's send_lock, which
+ # a worker-thread dispatch may hold while blocking on THIS loop to transmit
+ # (result(timeout=10)); inline would park the loop behind it.
try:
from gateway.browser_control_broker import get_browser_control_broker
@@ -454,11 +400,10 @@ async def handle_ws(
except Exception:
_log.exception("ws wake-word teardown failed peer=%s", peer)
- # The single WS-disconnect teardown path: reap sessions this transport
- # owned (close_on_disconnect sidecars) or detach the rest to the drop
- # sentinel so later emits don't hit a closed socket; detached ones go
- # to the grace-windowed orphan reaper (a quick resume cancels it).
- # Offloaded: worker.close() blocks (terminate + waits) plus a sync DB
+ # The single WS-disconnect teardown path: reap sessions this transport owned
+ # (close_on_disconnect sidecars) or detach the rest to the drop sentinel so later emits
+ # don't hit a closed socket; detached ones go to the grace-windowed orphan reaper (a quick
+ # resume cancels it). Offloaded: worker.close() blocks (terminate + waits) plus a sync DB
# write, which inline would freeze the loop for every other peer.
try:
reaped_sessions, detached_sessions = await asyncio.to_thread(