Skip to content

The agent that grows with you

refactor(tui): compact peripheral modules (compute_host, entry, hosted_room_*, ws, project_tree, ...); add _env knobs and method_ctx.bind_module

Teknium93fead86dda6
diff --git a/tui_gateway/_env.py b/tui_gateway/_env.py
new file mode 100644
index 00000000000..481edfac63c
--- /dev/null
+++ b/tui_gateway/_env.py
@@ -0,0 +1,24 @@
+"""Tolerant env-var knob parsing shared by the gateway entry points.
+
+A bare ``float(os.environ[...])`` would raise at import time on a typo
+(``HERMES_SLASH_WATCHDOG_POLL_S=2s``) and kill a worker before it serves a
+single command; these fall back to ``default`` on absent/empty/malformed values.
+"""
+
+from __future__ import annotations
+
+import os
+
+
+def env_float(name: str, default: float) -> float:
+ try:
+ return float(os.environ.get(name, "") or default)
+ except (TypeError, ValueError):
+ return default
+
+
+def env_int(name: str, default: int) -> int:
+ try:
+ return int(os.environ.get(name, "") or default)
+ except (TypeError, ValueError):
+ return default
diff --git a/tui_gateway/_stdin_recovery.py b/tui_gateway/_stdin_recovery.py
index 80c77aeb0dc..1f07c52bacd 100644
--- a/tui_gateway/_stdin_recovery.py
+++ b/tui_gateway/_stdin_recovery.py
@@ -1,119 +1,92 @@
"""Shared spurious stdin-EOF recovery for the TUI gateway entry point and slash worker.
-When a child process inherits fd 0 (stdin) and sets ``O_NONBLOCK``, the flag
-lands on the **shared open file description** — not just the child's descriptor.
-The gateway's next ``read()`` returns ``EAGAIN``, which CPython's buffered
-``TextIOWrapper`` converts to ``b''`` (apparent EOF), killing the gateway.
-
-This module provides:
-- :func:`diagnose_stdin_state` — forensic diagnostic (``O_NONBLOCK`` / ``SO_RCVTIMEO``)
-- :func:`handle_spurious_eof` — check whether an empty ``readline()`` is a genuine
- peer-close or a spurious EOF, and recover if spurious.
-
-The recovery is **POSIX-only** (``fcntl``). On Windows, ``O_NONBLOCK`` on a
-shared file description is not a concern, so the guard simply reports a
+When a child inherits fd 0 and sets ``O_NONBLOCK``, the flag lands on the
+**shared open file description**, not just the child's descriptor. The next
+``read()`` returns ``EAGAIN``, which CPython's buffered ``TextIOWrapper``
+converts to ``b''`` (apparent EOF), killing the gateway.
+
+Recovery is **POSIX-only** (``fcntl``); on Windows the guard just reports a
genuine EOF and lets the caller exit.
"""
from __future__ import annotations
import os
+import socket
+import struct
import time
try:
- import fcntl as _fcntl
- _HAS_FCNTL = True
-except ImportError:
- _fcntl = None # type: ignore[assignment]
- _HAS_FCNTL = False
+ import fcntl
+except ImportError: # Windows
+ fcntl = None # type: ignore[assignment]
-try:
- import socket as _socket
- _HAS_SOCKET = True
-except ImportError:
- _socket = None # type: ignore[assignment]
- _HAS_SOCKET = False
-import struct
+# At most this many recoveries per 60s window. A child aggressively flipping
+# the flag would otherwise create a tight busy-loop; exceeding the cap exits so
+# the parent respawns us with fresh state.
+MAX_RECOVERIES_PER_MINUTE = 10
-# Rate-limit: at most this many spurious-EOF recoveries per 60-second window.
-# A child aggressively flipping ``O_NONBLOCK`` on the shared fd would otherwise
-# create a tight busy-loop burning CPU. Exceeding the cap exits the process —
-# the parent (TUI / gateway) respawns it with fresh state, which is safer than
-# fighting forever.
-MAX_RECOVERIES_PER_MINUTE = 10
+def _stdin_nonblock() -> bool:
+ try:
+ return bool(fcntl.fcntl(0, fcntl.F_GETFL) & os.O_NONBLOCK) # type: ignore[union-attr]
+ except Exception:
+ return False
+
+
+def _stdin_sockopt(getter):
+ """Run ``getter(sock)`` against a dup of fd 0 as a socket; None on failure.
+
+ ``fromfd`` dups the fd, so ``close`` releases the dup without touching fd 0.
+ """
+ try:
+ s = socket.fromfd(0, socket.AF_UNIX, socket.SOCK_STREAM)
+ except Exception:
+ return None
+ try:
+ return getter(s)
+ except Exception:
+ return None
+ finally:
+ s.close()
def diagnose_stdin_state() -> str:
- """Return a diagnostic string about stdin's current state.
+ """Diagnostic string (``O_NONBLOCK`` / ``SO_RCVTIMEO``) for crash-log forensics.
- Used for crash-log forensics when stdin iteration falls through.
- Distinguishes genuine peer-close (flag clear) from spurious EOF
- caused by a child setting ``O_NONBLOCK`` on the shared file description.
+ ``SO_RCVTIMEO`` is a socket option equally shared on the open file
+ description; a child's ``setsockopt`` launders into the same spurious-EOF
+ path with ``O_NONBLOCK`` clear, so it is reported alongside the flag.
"""
parts: list[str] = []
- if _HAS_FCNTL and _fcntl is not None:
+ if fcntl is None:
+ parts.append("O_NONBLOCK=n/a (no fcntl)")
+ else:
try:
- flags = _fcntl.fcntl(0, _fcntl.F_GETFL)
+ flags = fcntl.fcntl(0, fcntl.F_GETFL)
parts.append(f"O_NONBLOCK={'1' if flags & os.O_NONBLOCK else '0'}")
except Exception as e:
parts.append(f"F_GETFL error: {e}")
- else:
- parts.append("O_NONBLOCK=n/a (no fcntl)")
- # ``SO_RCVTIMEO`` is a socket option (not a file-status flag), equally
- # shared on the open file description. A child setting it via
- # ``setsockopt`` launders into the same spurious-EOF path with
- # ``O_NONBLOCK`` clear, so we report it alongside the flag.
- if _HAS_SOCKET and _socket is not None:
- try:
- s = _socket.fromfd(0, _socket.AF_UNIX, _socket.SOCK_STREAM)
- try:
- tv = s.getsockopt(_socket.SOL_SOCKET, _socket.SO_RCVTIMEO)
- parts.append(f"SO_RCVTIMEO={tv!r}")
- finally:
- # ``fromfd`` duped the fd; ``close`` releases the dup without
- # touching the original fd 0.
- s.close()
- except Exception:
- pass
+ tv = _stdin_sockopt(lambda s: s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO))
+ if tv is not None:
+ parts.append(f"SO_RCVTIMEO={tv!r}")
return ", ".join(parts) if parts else "unknown"
-def handle_spurious_eof(
- recovery_times: list[float],
- log_fn: object,
-) -> bool:
+def handle_spurious_eof(recovery_times: list[float], log_fn: object) -> bool:
"""Check whether an empty ``readline()`` is spurious; recover if so.
- Returns ``True`` if the caller should ``continue`` the read loop
- (spurious EOF was recovered), ``False`` if it should ``break`` (genuine
- peer-close or rate limit exceeded).
-
- ``log_fn`` is called with a diagnostic string — ``_log_exit`` in
- ``entry.py``, ``print(file=sys.stderr)`` in ``slash_worker.py``.
+ Returns True if the caller should ``continue`` the read loop (recovered),
+ False if it should ``break`` (genuine peer-close or rate limit exceeded).
+ ``log_fn`` receives a diagnostic string.
"""
- # Without ``fcntl`` (Windows) we can't check the flag, and the
- # ``O_NONBLOCK`` shared-description issue is POSIX-specific anyway —
- # treat it as a genuine EOF.
- if not (_HAS_FCNTL and _fcntl is not None):
+ # Without fcntl (Windows) we can't check the flag, and the issue is
+ # POSIX-specific anyway; a clear flag means a genuine peer-close.
+ if fcntl is None or not _stdin_nonblock():
log_fn("stdin EOF (peer closed)") # type: ignore[operator]
return False
- try:
- flags = _fcntl.fcntl(0, _fcntl.F_GETFL)
- is_nonblock = bool(flags & os.O_NONBLOCK)
- except Exception:
- is_nonblock = False
-
- if not is_nonblock:
- # Genuine peer-close — no subprocess flag tampering detected.
- log_fn("stdin EOF (peer closed)") # type: ignore[operator]
- return False
-
- # Spurious EOF: a child set ``O_NONBLOCK`` (and/or ``SO_RCVTIMEO``) on
- # the shared file description, laundered into ``b''`` / ``EAGAIN`` by
- # CPython's buffered layer. Restore blocking mode and resume.
now = time.time()
recovery_times.append(now)
recovery_times[:] = [t for t in recovery_times if t > now - 60]
@@ -124,28 +97,14 @@ def handle_spurious_eof(
)
return False
- diag = diagnose_stdin_state()
- log_fn(f"stdin spurious EOF (subprocess O_NONBLOCK flip), recovering: {diag}") # type: ignore[operator]
+ log_fn(f"stdin spurious EOF (subprocess O_NONBLOCK flip), recovering: {diagnose_stdin_state()}") # type: ignore[operator]
- # Clear ``O_NONBLOCK`` on the shared file description.
+ # Restore blocking mode on the shared description, and clear SO_RCVTIMEO too:
+ # a non-zero timeout would make the next readline() return '' again, looping
+ # until the rate limiter fires.
os.set_blocking(0, True)
+ _stdin_sockopt(lambda s: s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack("ll", 0, 0)))
- # Also clear ``SO_RCVTIMEO`` if it was set by a child on the shared
- # description. A non-zero timeout would cause the next ``readline()``
- # to time out and return ``''`` again, looping until the rate limiter
- # kicks in. Clearing it restores fully blocking semantics.
- if _HAS_SOCKET and _socket is not None:
- try:
- s = _socket.fromfd(0, _socket.AF_UNIX, _socket.SOCK_STREAM)
- try:
- # Zero timeval: tv_sec=0, tv_usec=0 (struct timeval on most platforms)
- s.setsockopt(_socket.SOL_SOCKET, _socket.SO_RCVTIMEO, struct.pack("ll", 0, 0))
- finally:
- s.close()
- except Exception:
- pass
-
- # ``_io.TextIOWrapper.readline`` returns an empty string on ``EAGAIN``
- # but does NOT stick EOF; after restoring blocking, the next call will
- # block until data arrives or the peer truly closes.
+ # TextIOWrapper.readline returns '' on EAGAIN but does NOT stick EOF; the
+ # next call blocks until data arrives or the peer truly closes.
return True
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 0a0da9a40bd..8b5205809a1 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -23,6 +23,7 @@ from pathlib import Path
from typing import Any, Callable, Collection
from agent.interrupt_compat import request_hard_interrupt
+from tui_gateway.host_supervisor import MUTATOR_ROUTE_TABLE, _build_sha
def now_ns() -> int:
@@ -70,11 +71,7 @@ class SpikeAgent:
final = "".join(chunks)
if interrupted:
final += "[interrupted]"
- messages = [
- *base_history,
- {"role": "user", "content": prompt},
- {"role": "assistant", "content": final},
- ]
+ messages = [*base_history, {"role": "user", "content": prompt}, {"role": "assistant", "content": final}]
self.history = messages
return {"final_response": final, "messages": messages, "interrupted": interrupted}
@@ -94,11 +91,9 @@ class _HostTransport:
def write(self, obj: dict) -> bool:
sid = ""
- try:
+ with contextlib.suppress(Exception):
if obj.get("method") == "event":
sid = str(((obj.get("params") or {}).get("session_id")) or "")
- except Exception:
- sid = ""
self._emit({"type": "rpc", "sid": sid, "message": obj})
return True
@@ -106,34 +101,27 @@ class _HostTransport:
return None
-def _repo_root() -> Path:
- return Path(__file__).resolve().parents[1]
-
-
-def _build_sha() -> str:
- try:
- return subprocess.check_output(
- ["git", "rev-parse", "HEAD"],
- cwd=str(_repo_root()),
- text=True,
- encoding="utf-8",
- errors="replace",
- stderr=subprocess.DEVNULL,
- timeout=2,
- ).strip()
- except Exception:
- return "unknown"
-
-
# Slice of ``ComputeHost.shutdown``'s budget held back for the post-drain
# finalize. ``HostSupervisor._terminate_pid`` SIGKILLs the host
-# ``_SHUTDOWN_TIMEOUT_SECS`` (10s — the same value as ``shutdown``'s default
-# ``wait``) after SIGTERM, so a drain allowed to consume the whole budget would
-# leave the flush racing that kill and persist nothing at all.
+# ``_SHUTDOWN_TIMEOUT_SECS`` (10s, same as ``shutdown``'s default ``wait``)
+# after SIGTERM, so a drain allowed to consume the whole budget would leave the
+# flush racing that kill and persist nothing at all.
_FLUSH_RESERVE_SECS = 1.0
class ComputeHost:
+ # frame ``type`` -> handler method name (resolved per call so instance
+ # monkeypatches of a handler still take effect).
+ _FRAME_HANDLERS: dict[str, str] = {
+ "session.seed": "_handle_seed",
+ "turn.start": "_handle_turn_start",
+ "interrupt": "_handle_interrupt",
+ "respond": "_handle_respond",
+ "reload_mcp": "_handle_reload_mcp",
+ "control": "_handle_control",
+ "shutdown": "_handle_shutdown",
+ }
+
def __init__(
self,
*,
@@ -154,8 +142,8 @@ class ComputeHost:
self._progress_counter = 0
self._progress_lock = threading.Lock()
# Future -> the ``sid`` whose turn it is running. ``shutdown`` needs to
- # know *whose* turn is still live, not merely that something is, so that
- # it can leave those sessions unfinalized; a bare set cannot answer that.
+ # know *whose* turn is still live so it can leave those sessions
+ # unfinalized; a bare set cannot answer that.
self._turn_futures: dict[concurrent.futures.Future, str] = {}
self._turn_futures_lock = threading.Lock()
self._transport = _HostTransport(self.emit)
@@ -181,44 +169,29 @@ class ComputeHost:
def shutdown(self, *, reason: str = "shutdown", wait: float = 10.0) -> None:
"""Drain in-flight turns, then finalize every session.
- Order matters. ``_finalize_session`` is a one-shot latch: it sets
- ``session["_finalized"]`` and every later call returns immediately, so
- the flush gets exactly one chance to snapshot the session. Running it
- before the drain meant that chance was spent while turns were still
- producing output — the tail was unpersistable, ``on_session_end`` fired
- with ``interrupted=True`` against a session that was still running, and
- the active-session lease was released out from under a live turn. The
- drain loop exists precisely so that work survives; finalizing first
- defeated it.
-
- ``_FLUSH_RESERVE_SECS`` of the budget — but never more than half of it,
- so a short explicit ``wait`` still gets a real drain — is withheld from
- the drain, so the flush still runs when in-flight turns outlast the
- window. ``wait`` itself is unchanged, so this adds no shutdown latency
- and no new exposure to the supervisor's kill escalation.
-
- Sessions whose turn is *still running* when the drain deadline expires
- are excluded from that flush. Finalizing one would spend its single
- latch mid-turn — ``shutdown(wait=False, cancel_futures=True)`` below
- does not join the turn — leaving the session permanently
- un-finalizable and its active-session lease released out from under
- live work: exactly the race the drain exists to close, just moved later.
- Leaving them unfinalized keeps them recoverable instead. Sessions with
- no live turn finalize here as they always have.
-
- NOTE: ``server._shutdown_sessions`` is registered via ``atexit``
- (``server.py``) and runs on ``SystemExit`` after ``shutdown()``
- returns. It calls ``_finalize_session`` on any session still in
- ``server._sessions`` — including ones skipped here whose turn is
- still running, since ``_executor.shutdown(wait=False)`` only cancels
- pending futures, not running ones. The orphan path (``os._exit(0)``)
- bypasses atexit, so the skip is fully effective there. For the
- SIGTERM and stdin_closed paths the atexit handler may re-finalize
- skipped sessions; this is a pre-existing issue (the old finalize-
- first order had the same atexit interaction) and does not make the
- drain-before-finalize reordering worse. A follow-up could gate
- ``_shutdown_sessions`` on ``not session.get("_finalized") and not
- session.get("running")`` to close the gap.
+ Order matters: ``_finalize_session`` is a one-shot latch (sets
+ ``session["_finalized"]``), so finalizing before the drain would spend
+ the flush's single chance while turns were still producing output,
+ fire ``on_session_end(interrupted=True)`` against a running session and
+ release the active-session lease under a live turn.
+
+ ``_FLUSH_RESERVE_SECS`` of the budget (never more than half, so a short
+ explicit ``wait`` still gets a real drain) is withheld from the drain so
+ the flush still runs when in-flight turns outlast the window; ``wait``
+ itself is unchanged, so no added latency or kill-escalation exposure.
+
+ Sessions whose turn is *still running* at the drain deadline are
+ excluded from the flush: finalizing one mid-turn (``_executor.shutdown``
+ below does not join it) would leave it permanently un-finalizable with
+ its lease released — the very race the drain closes. Leaving them
+ unfinalized keeps them recoverable.
+
+ NOTE: ``server._shutdown_sessions`` (atexit) runs after ``shutdown()``
+ returns on the SIGTERM / stdin_closed paths and may re-finalize skipped
+ sessions still in ``server._sessions``; the orphan path (``os._exit``)
+ bypasses atexit. Pre-existing gap, not worsened by this ordering; a
+ follow-up could gate ``_shutdown_sessions`` on
+ ``not _finalized and not running``.
"""
self._closed.set()
budget = max(0.0, wait)
@@ -232,8 +205,7 @@ class ComputeHost:
if not pending:
break
# Bounded by ``remaining``: a flat 0.05s sleep would overshoot the
- # deadline and eat into the reserve it is there to protect, which
- # for a small ``wait`` can be the whole of it.
+ # deadline and eat the reserve it protects (all of it for small ``wait``).
time.sleep(min(0.05, remaining))
with self._turn_futures_lock:
live_sids = {sid for future, sid in self._turn_futures.items() if sid and not future.done()}
@@ -246,11 +218,8 @@ class ComputeHost:
reason: str = "shutdown",
skip_sids: Collection[str] | None = None,
) -> None:
- """Finalize every server session except the ones named in ``skip_sids``.
-
- ``skip_sids`` carries the sessions whose turn is still live, which must
- not spend their one-shot ``_finalize_session`` while running.
- """
+ """Finalize every server session except ``skip_sids`` (sessions whose
+ turn is still live and must not spend their one-shot finalize)."""
try:
from tui_gateway import server
except Exception:
@@ -259,39 +228,23 @@ class ComputeHost:
for sid, session in list(getattr(server, "_sessions", {}).items()):
if sid in skip:
continue
- try:
+ with contextlib.suppress(Exception):
server._finalize_session(session, end_reason=f"compute_host_{reason}")
- except Exception:
- pass
def handle_frame(self, frame: dict[str, Any]) -> None:
kind = str(frame.get("type") or "")
- if kind == "session.seed":
- self._handle_seed(frame)
- elif kind == "turn.start":
- self._handle_turn_start(frame)
- elif kind == "interrupt":
- self._handle_interrupt(frame)
- elif kind == "respond":
- self._handle_respond(frame)
- elif kind == "reload_mcp":
- self._handle_reload_mcp(frame)
- elif kind == "control":
- self._handle_control(frame)
- elif kind == "shutdown":
- self.emit({"type": "shutdown.ack", "request_id": frame.get("request_id")})
- # Explicit supervisor/test shutdown is a clean child-process close;
- # SIGTERM and orphan paths are the durability flush paths.
- self._closed.set()
- self._executor.shutdown(wait=False, cancel_futures=True)
- else:
- self.emit(
- {
- "type": "error",
- "request_id": frame.get("request_id"),
- "message": f"unknown frame type: {kind}",
- }
- )
+ handler = self._FRAME_HANDLERS.get(kind)
+ if handler is None:
+ self.emit({"type": "error", "request_id": frame.get("request_id"), "message": f"unknown frame type: {kind}"})
+ return
+ getattr(self, handler)(frame)
+
+ def _handle_shutdown(self, frame: dict[str, Any]) -> None:
+ self.emit({"type": "shutdown.ack", "request_id": frame.get("request_id")})
+ # Explicit supervisor/test shutdown is a clean child-process close;
+ # SIGTERM and orphan paths are the durability flush paths.
+ self._closed.set()
+ self._executor.shutdown(wait=False, cancel_futures=True)
# ── Phase-0 deterministic spike frames ─────────────────────────────
@@ -307,12 +260,8 @@ class ComputeHost:
self.emit({"type": "session.seeded", "sid": sid, "request_id": frame.get("request_id")})
def _track_turn_future(self, future: concurrent.futures.Future, sid: str) -> None:
- """Register an in-flight turn against the session running it.
-
- The callback has to remove the entry under the lock — a bare
- ``dict.pop`` bound method is not the drop-in ``set.discard`` was — or
- the mapping grows for the life of the host.
- """
+ """Register an in-flight turn against the session running it; the done
+ callback must pop under the lock or the mapping grows for the host's life."""
with self._turn_futures_lock:
self._turn_futures[future] = sid
future.add_done_callback(self._untrack_turn_future)
@@ -345,34 +294,26 @@ class ComputeHost:
def _handle_interrupt(self, frame: dict[str, Any]) -> None:
sid = str(frame.get("sid") or "")
+ request_id = frame.get("request_id")
spike = self._sessions.get(sid)
if spike is not None:
request_hard_interrupt(spike.agent)
- self.emit(
- {
- "type": "interrupt.ack",
- "sid": sid,
- "request_id": frame.get("request_id"),
- "applied": True,
- "applied_ns": now_ns(),
- }
- )
+ self.emit({"type": "interrupt.ack", "sid": sid, "request_id": request_id, "applied": True, "applied_ns": now_ns()})
return
try:
from tui_gateway import server
session = server._sessions.get(sid)
if session is None:
- self.emit({"type": "interrupt.ack", "sid": sid, "request_id": frame.get("request_id"), "applied": False})
+ self.emit({"type": "interrupt.ack", "sid": sid, "request_id": request_id, "applied": False})
return
- # In the child, `_session_uses_compute_host()` is false, so the
- # shared helper interrupts the local agent and releases this
- # process's pending clarify Event. The parent has only a metadata
- # mirror and cannot release the prompt that is blocking the turn.
+ # In the child, `_session_uses_compute_host()` is false, so the shared
+ # helper interrupts the local agent and releases this process's pending
+ # clarify Event; the parent only has a metadata mirror and cannot.
server._interrupt_session_turn(sid, session)
- self.emit({"type": "interrupt.ack", "sid": sid, "request_id": frame.get("request_id"), "applied": True, "applied_ns": now_ns()})
+ self.emit({"type": "interrupt.ack", "sid": sid, "request_id": request_id, "applied": True, "applied_ns": now_ns()})
except Exception as exc:
- self.emit({"type": "interrupt.ack", "sid": sid, "request_id": frame.get("request_id"), "applied": False, "message": str(exc)})
+ self.emit({"type": "interrupt.ack", "sid": sid, "request_id": request_id, "applied": False, "message": str(exc)})
def _handle_respond(self, frame: dict[str, Any]) -> None:
"""Resolve an interactive request in the host-owned pending registry."""
@@ -382,56 +323,22 @@ class ComputeHost:
from tui_gateway import server
if sid not in server._sessions:
- self.emit(
- {
- "type": "respond.error",
- "sid": sid,
- "request_id": request_id,
- "message": "session not found",
- }
- )
+ self.emit({"type": "respond.error", "sid": sid, "request_id": request_id, "message": "session not found"})
return
params = frame.get("params")
if not isinstance(params, dict):
- self.emit(
- {
- "type": "respond.error",
- "sid": sid,
- "request_id": request_id,
- "message": "response params must be an object",
- }
- )
+ self.emit({"type": "respond.error", "sid": sid, "request_id": request_id, "message": "response params must be an object"})
return
response = server._methods["clarify.respond"](request_id, params)
- self.emit(
- {
- "type": "respond.ack",
- "sid": sid,
- "request_id": request_id,
- "response": response,
- }
- )
+ self.emit({"type": "respond.ack", "sid": sid, "request_id": request_id, "response": response})
except Exception as exc:
- self.emit(
- {
- "type": "respond.error",
- "sid": sid,
- "request_id": request_id,
- "message": str(exc),
- }
- )
+ self.emit({"type": "respond.error", "sid": sid, "request_id": request_id, "message": str(exc)})
def _run_spike_turn(self, session: HostSession, frame: dict[str, Any]) -> None:
request_id = frame.get("request_id") or uuid.uuid4().hex
prompt = str(frame.get("prompt") or frame.get("text") or "")
- try:
- delta_count = int(frame.get("delta_count", 24))
- except (TypeError, ValueError):
- delta_count = 24
- try:
- delay_s = float(frame.get("delay_s", 0.001))
- except (TypeError, ValueError):
- delay_s = 0.001
+ delta_count = _coerce(frame.get("delta_count", 24), int, 24)
+ delay_s = _coerce(frame.get("delay_s", 0.001), float, 0.001)
with session.lock:
history = list(session.agent.history)
session.agent.clear_interrupt()
@@ -439,15 +346,7 @@ class ComputeHost:
def stream(delta: str) -> None:
self._bump_progress()
- self.emit(
- {
- "type": "delta",
- "sid": session.sid,
- "request_id": request_id,
- "text": delta,
- "emitted_ns": now_ns(),
- }
- )
+ self.emit({"type": "delta", "sid": session.sid, "request_id": request_id, "text": delta, "emitted_ns": now_ns()})
try:
result = session.agent.run_conversation(
@@ -463,15 +362,8 @@ class ComputeHost:
history_version = session.history_version
self._bump_progress()
self.emit(
- {
- "type": "turn.end",
- "sid": session.sid,
- "request_id": request_id,
- "history_version": history_version,
- "message_count": len(result.get("messages") or []),
- "interrupted": bool(result.get("interrupted")),
- "ended_ns": now_ns(),
- }
+ {"type": "turn.end", "sid": session.sid, "request_id": request_id, "history_version": history_version,
+ "message_count": len(result.get("messages") or []), "interrupted": bool(result.get("interrupted")), "ended_ns": now_ns()}
)
except Exception as exc: # pragma: no cover - defensive host boundary
with session.lock:
@@ -490,22 +382,11 @@ class ComputeHost:
from tui_gateway import server
session = self._ensure_server_session(server, frame)
+ text = frame.get("text") if "text" in frame else frame.get("prompt", "")
with session["history_lock"]:
- queued_prompt_generation = frame.get("queued_prompt_generation")
- if (
- queued_prompt_generation is not None
- and int(session.get("_queued_prompt_generation", 0))
- != int(queued_prompt_generation)
- ):
- self.emit(
- {
- "type": "turn.end",
- "sid": sid,
- "request_id": request_id,
- "interrupted": True,
- "ended_ns": now_ns(),
- }
- )
+ queued_gen = frame.get("queued_prompt_generation")
+ if queued_gen is not None and int(session.get("_queued_prompt_generation", 0)) != int(queued_gen):
+ self.emit({"type": "turn.end", "sid": sid, "request_id": request_id, "interrupted": True, "ended_ns": now_ns()})
return
if session.get("running"):
self.emit({"type": "turn.error", "sid": sid, "request_id": request_id, "message": "session busy"})
@@ -515,28 +396,15 @@ class ComputeHost:
session["last_active"] = time.time()
server._start_inflight_turn(session, frame.get("text") if "text" in frame else frame.get("prompt"))
self.emit({"type": "turn.started", "sid": sid, "request_id": request_id, "started_ns": now_ns()})
- try:
+ with contextlib.suppress(Exception):
server._ensure_session_db_row(session)
- except Exception:
- pass
- try:
+ with contextlib.suppress(Exception):
import hermes_undo
hermes_undo.on_user_message_appended(session["session_key"])
- except Exception:
- pass
- try:
+ with contextlib.suppress(Exception):
server._persist_branch_seed(session)
- except Exception:
- pass
- text = frame.get("text") if "text" in frame else frame.get("prompt", "")
- server._run_prompt_submit(
- request_id,
- sid,
- session,
- text,
- display_kind=frame.get("display_kind") or None,
- )
+ server._run_prompt_submit(request_id, sid, session, text, display_kind=frame.get("display_kind") or None)
run_thread = session.get("_run_thread")
if run_thread is not None and hasattr(run_thread, "join"):
run_thread.join()
@@ -548,21 +416,11 @@ class ComputeHost:
session_info = server._session_info(session.get("agent"), session)
self._bump_progress()
self.emit(
- {
- "type": "turn.end",
- "sid": sid,
- "request_id": request_id,
- "history_version": history_version,
- "session_key": session_key,
- "message_count": message_count,
- "interrupted": interrupted,
- "ended_ns": now_ns(),
- "session_info": session_info,
- "session_info_emitted": True,
- }
+ {"type": "turn.end", "sid": sid, "request_id": request_id, "history_version": history_version, "session_key": session_key,
+ "message_count": message_count, "interrupted": interrupted, "ended_ns": now_ns(), "session_info": session_info, "session_info_emitted": True}
)
except Exception as exc:
- try:
+ with contextlib.suppress(Exception):
from tui_gateway import server
session = server._sessions.get(sid)
@@ -570,8 +428,6 @@ class ComputeHost:
with session.get("history_lock", threading.Lock()):
session["running"] = False
server._clear_inflight_turn(session)
- except Exception:
- pass
self.emit({"type": "turn.error", "sid": sid, "request_id": request_id, "reason": "exception", "message": str(exc)})
def _ensure_server_session(self, server: Any, frame: dict[str, Any]) -> dict:
@@ -600,16 +456,14 @@ class ComputeHost:
if profile_home:
from hermes_constants import set_hermes_home_override
from agent.secret_scope import build_profile_secret_scope, set_secret_scope
- from hermes_state import SessionDB
+ from hermes_state import get_shared_session_db
home_token = set_hermes_home_override(profile_home)
secret_token = set_secret_scope(build_profile_secret_scope(Path(profile_home)))
- # DEDICATED handle — ours only until _make_agent succeeds. Every
- # path after that keeps the agent registered in
- # server._sessions[sid] (via _init_session, or the fallback dict
- # in the except below), so the agent is the right owner; a
- # _make_agent that RAISES is the one path where nothing takes it.
- from hermes_state import get_shared_session_db
+ # DEDICATED handle — ours only until _make_agent succeeds; after that
+ # the agent (registered in server._sessions[sid] via _init_session or
+ # the fallback dict below) owns it. A RAISING _make_agent is the one
+ # path where nothing takes it, hence ``owns_db``.
session_db = get_shared_session_db(Path(profile_home) / "state.db")
owns_db = True
agent = server._make_agent(
@@ -620,9 +474,7 @@ class ComputeHost:
reasoning_config_override=frame.get("reasoning_config_override"),
service_tier_override=frame.get("service_tier_override"),
platform_override=frame.get("source"),
- context_cwd_is_launch_artifact=bool(
- frame.get("context_cwd_is_launch_artifact", False)
- ),
+ context_cwd_is_launch_artifact=bool(frame.get("context_cwd_is_launch_artifact", False)),
session_db=session_db,
)
if server._transfer_db_to_agent(agent, session_db):
@@ -631,16 +483,15 @@ class ComputeHost:
if owns_db and session_db is not None:
with contextlib.suppress(Exception):
from hermes_state import release_or_close
+
release_or_close(session_db)
if home_token is not None:
- try:
+ with contextlib.suppress(Exception):
from hermes_constants import reset_hermes_home_override
from agent.secret_scope import reset_secret_scope
reset_hermes_home_override(home_token)
reset_secret_scope(secret_token)
- except Exception:
- pass
try:
from tui_gateway.transport import bind_transport, reset_transport
@@ -709,134 +560,92 @@ class ComputeHost:
sid = str(frame.get("sid") or "")
request_id = frame.get("request_id")
route_name = str(frame.get("route_name") or "")
+
+ def _error(message: str) -> None:
+ self.emit({"type": "control.error", "sid": sid, "request_id": request_id, "message": message})
+
+ def _ack(**extra: Any) -> None:
+ self.emit({"type": "control.ack", "sid": sid, "request_id": request_id, "route_name": route_name, **extra})
+
+ def _call_method(name: str, params: dict[str, Any], failure: str) -> dict | None:
+ """Run a server method; emit control.error and return None on error."""
+ response = server._methods[name](request_id, params)
+ if "error" in response:
+ _error(str(response["error"].get("message") or failure))
+ return None
+ return response
+
try:
from tui_gateway import server
- from tui_gateway.host_supervisor import MUTATOR_ROUTE_TABLE
route = MUTATOR_ROUTE_TABLE.get(route_name)
if route is None:
- self.emit({"type": "control.error", "sid": sid, "request_id": request_id, "message": f"unclassified route: {route_name}"})
+ _error(f"unclassified route: {route_name}")
return
session = server._sessions.get(sid)
if session is None:
- self.emit({"type": "control.error", "sid": sid, "request_id": request_id, "message": "session not found"})
+ _error("session not found")
return
if route == "idle-gated" and session.get("running"):
- self.emit({"type": "control.error", "sid": sid, "request_id": request_id, "message": "session busy"})
+ _error("session busy")
return
if route_name == "reload.mcp":
self._handle_reload_mcp({**frame, "type": "reload_mcp"})
return
if route_name == "session.save":
- response = server._methods["session.save"](
- request_id,
- {"session_id": sid},
- )
- if "error" in response:
- self.emit(
- {
- "type": "control.error",
- "sid": sid,
- "request_id": request_id,
- "message": str(response["error"].get("message") or "session save failed"),
- }
- )
- return
- self.emit(
- {
- "type": "control.ack",
- "sid": sid,
- "request_id": request_id,
- "route_name": route_name,
- "result": response.get("result") or {},
- }
- )
+ response = _call_method("session.save", {"session_id": sid}, "session save failed")
+ if response is not None:
+ _ack(result=response.get("result") or {})
return
if route_name == "session.compress":
- command = str(frame.get("command") or "")
- focus_topic = command.removeprefix("/compress").strip()
- response = server._methods["session.compress"](
- request_id,
- {
- "session_id": sid,
- **({"focus_topic": focus_topic} if focus_topic else {}),
- },
- )
- if "error" in response:
- self.emit(
- {
- "type": "control.error",
- "sid": sid,
- "request_id": request_id,
- "message": str(response["error"].get("message") or "session compression failed"),
- }
- )
+ focus_topic = str(frame.get("command") or "").removeprefix("/compress").strip()
+ params = {"session_id": sid, **({"focus_topic": focus_topic} if focus_topic else {})}
+ response = _call_method("session.compress", params, "session compression failed")
+ if response is None:
return
with session["history_lock"]:
session_key = str(session.get("session_key") or "")
history_version = int(session.get("history_version", 0))
message_count = len(session.get("history") or [])
- self.emit(
- {
- "type": "control.ack",
- "sid": sid,
- "request_id": request_id,
- "route_name": route_name,
- "result": response.get("result") or {},
- "session_key": session_key,
- "history_version": history_version,
- "message_count": message_count,
- "session_info": server._session_info(session.get("agent"), session),
- }
+ _ack(
+ result=response.get("result") or {},
+ session_key=session_key,
+ history_version=history_version,
+ message_count=message_count,
+ session_info=server._session_info(session.get("agent"), session),
)
return
command = str(frame.get("command") or "")
- output = ""
- if command:
- output = server._mirror_slash_side_effects(sid, session, command)
+ output = server._mirror_slash_side_effects(sid, session, command) if command else ""
with session["history_lock"]:
messages = server._history_to_messages(list(session.get("history") or []))
history_version = int(session.get("history_version", 0))
message_count = len(session.get("history") or [])
session_key = str(session.get("session_key") or "")
- self.emit(
- {
- "type": "control.ack",
- "sid": sid,
- "request_id": request_id,
- "route_name": route_name,
- "output": output,
- "session_key": session_key,
- "history_version": history_version,
- "message_count": message_count,
- "messages": messages,
- "session_info": server._session_info(session.get("agent"), session),
- }
+ _ack(
+ output=output,
+ session_key=session_key,
+ history_version=history_version,
+ message_count=message_count,
+ messages=messages,
+ session_info=server._session_info(session.get("agent"), session),
)
except Exception as exc:
if route_name in {"session.compress", "slash.compress"}:
- # The compress mirror defers the context-engine boundary
- # notification until the host commits. If anything raises
- # between queueing and finalize (e.g. building the ack's
- # session_info), discard the pending notification so it can't
- # leak onto the agent and fire against a rejected boundary on
- # a later compress. finalize is exactly-once, so this is a
- # no-op when the mirror already emitted or discarded it.
- try:
+ # The compress mirror defers the context-engine boundary notification
+ # until the host commits. If anything raises between queueing and
+ # finalize (e.g. building the ack's session_info), discard the pending
+ # notification so it can't fire against a rejected boundary on a later
+ # compress. finalize is exactly-once, so this is a no-op if the mirror
+ # already emitted or discarded it.
+ with contextlib.suppress(Exception):
from tui_gateway import server as _server
- from agent.conversation_compression import (
- finalize_context_engine_compression_notification,
- )
+ from agent.conversation_compression import finalize_context_engine_compression_notification
_agent = (_server._sessions.get(sid) or {}).get("agent")
if _agent is not None:
- finalize_context_engine_compression_notification(
- _agent,
- committed=False,
- )
- except Exception:
- pass
- self.emit({"type": "control.error", "sid": sid, "request_id": request_id, "message": str(exc)})
+ finalize_context_engine_compression_notification(_agent, committed=False)
+ _error(str(exc))
def _bump_progress(self) -> None:
with self._progress_lock:
@@ -848,14 +657,7 @@ class ComputeHost:
active_turns = sum(1 for f in self._turn_futures if not f.done())
with self._progress_lock:
counter = self._progress_counter
- self.emit(
- {
- "type": "hb",
- "active_turns": active_turns,
- "progress_counter": counter,
- "rss_mb": _rss_mb(os.getpid()),
- }
- )
+ self.emit({"type": "hb", "active_turns": active_turns, "progress_counter": counter, "rss_mb": _rss_mb(os.getpid())})
def _parent_guard_loop(self) -> None:
while not self._closed.wait(1.0):
@@ -866,6 +668,13 @@ class ComputeHost:
os._exit(0)
+def _coerce(value: Any, cast: Callable[[Any], Any], default: Any) -> Any:
+ try:
+ return cast(value)
+ except (TypeError, ValueError):
+ return default
+
+
def _rss_mb(pid: int) -> float:
try:
out = subprocess.check_output(["ps", "-o", "rss=", "-p", str(pid)], text=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2).strip()
@@ -875,10 +684,7 @@ def _rss_mb(pid: int) -> float:
def _default_workers() -> int:
- try:
- return max(2, int(os.environ.get("HERMES_TUI_RPC_POOL_WORKERS") or "8"))
- except (TypeError, ValueError):
- return 8
+ return _coerce(os.environ.get("HERMES_TUI_RPC_POOL_WORKERS") or "8", lambda v: max(2, int(v)), 8)
def run_host(stdin: Any = None, stdout: Any = None) -> None:
@@ -894,21 +700,13 @@ def run_host(stdin: Any = None, stdout: Any = None) -> None:
host.shutdown(reason="sigterm")
raise SystemExit(0)
- try:
+ with contextlib.suppress(Exception):
signal.signal(signal.SIGTERM, _signal_handler)
signal.signal(signal.SIGINT, _signal_handler)
- except Exception:
- pass
host.emit(
- {
- "type": "hello",
- "host_pid": os.getpid(),
- "boot_id": host._boot_id,
- "build_sha": _build_sha(),
- "cwd": os.getcwd(),
- "hermes_home": os.environ.get("HERMES_HOME", ""),
- }
+ {"type": "hello", "host_pid": os.getpid(), "boot_id": host._boot_id, "build_sha": _build_sha(),
+ "cwd": os.getcwd(), "hermes_home": os.environ.get("HERMES_HOME", "")}
)
def _reader() -> None:
diff --git a/tui_gateway/entry.py b/tui_gateway/entry.py
index 27fd051b8af..f6f82785cb3 100644
--- a/tui_gateway/entry.py
+++ b/tui_gateway/entry.py
@@ -3,9 +3,8 @@ import sys
# Stop a ``utils/`` (or ``proxy/``, ``ui/``) package in the launch directory
# from shadowing Hermes's own top-level modules. ``hermes_bootstrap`` lives at
-# the repo root next to this package, so importing it is safe before the guard
-# runs (its name won't collide with a user package), and it owns the canonical
-# path-hardening logic shared with the other entry points.
+# the repo root (its name can't collide with a user package), so importing it
+# before the guard runs is safe.
import hermes_bootstrap
hermes_bootstrap.harden_import_path()
@@ -17,6 +16,7 @@ import threading
import time
import traceback
+from tui_gateway._env import env_float
from tui_gateway._stdin_recovery import handle_spurious_eof
from tui_gateway import server
@@ -26,133 +26,102 @@ from tui_gateway.transport import TeeTransport
logger = logging.getLogger(__name__)
-# Handle for the background MCP tool-discovery thread (see
-# ensure_mcp_discovery_started). The first agent build briefly joins this so
-# already-spawning fast servers land before the agent snapshots its tool list
-# (see wait_for_mcp_discovery). Stays None when discovery is delegated to the
-# shared owner in hermes_cli.mcp_startup — the wait/in-flight/join helpers
-# below consult both owners.
+# Handle for a background MCP discovery thread spawned by THIS module. Stays
+# None when discovery is delegated to the shared owner in hermes_cli.mcp_startup
+# (the current path); the wait/in-flight/join helpers consult both owners.
_mcp_discovery_thread = None
-# True once ensure_mcp_discovery_started decided this process has MCP servers
-# configured and spawned discovery through the shared owner. Lets
-# wait_for_mcp_discovery re-invoke the (idempotent) spawn on later agent
-# builds so the retry-after-zero-connected allowance in
-# hermes_cli.mcp_startup.start_background_mcp_discovery can actually fire —
-# without this, the single spawn is the only call and a first run that
-# connected nothing latches the process MCP-less. Kept as a flag (rather than
-# re-probing config) so non-MCP sessions never pay the tools.mcp_tool import
-# on the per-agent-build wait path.
+# True once ensure_mcp_discovery_started found MCP servers configured and spawned
+# discovery through the shared owner. Lets wait_for_mcp_discovery re-invoke the
+# idempotent spawn on later agent builds so the retry-after-zero-connected
+# allowance can fire (otherwise a first run that connected nothing latches the
+# process MCP-less). A flag rather than a config re-probe so non-MCP sessions
+# never pay the tools.mcp_tool import on the per-agent-build wait path.
_mcp_discovery_enabled = False
def _install_sidecar_publisher() -> None:
"""Mirror every dispatcher emit to the dashboard sidebar via WS.
- Activated by `HERMES_TUI_SIDECAR_URL`, set by the dashboard's
- ``/api/pty`` endpoint when a chat tab passes a ``channel`` query param.
- Best-effort: connect failure or runtime drop falls back to stdio-only.
+ Activated by `HERMES_TUI_SIDECAR_URL`, set by the dashboard's ``/api/pty``
+ endpoint when a chat tab passes a ``channel`` query param. Best-effort:
+ connect failure or runtime drop falls back to stdio-only.
"""
url = os.environ.get("HERMES_TUI_SIDECAR_URL")
-
if not url:
return
-
from tui_gateway.event_publisher import WsPublisherTransport
- server._stdio_transport = TeeTransport(
- server._stdio_transport, WsPublisherTransport(url)
- )
+ server._stdio_transport = TeeTransport(server._stdio_transport, WsPublisherTransport(url))
-# How long to wait for orderly shutdown (atexit + finalisers) before
-# falling back to ``os._exit(0)`` so a wedged worker mid-flush can't
-# strand the process. 1s covers the gateway's own shutdown work
-# (thread-pool drain + session finalize) on every machine we've
-# tested; override via ``HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S`` if a
-# slower environment needs more headroom (e.g. encrypted disks
-# flushing checkpoints) and accept that a longer grace also means a
-# longer wait when shutdown actually deadlocks.
+# Grace for orderly shutdown (atexit + finalisers) before ``os._exit(0)`` so a
+# wedged worker mid-flush can't strand the process. 1s covers the gateway's own
+# shutdown work; ``HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S`` overrides for slower
+# environments (a longer grace also means a longer wait on a real deadlock).
_DEFAULT_SHUTDOWN_GRACE_S = 1.0
def _shutdown_grace_seconds() -> float:
- raw = (os.environ.get("HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S") or "").strip()
- if not raw:
- return _DEFAULT_SHUTDOWN_GRACE_S
- try:
- value = float(raw)
- except ValueError:
- return _DEFAULT_SHUTDOWN_GRACE_S
+ value = env_float("HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S", _DEFAULT_SHUTDOWN_GRACE_S)
return value if value > 0 else _DEFAULT_SHUTDOWN_GRACE_S
-def _log_signal(signum: int, frame) -> None:
- """Capture WHICH thread and WHERE a termination signal hit us.
-
- SIG_DFL for SIGPIPE kills the process silently the instant any
- background thread (TTS playback, beep, voice status emitter, etc.)
- writes to a stdout the TUI has stopped reading. Without this
- handler the gateway-exited banner in the TUI has no trace — the
- crash log never sees a Python exception because the kernel reaps
- the process before the interpreter runs anything.
-
- Termination semantics: ``sys.exit(0)`` here used to race the worker
- pool — a thread holding ``_stdout_lock`` mid-flush would block the
- interpreter shutdown indefinitely. We now log the stack, give the
- process the configured shutdown grace
- (``HERMES_TUI_GATEWAY_SHUTDOWN_GRACE_S``, default
- ``_DEFAULT_SHUTDOWN_GRACE_S``) to drain naturally on a background
- thread, and fall back to ``os._exit(0)`` so a wedged write/flush
- can never strand the process.
- """
- # SIGPIPE and SIGHUP don't exist on Windows — build the lookup
- # dict from attributes that actually exist on the current platform.
- _signal_names: dict[int, str] = {}
- for _attr in ("SIGPIPE", "SIGTERM", "SIGHUP", "SIGINT", "SIGBREAK"):
- _sig = getattr(signal, _attr, None)
- if _sig is not None:
- _signal_names[int(_sig)] = _attr
- name = _signal_names.get(signum, f"signal {signum}")
+def _stamp() -> str:
+ return time.strftime("%Y-%m-%d %H:%M:%S")
+
+
+def _append_crash_log(header: str, dump=None) -> None:
+ """Best-effort ``=== header ===`` entry in the crash log; ``dump(f)`` adds detail."""
try:
os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
with open(_CRASH_LOG, "a", encoding="utf-8") as f:
- f.write(
- f"\n=== {name} received · {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n"
- )
- if frame is not None:
- f.write("main-thread stack at signal delivery:\n")
- traceback.print_stack(frame, file=f)
- # All live threads — signal may have been triggered by a
- # background thread (write to broken stdout from TTS, etc.).
- import threading as _threading
- for tid, th in _threading._active.items():
- f.write(f"\n--- thread {th.name} (id={tid}) ---\n")
- f.write("".join(traceback.format_stack(sys._current_frames().get(tid))))
+ f.write(f"\n=== {header} ===\n")
+ if dump is not None:
+ dump(f)
except Exception:
pass
- print(f"[gateway-signal] {name}", file=sys.stderr, flush=True)
- import threading as _threading
- def _hard_exit() -> None:
- # If a worker thread is still mid-flush on a half-closed pipe,
- # ``sys.exit(0)`` would wait forever for it to drop the GIL on
- # interpreter shutdown. ``os._exit`` skips atexit handlers but
- # breaks the deadlock. The crash log + stderr line above are
- # the forensic trail.
- os._exit(0)
+def _log_signal(signum: int, frame) -> None:
+ """Capture WHICH thread and WHERE a termination signal hit us, then exit.
+
+ SIG_DFL for SIGPIPE kills the process silently the instant a background
+ thread (TTS, beep, voice status) writes to a stdout the TUI stopped reading,
+ leaving no trace in the crash log. ``sys.exit(0)`` alone used to race the
+ worker pool — a thread holding ``_stdout_lock`` mid-flush blocks interpreter
+ shutdown indefinitely — so we log all thread stacks, give the process the
+ configured grace to drain, and fall back to ``os._exit(0)``.
+ """
+ # SIGPIPE/SIGHUP don't exist on Windows — only look up attributes present.
+ names = {
+ int(sig): attr
+ for attr in ("SIGPIPE", "SIGTERM", "SIGHUP", "SIGINT", "SIGBREAK")
+ if (sig := getattr(signal, attr, None)) is not None
+ }
+ name = names.get(signum, f"signal {signum}")
+
+ def _dump(f):
+ if frame is not None:
+ f.write("main-thread stack at signal delivery:\n")
+ traceback.print_stack(frame, file=f)
+ # All live threads — the signal may have come from a background writer.
+ for tid, th in threading._active.items():
+ f.write(f"\n--- thread {th.name} (id={tid}) ---\n")
+ f.write("".join(traceback.format_stack(sys._current_frames().get(tid))))
+
+ _append_crash_log(f"{name} received · {_stamp()}", _dump)
+ print(f"[gateway-signal] {name}", file=sys.stderr, flush=True)
- timer = _threading.Timer(_shutdown_grace_seconds(), _hard_exit)
+ # ``os._exit`` skips atexit but breaks the mid-flush deadlock; the crash log
+ # + stderr line above are the forensic trail.
+ timer = threading.Timer(_shutdown_grace_seconds(), lambda: os._exit(0))
timer.daemon = True
timer.start()
- # ── Flush sessions before exit ───────────────────────────────────
- # The atexit handler (_shutdown_sessions) is registered in
- # tui_gateway/server.py, but a worker thread holding the GIL or
- # _stdout_lock can block atexit from completing within the grace
- # window. Explicitly finalize sessions here so that unpersisted
- # messages reach state.db before the hard-exit timer fires.
+ # The atexit handler (_shutdown_sessions) can be blocked past the grace
+ # window by a worker holding the GIL/_stdout_lock; finalize explicitly so
+ # unpersisted messages reach state.db before the hard-exit timer fires.
try:
from tui_gateway.server import _shutdown_sessions
@@ -160,114 +129,68 @@ def _log_signal(signum: int, frame) -> None:
except Exception:
pass
- try:
- sys.exit(0)
- except SystemExit:
- # Re-raise so the main-thread interpreter unwinds and runs
- # atexit + finalisers inside the grace window. Python signal
- # handlers always run on the main thread, but a worker thread
- # holding ``_stdout_lock`` mid-flush can keep that unwind
- # waiting indefinitely; the daemon timer above is the safety
- # net for that exact case.
- raise
-
-
-# SIGPIPE: ignore, don't exit. The old SIG_DFL killed the process
-# silently whenever a *background* thread (TTS playback chain, voice
-# debug stderr emitter, beep thread) wrote to a pipe the TUI had gone
-# quiet on — even though the main thread was perfectly fine waiting on
-# stdin. Ignoring the signal lets Python raise BrokenPipeError on the
-# offending write (write_json already handles that with a clean
-# sys.exit(0) + _log_exit), which keeps the gateway alive as long as
-# the main command pipe is still readable. Terminal signals still
-# route through _log_signal so kills and hangups are diagnosable.
-#
-# SIGPIPE and SIGHUP don't exist on Windows; guard each installation
-# with hasattr so ``python -m tui_gateway.entry`` (spawned by
-# ``hermes --tui``) imports cleanly there. SIGBREAK (Windows' Ctrl+Break)
-# is installed when available as a weaker equivalent of SIGHUP.
-#
-# signal.signal() is only legal in the MAIN thread. On the Desktop/WebSocket
-# agent-build path, server._build() runs in a daemon thread and does
-# ``from tui_gateway.entry import ensure_mcp_discovery_started`` as the first
-# import of entry (entry.main() is never run there), which used to raise
-# "ValueError: signal only works in main thread of the main interpreter" and
-# abort MCP discovery startup. Install each handler only when we're in the
-# main thread: handlers are process-global, so a main-thread import anywhere
-# in the process still installs them for everyone, and an off-thread import
-# (Desktop build path) simply no-ops instead of crashing the import. This
-# preserves the original SIG_IGN/SIG_DFL behavior on the classic TUI/serve
-# path while fixing the off-thread import crash.
+ # Unwind the main thread so atexit + finalisers run inside the grace window;
+ # the daemon timer is the safety net if that unwind hangs.
+ sys.exit(0)
def _install_signal(signame, handler):
- """Install a signal handler if legal in this thread.
+ """Install a signal handler if legal in this thread and platform.
- signal.signal() raises ValueError outside the main thread; skip silently
- there so a worker-thread import of this module (Desktop build path) does
- not abort. On any main-thread import the handler is installed as before.
+ signal.signal() raises ValueError outside the main thread; skip silently so a
+ worker-thread first import (Desktop build path: server._build does ``from
+ tui_gateway.entry import ...``) doesn't abort. Handlers are process-global,
+ so any main-thread import installs them for everyone. Missing signals
+ (Windows: SIGPIPE/SIGHUP) are skipped too.
"""
if threading.current_thread() is not threading.main_thread():
return
sig = getattr(signal, signame, None)
if sig is None:
- return # Windows: SIGPIPE/SIGHUP absent
+ return
try:
signal.signal(sig, handler)
except (ValueError, OSError, RuntimeError):
- # Not in the main thread despite the check, or handler rejected.
- # Skip rather than crash the import (see above).
pass
+# SIGPIPE: ignore, don't exit. SIG_DFL killed the process silently whenever a
+# *background* thread wrote to a pipe the TUI had gone quiet on, even with the
+# main thread fine on stdin. Ignoring lets the write raise BrokenPipeError
+# (write_json handles it with a clean sys.exit(0) + _log_exit) so the gateway
+# lives as long as the command pipe is readable. Terminal signals route through
+# _log_signal so kills/hangups are diagnosable; SIGBREAK (Windows Ctrl+Break) is
+# the weaker SIGHUP equivalent.
_install_signal("SIGPIPE", signal.SIG_IGN)
_install_signal("SIGTERM", _log_signal)
if hasattr(signal, "SIGHUP"):
_install_signal("SIGHUP", _log_signal)
elif hasattr(signal, "SIGBREAK"):
- # Windows-only: Ctrl+Break in a console window delivers SIGBREAK.
- # Route it through the same handler so kills are diagnosable.
_install_signal("SIGBREAK", _log_signal)
_install_signal("SIGINT", signal.SIG_IGN)
def _log_exit(reason: str) -> None:
- """Record why the gateway subprocess is shutting down.
-
- Three exit paths (startup write fail, parse-error-response write fail,
- dispatch-response write fail, stdin EOF) all collapse into a silent
- sys.exit(0) here. Without this trail the TUI shows "gateway exited"
- with no actionable clue about WHICH broken pipe or WHICH message
- triggered it — the main reason voice-mode turns look like phantom
- crashes when the real story is "TUI read pipe closed on this event".
+ """Record why the gateway is shutting down.
+
+ Every exit path (startup/parse-error/response write fail, stdin EOF)
+ collapses into a silent sys.exit(0); without this trail the TUI shows
+ "gateway exited" with no clue WHICH broken pipe or message triggered it.
"""
- try:
- os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
- with open(_CRASH_LOG, "a", encoding="utf-8") as f:
- f.write(
- f"\n=== gateway exit · {time.strftime('%Y-%m-%d %H:%M:%S')} "
- f"· reason={reason} ===\n"
- )
- except Exception:
- pass
+ _append_crash_log(f"gateway exit · {_stamp()} · reason={reason}")
print(f"[gateway-exit] {reason}", file=sys.stderr, flush=True)
def wait_for_mcp_discovery(timeout: "float | None" = None) -> None:
"""Block until background MCP discovery finishes, up to the resolved bound.
- MCP discovery runs in a daemon thread spawned at startup (see main()) so a
- slow/dead server can't freeze ``gateway.ready``. But the agent snapshots
- its tool list ONCE at build time and never re-reads it, so a reachable-but-
- slow server that finishes connecting *after* the first prompt would be
- invisible for the whole session. Joining with a bounded timeout before the
- first agent build lets already-spawning servers land without re-introducing
- the startup hang: ``thread.join(timeout)`` returns the instant discovery
- completes (so fast/no-MCP startups pay ~0s), and a dead server is simply not
- waited on beyond the bound. No-op when no discovery thread was started.
-
- The bound comes from ``mcp_discovery_timeout`` in config (shared with the
- CLI path via ``hermes_cli.mcp_startup``); ``timeout`` overrides it.
+ Discovery runs in a daemon thread so a slow/dead server can't freeze
+ ``gateway.ready``, but the agent snapshots its tool list ONCE at build time.
+ Joining with a bounded timeout before the first build lets already-spawning
+ servers land (join returns the instant discovery completes, so no-MCP
+ startups pay ~0s) without re-introducing the startup hang. The bound is
+ ``mcp_discovery_timeout`` from config (via ``hermes_cli.mcp_startup``);
+ ``timeout`` overrides it.
"""
thread = _mcp_discovery_thread
if thread is not None and thread.is_alive():
@@ -279,34 +202,22 @@ def wait_for_mcp_discovery(timeout: "float | None" = None) -> None:
bound = timeout if timeout is not None else 0.75
thread.join(timeout=bound)
return
- # Discovery is spawned via the shared owner (ensure_mcp_discovery_started
- # → hermes_cli.mcp_startup); wait on it so the first agent build still
- # catches fast servers. Re-invoke the idempotent spawn first: if the
- # previous run finished with zero connected servers,
- # start_background_mcp_discovery's retry-after-zero-connected allowance
- # kicks off a fresh discovery run here instead of leaving the process
- # latched MCP-less for the session. In multi-profile processes this
- # retry runs under the CALLER's profile context (agent build binds the
- # session profile's HERMES_HOME first), so a launch profile with no
- # mcp_servers no longer starves selected profiles of discovery (#67605).
- # Gated on _mcp_discovery_enabled so non-MCP sessions never pay the
- # tools.mcp_tool import on the per-agent-build wait path.
+ # Shared-owner path. Re-invoke the idempotent spawn first: if the previous
+ # run connected zero servers, the retry allowance starts a fresh run instead
+ # of leaving the process latched MCP-less. It runs under the CALLER's
+ # profile context (agent build binds the session profile's HERMES_HOME
+ # first), so a launch profile without mcp_servers doesn't starve selected
+ # profiles. Gated so non-MCP sessions never pay the tools.mcp_tool import.
if not _mcp_discovery_enabled:
return
try:
from hermes_cli.mcp_startup import start_background_mcp_discovery
- start_background_mcp_discovery(
- logger=logger, thread_name="tui-mcp-discovery"
- )
+ start_background_mcp_discovery(logger=logger, thread_name="tui-mcp-discovery")
except Exception:
- logger.debug(
- "TUI MCP discovery retry-spawn failed", exc_info=True
- )
+ logger.debug("TUI MCP discovery retry-spawn failed", exc_info=True)
try:
- from hermes_cli.mcp_startup import (
- wait_for_mcp_discovery as _startup_wait,
- )
+ from hermes_cli.mcp_startup import wait_for_mcp_discovery as _startup_wait
_startup_wait(timeout)
except Exception:
@@ -314,30 +225,20 @@ def wait_for_mcp_discovery(timeout: "float | None" = None) -> None:
def mcp_discovery_in_flight() -> bool:
- """Return True if ANY background MCP discovery thread is still running.
-
- Used by the agent-build path to decide whether to schedule a late tool
- snapshot refresh: if discovery didn't land within the bounded
- ``wait_for_mcp_discovery`` join, the agent was built without those tools
- and the banner/tool count will be stale until they arrive.
-
- There are two independent discovery-thread owners by surface: the stdio
- ``hermes --tui`` path spawns ITS thread here (``_mcp_discovery_thread``),
- while the desktop app + dashboard WebSocket sidecar (``tui_gateway/ws.py``)
- and ``hermes dashboard`` spawn theirs via
- ``hermes_cli.mcp_startup.start_background_mcp_discovery``. The late-refresh
- scheduler imports this function regardless of surface, so it MUST consult
- both — checking only the entry thread left the desktop/dashboard surfaces
- with no late refresh, so a slow MCP server's tools never surfaced for the
- whole session (#51587).
+ """True if ANY background MCP discovery thread is still running.
+
+ The agent-build path uses this to schedule a late tool-snapshot refresh when
+ discovery didn't land within the bounded join. There are two owners by
+ surface — the stdio ``hermes --tui`` thread here and the
+ ``hermes_cli.mcp_startup`` thread used by desktop/dashboard — and the
+ late-refresh scheduler imports this regardless of surface, so it MUST
+ consult both or slow MCP servers' tools never surface on desktop.
"""
thread = _mcp_discovery_thread
if thread is not None and thread.is_alive():
return True
try:
- from hermes_cli.mcp_startup import (
- mcp_discovery_in_flight as _startup_in_flight,
- )
+ from hermes_cli.mcp_startup import mcp_discovery_in_flight as _startup_in_flight
return _startup_in_flight()
except Exception:
@@ -345,17 +246,11 @@ def mcp_discovery_in_flight() -> bool:
def join_mcp_discovery(timeout: float | None = None) -> bool:
- """Block until background MCP discovery finishes, up to ``timeout`` seconds.
-
- Returns True if discovery has completed (both thread owners absent or no
- longer alive), False if either is still running after the timeout. Unlike
- ``wait_for_mcp_discovery`` this accepts an unbounded/long wait and reports
- the outcome, for the off-critical-path late-refresh waiter.
+ """Join both discovery owners; True once neither is alive.
- Joins both discovery-thread owners (see ``mcp_discovery_in_flight``): the
- entry thread first, then the ``hermes_cli.mcp_startup`` thread used by the
- desktop/dashboard surfaces. ``timeout`` bounds EACH join, mirroring the
- pre-#51587 single-owner behavior for the entry thread.
+ Unlike ``wait_for_mcp_discovery`` this accepts an unbounded/long wait and
+ reports the outcome (for the off-critical-path late-refresh waiter).
+ ``timeout`` bounds EACH join: entry thread first, then the shared owner.
"""
entry_done = True
thread = _mcp_discovery_thread
@@ -375,7 +270,6 @@ def join_mcp_discovery(timeout: float | None = None) -> bool:
_recovery_times: list[float] = []
-
def _has_configured_mcp_servers() -> bool:
"""Delegate to the shared native and portable MCP startup gate."""
from hermes_cli.mcp_startup import _has_configured_mcp_servers as configured
@@ -386,21 +280,14 @@ def _has_configured_mcp_servers() -> bool:
def ensure_mcp_discovery_started() -> None:
"""Start background MCP discovery for the current profile context, once.
- ``main()`` calls this for the stdio/TUI path. WebSocket/Desktop
- entrypoints can accept sessions without running ``main()``, so the
- agent-build path (``server._start_agent_build``) also calls it AFTER
- binding the session profile's HERMES_HOME override — the shared owner in
- ``hermes_cli.mcp_startup`` captures the caller's context-local override
- and propagates it into the discovery thread, so discovery reads the
- SELECTED profile's ``mcp_servers``, not the launch profile's (#67605).
-
- Delegating to the shared owner (instead of a hand-rolled thread) keeps
- the process-wide start lock, the retry-after-zero-connected allowance,
- and interactive-OAuth suppression.
-
- Known limitation: MCP tool registration is process-global, so in a
- multi-profile process the FIRST profile that builds an agent wins the
- discovery slot. Full per-profile MCP registries are tracked in #67605.
+ ``main()`` calls this for the stdio path. WebSocket/Desktop entrypoints skip
+ ``main()``, so ``server._start_agent_build`` also calls it AFTER binding the
+ session profile's HERMES_HOME — the shared owner captures the caller's
+ context-local override into the discovery thread, so discovery reads the
+ SELECTED profile's ``mcp_servers``. Delegating keeps the process-wide start
+ lock, retry-after-zero-connected allowance, and interactive-OAuth
+ suppression. Limitation: MCP registration is process-global, so the FIRST
+ profile to build an agent wins the discovery slot.
"""
global _mcp_discovery_enabled
@@ -410,45 +297,32 @@ def ensure_mcp_discovery_started() -> None:
try:
from hermes_cli.mcp_startup import start_background_mcp_discovery
- start_background_mcp_discovery(
- logger=logger, thread_name="tui-mcp-discovery"
- )
+ start_background_mcp_discovery(logger=logger, thread_name="tui-mcp-discovery")
except Exception:
- logger.warning(
- "Background MCP tool discovery failed to start", exc_info=True
- )
+ logger.warning("Background MCP tool discovery failed to start", exc_info=True)
def main():
_install_sidecar_publisher()
- # Cross-backend liveness (#94895): register a heartbeat row so the
- # startup orphan sweep can distinguish "row owned by a live but idle
- # backend" from "row truly orphaned". Must run BEFORE the sweep so
- # the sweep sees our row in the same transaction.
+ # Heartbeat row lets the orphan sweep tell "live but idle backend" from
+ # "truly orphaned"; must run BEFORE the sweep so it sees our row.
try:
server._start_backend_heartbeat_refresher()
except Exception:
logger.warning("backend heartbeat refresher start failed", exc_info=True)
- # One-time sweep of session rows orphaned by a previous gateway process
- # (#65194) — the in-process WS-orphan reap timer dies with the process.
- # Desktop/dashboard reach the agent through handle_ws instead; the
- # scheduler is once-per-process + config-gated so the second site is a
- # no-op when this already ran.
+ # One-time sweep of rows orphaned by a previous gateway process (the
+ # in-process reap timer dies with the process). Once-per-process and
+ # config-gated, so the handle_ws call site is a no-op when this ran.
try:
server._schedule_startup_orphan_sweep()
except Exception:
logger.warning("startup orphan sweep scheduling failed", exc_info=True)
- # MCP tool discovery — backgrounded so a slow or unreachable MCP server
- # can't freeze TUI startup (a dead stdio/http server burns 1+2+4s of
- # connect retries → ~7s of dead air before the composer appears). The
- # agent isn't built until the first prompt, at which point _make_agent
- # briefly joins the discovery thread (wait_for_mcp_discovery, bounded) so
- # already-spawning fast servers land in the tool snapshot. The config
- # gate inside ensure_mcp_discovery_started keeps the ~200ms MCP SDK
- # import cost entirely off the path for users with no mcp_servers.
+ # Backgrounded so a dead MCP server (~7s of connect retries) can't freeze
+ # startup; _make_agent briefly joins it (wait_for_mcp_discovery). The config
+ # gate inside keeps the ~200ms MCP SDK import off the no-mcp_servers path.
ensure_mcp_discovery_started()
if not write_json({
@@ -456,9 +330,8 @@ def main():
"method": "event",
"params": {
"type": "gateway.ready",
- # change_events: see tui_gateway/ws.py — clients demote legacy polls.
- # replay_epoch: restart detection for the WS replay contract (the
- # stdio TUI ignores it).
+ # change_events: clients demote legacy polls (see tui_gateway/ws.py).
+ # replay_epoch: WS restart detection; the stdio TUI ignores it.
"payload": {
"skin": resolve_skin(),
"change_events": True,
@@ -472,11 +345,9 @@ def main():
# Live-apply skins Hermes activates mid-conversation.
server._ensure_skin_watcher()
- # Warm the /model picker's provider-models cache off-thread during this
- # idle window (gateway.ready sent, user about to type). Mirrors the classic
- # CLI run() loop — the stdio TUI otherwise never prewarms, so the first
- # /model open blocks on serial /v1/models fetches. Fire-and-forget,
- # guarded once-per-process, fully exception-isolated.
+ # Warm the /model picker's provider-models cache during this idle window
+ # (mirrors the classic CLI loop); otherwise the first /model open blocks on
+ # serial /v1/models fetches. Fire-and-forget, once-per-process.
try:
from hermes_cli.model_switch import prewarm_picker_cache_async
prewarm_picker_cache_async()
@@ -486,8 +357,7 @@ def main():
while True:
raw = sys.stdin.readline()
if not raw:
- # Stdin fell through — check if spurious (O_NONBLOCK flip by a
- # child on the shared open file description) or genuine EOF.
+ # Spurious (child flipped O_NONBLOCK on the shared description) or genuine EOF?
if not handle_spurious_eof(_recovery_times, _log_exit):
break
continue
@@ -506,10 +376,9 @@ def main():
method = req.get("method") if isinstance(req, dict) else None
resp = dispatch(req)
- if resp is not None:
- if not write_json(resp):
- _log_exit(f"response write failed for method={method!r} (broken stdout pipe)")
- sys.exit(0)
+ if resp is not None and not write_json(resp):
+ _log_exit(f"response write failed for method={method!r} (broken stdout pipe)")
+ sys.exit(0)
if __name__ == "__main__":
diff --git a/tui_gateway/git_probe.py b/tui_gateway/git_probe.py
index a0b5d135306..754a3bbd5d0 100644
--- a/tui_gateway/git_probe.py
+++ b/tui_gateway/git_probe.py
@@ -1,24 +1,18 @@
"""Git working-tree probing for the gateway: run git, resolve repo roots, fold
linked worktrees under their common root.
-Probing runs where the gateway runs, so it resolves repos for both local and
-remote backends (unlike the desktop's electron probe, which only sees the local
-fs). Resolved roots are cached with a thread-safe, single-flight cache: the
-gateway's long handlers run on worker threads, so concurrent identical probes
-(e.g. two overlapping project-tree builds) share one `git` invocation instead of
-racing an unguarded dict.
-
-Positive results are cached for the process lifetime; negative results (a cwd
-that isn't a git repo, or a deleted/nonexistent dir) are cached only for a short
-TTL (`_NEG_TTL`). Caching negatives matters a lot for the desktop Projects tree:
-``project_tree.build_tree`` resolves a cwd once *per session* (not per distinct
-cwd), so a power user with hundreds of sessions in non-git/deleted dirs would
-otherwise re-spawn ``git`` hundreds of times on *every* sidebar open — the cause
-of the multi-second "Projects" load. The TTL keeps a not-yet-repo cwd
-re-probable (we `git init` a new project's folder on its first worktree, and a
-frozen "" would mislabel its main lane by the dir basename) — it just stops the
-same "not a repo" answer from being re-derived dozens of times within one build
-and across rapid re-opens. `invalidate()` drops everything after a known
+Probing runs where the gateway runs, so it covers local and remote backends
+(the desktop's electron probe only sees the local fs). Roots go through a
+thread-safe single-flight cache: gateway handlers run on worker threads, so
+concurrent identical probes share one ``git`` spawn instead of racing a dict.
+
+Positive results are cached for the process lifetime; negatives (not a repo, or
+a deleted dir) only for ``_NEG_TTL``. Caching negatives matters: ``build_tree``
+resolves a cwd once *per session*, so hundreds of sessions in non-git/deleted
+dirs would otherwise re-spawn ``git`` on every sidebar open (multi-second
+"Projects" load). The TTL keeps a not-yet-repo cwd re-probable — we ``git init``
+a new project's folder on its first worktree, and a frozen "" would mislabel its
+main lane by dir basename. ``invalidate()`` drops everything after a known
mutation.
"""
@@ -35,26 +29,22 @@ from hermes_cli._subprocess_compat import bounded_git_probe
_GIT_TIMEOUT = 1.5
_WARM_WORKERS = 8
-# How long a "not a git repo" answer stays cached before it's re-probed. Short
-# enough that a freshly `git init`-ed / newly-created folder shows correctly
-# within a few seconds; long enough to collapse the hundreds of redundant probes
-# a single project-tree build (and rapid re-opens) would otherwise fire.
+# "Not a git repo" cache TTL: short enough that a freshly `git init`-ed folder
+# shows correctly within seconds, long enough to collapse a tree build's
+# hundreds of redundant probes.
_NEG_TTL = 30.0
def run_git(cwd: str, *args: str) -> str:
"""``git -C <cwd> <args>`` → stripped stdout, or ``""`` on any failure.
- Uses the shared :func:`bounded_git_probe` so the post-kill cleanup is bounded
- on Windows — a plain ``subprocess.run(timeout=...)`` here deadlocked Desktop
- session readiness when a killed git left a suspended descendant holding the
- pipe handles (issue #68609).
+ Uses :func:`bounded_git_probe` so post-kill cleanup is bounded on Windows —
+ a plain ``subprocess.run(timeout=...)`` deadlocked Desktop session readiness
+ when a killed git left a suspended descendant holding the pipe handles.
"""
if not cwd or not os.path.isdir(cwd):
- # `git -C` on a directory that no longer exists can only fail, and it
- # fails at the price of a fork. Deleted worktrees dominate the cwds a
- # long-lived session history hands us, so the stat pays for itself many
- # times over on every project-tree build.
+ # `git -C` on a missing dir can only fail, at the price of a fork; deleted
+ # worktrees dominate a long session history's cwds, so the stat pays off.
return ""
return bounded_git_probe(["git", "-C", cwd, *args], timeout=_GIT_TIMEOUT)
@@ -64,10 +54,8 @@ def branch(cwd: str) -> str:
class _RootCache:
- """Thread-safe, single-flight cache of git-root probes. Positive results are
- cached for the process lifetime; negative ("not a repo") results are cached
- only for ``_NEG_TTL`` seconds so a not-yet-repo cwd stays re-probable.
- Followers wait on the leader's probe instead of duplicating it."""
+ """Thread-safe, single-flight cache of git-root probes: positives live for
+ the process, negatives for ``_NEG_TTL``; followers wait on the leader."""
def __init__(self) -> None:
self._lock = threading.Lock()
@@ -90,19 +78,12 @@ class _RootCache:
expiry = self._neg.get(key)
if expiry is not None:
if expiry > time.monotonic():
- # Recently probed as "not a repo" — trust it briefly
- # instead of re-spawning git for the same dead/non-repo
- # cwd on every session in the tree build.
- return ""
- # TTL elapsed: drop it and re-probe (it may be a repo now).
- del self._neg[key]
+ return "" # recent "not a repo": trust it briefly
+ del self._neg[key] # TTL elapsed: re-probe (may be a repo now)
gate = self._inflight.get(key)
- if gate is None:
- gate = threading.Event()
- self._inflight[key] = gate
- leader = True
- else:
- leader = False
+ leader = gate is None
+ if leader:
+ gate = self._inflight[key] = threading.Event()
if not leader:
# Another thread is probing this key — wait, then re-read.
@@ -141,27 +122,20 @@ def repo_root(cwd: str) -> str:
def common_repo_root(cwd: str) -> str:
"""The MAIN (common) repo root for ``cwd``, folding linked worktrees.
- ``--show-toplevel`` returns a linked worktree's OWN root, so grouping by it
- splits every worktree into a separate "repo". The common ``.git`` dir
- (``--git-common-dir``) is shared by a repo and all its worktrees, so its
- parent is the one true repo root; fall back to the toplevel root otherwise.
-
- The returned path is normalized to git's forward-slash spelling so it can be
- compared against :func:`repo_root` (which returns raw ``--show-toplevel``
- output). ``os.path.realpath`` rewrites separators to the platform's native
- ``\\`` on Windows, so without this the SAME directory came back spelled two
- ways and the repo's own checkout compared unequal to its common root — the
- main checkout was then misread as a linked worktree and the desktop sidebar
- rendered it twice (a dir-labeled lane plus a branch-labeled ``main`` lane).
- """
- if not cwd:
- return ""
+ ``--show-toplevel`` returns a linked worktree's OWN root, splitting every
+ worktree into its own "repo"; the parent of the shared ``--git-common-dir``
+ is the one true root (fallback: the toplevel root).
- # No work tree, nothing to fold. Reading the (warmed, negative-cached)
- # toplevel first spares every non-repo cwd a second `git` spawn — one the
- # parallel warm can never absorb, since `resolve()` only reaches here for
- # cwds that ARE repos.
- if not repo_root(cwd):
+ The result is normalized to git's forward-slash spelling so it compares
+ equal to :func:`repo_root` (raw ``--show-toplevel``). ``os.path.realpath``
+ uses native ``\\`` on Windows, so without this the main checkout compared
+ unequal to its own common root, was misread as a linked worktree, and the
+ desktop sidebar rendered it twice.
+ """
+ # Not a repo: nothing to fold. Checking the (warmed, negative-cached)
+ # toplevel first spares every non-repo cwd a second `git` spawn that the
+ # parallel warm can't absorb (`resolve()` only reaches here for repos).
+ if not cwd or not repo_root(cwd):
return ""
def _probe() -> str:
@@ -190,8 +164,7 @@ def resolve(cwd: str) -> dict | None:
def warm_roots(cwds: Iterable[str], max_workers: int = _WARM_WORKERS) -> None:
"""Pre-resolve many cwds' roots in parallel (bounded) so a cold first paint
- doesn't serialize one git subprocess per session cwd. Single-flight dedupes
- overlap; results land in the shared cache for the sequential consumers."""
+ doesn't serialize one git spawn per session cwd; results land in the cache."""
pending = sorted({(cwd or "").strip() for cwd in cwds} - {""})
if not pending:
return
diff --git a/tui_gateway/host_supervisor.py b/tui_gateway/host_supervisor.py
index 9f8a7bd4a6d..25b9f084b97 100644
--- a/tui_gateway/host_supervisor.py
+++ b/tui_gateway/host_supervisor.py
@@ -8,6 +8,7 @@ not contend with the serving process' event loop for the same GIL.
from __future__ import annotations
+import contextlib
import json
import logging
import os
@@ -47,11 +48,15 @@ MUTATOR_ROUTE_TABLE: dict[str, str] = {
_REGISTRY_NAME = "dashboard-compute-host.json"
_RESPAWN_WINDOW_SECS = 300.0
_SHUTDOWN_TIMEOUT_SECS = 10.0
-# Late control-ack handlers (#97948): a compress that outlives its RPC waiter
-# can legitimately run for the full compression ceiling plus a stall-fallback
-# retry, so keep registrations around well past that — but bounded.
+# Late control-ack handlers: a compress that outlives its RPC waiter can run for
+# the full compression ceiling plus a stall-fallback retry, so keep
+# registrations well past that — but bounded.
_LATE_CONTROL_TTL_SECS = 1800.0
_LATE_CONTROL_MAX = 64
+# Host frames whose ``request_id`` resolves a pending/late control waiter.
+_CONTROL_REPLY_TYPES = frozenset(
+ {"control.ack", "control.error", "respond.ack", "respond.error", "interrupt.ack", "reload_mcp.ack", "shutdown.ack"}
+)
def append_log_record(path: str | Path, record: str) -> None:
@@ -72,6 +77,8 @@ def _repo_root() -> Path:
def _build_sha() -> str:
+ """Current checkout's HEAD sha, or ``"unknown"``. Shared with ``compute_host``
+ so the hello handshake and the supervisor's expectation agree byte-for-byte."""
try:
return subprocess.check_output(
["git", "rev-parse", "HEAD"],
@@ -107,14 +114,10 @@ def _pid_alive(pid: int) -> bool:
def _pid_command(pid: int) -> str:
if pid <= 0:
return ""
- # Linux fast path.
- proc_cmdline = Path("/proc") / str(pid) / "cmdline"
- try:
- data = proc_cmdline.read_bytes()
+ with contextlib.suppress(Exception): # Linux fast path
+ data = (Path("/proc") / str(pid) / "cmdline").read_bytes()
if data:
return data.replace(b"\x00", b" ").decode("utf-8", errors="replace")
- except Exception:
- pass
try:
return subprocess.check_output(
["ps", "-p", str(pid), "-o", "command="],
@@ -129,8 +132,7 @@ def _pid_command(pid: int) -> str:
def is_compute_host_identity(pid: int) -> bool:
- cmd = _pid_command(pid)
- return "tui_gateway.compute_host" in cmd
+ return "tui_gateway.compute_host" in _pid_command(pid)
class HostSupervisor:
@@ -173,9 +175,8 @@ class HostSupervisor:
self._pending_turns: dict[str, tuple[str, Callable[[dict], None] | None]] = {}
self._pending_controls: dict[str, queue.Queue[dict]] = {}
# request_id -> (registered_at, handler) for control waiters that timed
- # out but whose host work is still running (#97948). The host emits
- # its control.ack whenever it finishes; without this the ack matched
- # no queue and was silently dropped.
+ # out while their host work still runs; without it the eventual
+ # control.ack matched no queue and was silently dropped.
self._late_control_handlers: dict[str, tuple[float, Callable[[dict], None]]] = {}
self._stderr_tail: list[str] = []
self._last_progress_counter = 0
@@ -254,9 +255,7 @@ class HostSupervisor:
self.start()
request_id = str(frame.get("request_id") or uuid.uuid4().hex)
sid = str(frame.get("sid") or "")
- payload = dict(frame)
- payload["type"] = "turn.start"
- payload["request_id"] = request_id
+ payload = {**frame, "type": "turn.start", "request_id": request_id}
with self._lock:
self._pending_turns[request_id] = (sid, on_complete)
try:
@@ -264,15 +263,8 @@ class HostSupervisor:
except Exception as exc:
with self._lock:
self._pending_turns.pop(request_id, None)
- err = {
- "type": "turn.error",
- "sid": sid,
- "request_id": request_id,
- "reason": "send_failed",
- "message": str(exc),
- }
if on_complete is not None:
- on_complete(err)
+ on_complete({"type": "turn.error", "sid": sid, "request_id": request_id, "reason": "send_failed", "message": str(exc)})
raise
return request_id
@@ -288,14 +280,7 @@ class HostSupervisor:
with self._lock:
self._pending_controls[request_id] = q
try:
- self._send_frame(
- {
- "type": "respond",
- "sid": sid,
- "request_id": request_id,
- "params": dict(params),
- }
- )
+ self._send_frame({"type": "respond", "sid": sid, "request_id": request_id, "params": dict(params)})
return q.get(timeout=timeout)
finally:
with self._lock:
@@ -321,22 +306,16 @@ class HostSupervisor:
) -> dict:
"""Send a control frame; with ``wait`` block up to ``timeout`` for its ack.
- ``on_late_ack`` (only meaningful with ``wait``) keeps the request
- adoptable after the waiter gives up: when the host's ``control.ack`` /
- ``control.error`` / ``error`` for this ``request_id`` eventually
- arrives, the handler fires once instead of the frame being dropped.
- Registrations are bounded by ``_LATE_CONTROL_TTL_SECS`` /
- ``_LATE_CONTROL_MAX``.
+ ``on_late_ack`` (only with ``wait``) keeps the request adoptable after the
+ waiter gives up: the host's eventual ``control.ack``/``control.error``/
+ ``error`` for this ``request_id`` fires the handler once instead of being
+ dropped. Bounded by ``_LATE_CONTROL_TTL_SECS`` / ``_LATE_CONTROL_MAX``.
"""
if route_name not in MUTATOR_ROUTE_TABLE:
raise ValueError(f"unclassified host mutator route: {route_name}")
self.start()
request_id = str((payload or {}).get("request_id") or uuid.uuid4().hex)
- frame = dict(payload or {})
- frame.setdefault("type", "control")
- frame["sid"] = sid
- frame["route_name"] = route_name
- frame["request_id"] = request_id
+ frame = {"type": "control", **(payload or {}), "sid": sid, "route_name": route_name, "request_id": request_id}
q: queue.Queue[dict] | None = None
if wait:
q = queue.Queue(maxsize=1)
@@ -358,12 +337,7 @@ class HostSupervisor:
def _register_late_control_handler(self, request_id: str, handler: Callable[[dict], None]) -> None:
now = time.monotonic()
with self._lock:
- expired = [
- rid
- for rid, (registered_at, _cb) in self._late_control_handlers.items()
- if now - registered_at > _LATE_CONTROL_TTL_SECS
- ]
- for rid in expired:
+ for rid in [r for r, (at, _cb) in self._late_control_handlers.items() if now - at > _LATE_CONTROL_TTL_SECS]:
self._late_control_handlers.pop(rid, None)
while len(self._late_control_handlers) >= _LATE_CONTROL_MAX:
oldest = min(self._late_control_handlers, key=lambda rid: self._late_control_handlers[rid][0])
@@ -375,16 +349,13 @@ class HostSupervisor:
q = self._pending_controls.get(request_id)
late = None if q is not None else self._late_control_handlers.pop(request_id, None)
if q is not None:
- try:
+ with contextlib.suppress(queue.Full):
q.put_nowait(frame)
- except queue.Full:
- pass
return
if late is None:
return
- _registered_at, handler = late
try:
- handler(frame)
+ late[1](frame)
except Exception:
logger.exception("compute host late control ack handler failed (request_id=%s)", request_id)
@@ -398,9 +369,10 @@ class HostSupervisor:
if self.env:
env.update(self.env)
env["HERMES_COMPUTE_HOST_HEARTBEAT_SECS"] = str(self.heartbeat_secs)
- env.setdefault("PYTHONPATH", str(_repo_root()))
- if str(_repo_root()) not in env["PYTHONPATH"].split(os.pathsep):
- env["PYTHONPATH"] = str(_repo_root()) + os.pathsep + env["PYTHONPATH"]
+ root = str(_repo_root())
+ env.setdefault("PYTHONPATH", root)
+ if root not in env["PYTHONPATH"].split(os.pathsep):
+ env["PYTHONPATH"] = root + os.pathsep + env["PYTHONPATH"]
proc = subprocess.Popen(
self.argv,
cwd=str(self.cwd),
@@ -409,9 +381,8 @@ class HostSupervisor:
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
- # Lossy UTF-8 decode — the compute host emits UTF-8; a
- # locale-mismatched byte must not raise inside the drain
- # threads and kill the supervisor (#52649).
+ # Lossy UTF-8 decode: a locale-mismatched byte must not raise inside
+ # the drain threads and kill the supervisor.
encoding="utf-8",
errors="replace",
bufsize=1,
@@ -421,9 +392,8 @@ class HostSupervisor:
self._stdout_thread = _Thread(target=self._drain_stdout, args=(proc,), name="compute-host-stdout", daemon=True)
self._stderr_thread = _Thread(target=self._drain_stderr, args=(proc,), name="compute-host-stderr", daemon=True)
self._wait_thread = _Thread(target=self._wait_for_exit, args=(proc,), name="compute-host-wait", daemon=True)
- self._stdout_thread.start()
- self._stderr_thread.start()
- self._wait_thread.start()
+ for t in (self._stdout_thread, self._stderr_thread, self._wait_thread):
+ t.start()
if not self._hello_event.wait(timeout=10.0):
self._terminate_process(proc)
raise RuntimeError(f"compute host did not send hello; stderr={self._stderr_tail[-5:]}")
@@ -457,9 +427,7 @@ class HostSupervisor:
def _remove_registry(self) -> None:
try:
- self.registry_path.unlink()
- except FileNotFoundError:
- pass
+ self.registry_path.unlink(missing_ok=True)
except Exception:
logger.debug("failed to remove compute host registry", exc_info=True)
@@ -492,38 +460,42 @@ class HostSupervisor:
def _handle_host_frame(self, frame: dict[str, Any]) -> None:
ftype = str(frame.get("type") or "")
- if ftype == "hello":
- self._hello = dict(frame)
- self._hello_event.set()
- return
- if ftype == "hb":
- self._last_progress_counter = int(frame.get("progress_counter") or self._last_progress_counter)
- logger.debug("compute host heartbeat: %s", frame)
- return
- if ftype == "rpc":
- message = frame.get("message")
- if isinstance(message, dict):
- self.rpc_sink(message)
- return
- if ftype in {"turn.end", "turn.error"}:
- self._complete_turn(frame)
- return
- if ftype in {"control.ack", "control.error", "respond.ack", "respond.error", "interrupt.ack", "reload_mcp.ack", "shutdown.ack"}:
+ if ftype in _CONTROL_REPLY_TYPES or (ftype == "error" and frame.get("request_id")):
self._deliver_control_frame(str(frame.get("request_id") or ""), frame)
return
- if ftype == "error" and frame.get("request_id"):
- self._deliver_control_frame(str(frame.get("request_id") or ""), frame)
+ handler = self._HOST_FRAME_HANDLERS.get(ftype)
+ if handler is not None:
+ getattr(self, handler)(frame)
+
+ # host frame ``type`` -> handler method name (see also _CONTROL_REPLY_TYPES).
+ _HOST_FRAME_HANDLERS: dict[str, str] = {
+ "hello": "_on_hello",
+ "hb": "_on_heartbeat",
+ "rpc": "_on_rpc",
+ "turn.end": "_complete_turn",
+ "turn.error": "_complete_turn",
+ }
+
+ def _on_hello(self, frame: dict[str, Any]) -> None:
+ self._hello = dict(frame)
+ self._hello_event.set()
+
+ def _on_heartbeat(self, frame: dict[str, Any]) -> None:
+ self._last_progress_counter = int(frame.get("progress_counter") or self._last_progress_counter)
+ logger.debug("compute host heartbeat: %s", frame)
+
+ def _on_rpc(self, frame: dict[str, Any]) -> None:
+ message = frame.get("message")
+ if isinstance(message, dict):
+ self.rpc_sink(message)
def _complete_turn(self, frame: dict[str, Any]) -> None:
request_id = str(frame.get("request_id") or "")
with self._lock:
pending = self._pending_turns.pop(request_id, None)
- if pending is None:
- return
- _sid, cb = pending
- if cb is not None:
+ if pending is not None and pending[1] is not None:
try:
- cb(frame)
+ pending[1](frame)
except Exception:
logger.exception("compute host turn completion callback failed")
@@ -544,32 +516,20 @@ class HostSupervisor:
pending = self._pending_turns
self._pending_turns = {}
for request_id, (sid, cb) in pending.items():
- frame = {
- "type": "turn.error",
- "sid": sid,
- "request_id": request_id,
- "reason": reason,
- "message": message,
- }
self.rpc_sink(
{
"jsonrpc": "2.0",
"method": "event",
- "params": {
- "type": "error",
- "session_id": sid,
- "payload": {"message": message, "reason": reason},
- },
+ "params": {"type": "error", "session_id": sid, "payload": {"message": message, "reason": reason}},
}
)
if cb is not None:
try:
- cb(frame)
+ cb({"type": "turn.error", "sid": sid, "request_id": request_id, "reason": reason, "message": message})
except Exception:
logger.exception("compute host error callback failed")
- # A crashed host will never emit the late acks the timed-out control
- # waiters are still expecting; fail them the same way so the client's
- # "still running in the background" notice does not hang forever.
+ # A crashed host never emits the late acks timed-out control waiters still
+ # expect; fail them too so the client's "still running" notice can't hang.
with self._lock:
late = self._late_control_handlers
self._late_control_handlers = {}
@@ -602,8 +562,7 @@ class HostSupervisor:
_Thread(target=_respawn, name="compute-host-respawn", daemon=True).start()
- def _pid_matches_compute_host(self, pid: int) -> bool:
- return is_compute_host_identity(pid)
+ _pid_matches_compute_host = staticmethod(is_compute_host_identity)
def _terminate_pid(self, pid: int, *, timeout: float = _SHUTDOWN_TIMEOUT_SECS) -> None:
try:
@@ -634,14 +593,10 @@ class HostSupervisor:
return
except Exception:
pass
- try:
+ with contextlib.suppress(Exception):
proc.kill()
- except Exception:
- pass
- try:
+ with contextlib.suppress(Exception):
proc.wait(timeout=2)
- except Exception:
- pass
__all__ = [
diff --git a/tui_gateway/hosted_room_driver.py b/tui_gateway/hosted_room_driver.py
index 3223df4d22f..94e4b8296fc 100644
--- a/tui_gateway/hosted_room_driver.py
+++ b/tui_gateway/hosted_room_driver.py
@@ -2,12 +2,8 @@
The durable state machine lives in :mod:`gateway.hosted_room_driver`. This
module owns the process-local worker and a deliberately small, injected session
-adapter. It does not import the gateway server, construct agents, or depend on
-any client transport.
-
-The adapter normalizes existing internal session RPCs into seven methods. A
-future server integration can implement those methods with the in-process
-handlers while tests use deterministic fakes and no models or network.
+adapter (seven methods). It does not import the gateway server, construct
+agents, or depend on any client transport; tests use deterministic fakes.
One bounded supervisor schedules independent room workers. Profile turn locks
still serialize Bots that share one profile, while a room waiting for approval
@@ -18,7 +14,6 @@ preserves the same canonical transcript instead of forking a second conversation
from __future__ import annotations
-import contextlib
import threading
import time
import uuid
@@ -30,7 +25,7 @@ from typing import Any, ContextManager, Protocol, cast
from gateway import hosted_room_driver as state
_CANCEL_ROUTE_RETRIES = 8
-
+_STOP_ACK_STATUSES = {"cancelled", "interrupted"}
ROOM_SESSION_SOURCE = "bot_room"
MAX_TERMINAL_TEXT_BYTES = 64 * 1024
@@ -42,17 +37,13 @@ _TERMINAL_TRUNCATION_NOTICE = (
class InternalSessionRPC(Protocol):
"""Normalized in-process session operations required by the room driver."""
- def resolve_exact(
- self, *, profile: str, title: str, source: str
- ) -> Mapping[str, Any] | None:
+ def resolve_exact(self, *, profile: str, title: str, source: str) -> Mapping[str, Any] | None:
"""Return the exact titled session under ``profile``, if it exists."""
def create(self, *, profile: str, title: str, source: str) -> Mapping[str, Any]:
"""Create a session without model or provider overrides."""
- def resume(
- self, *, profile: str, session_id: str, source: str
- ) -> Mapping[str, Any]:
+ def resume(self, *, profile: str, session_id: str, source: str) -> Mapping[str, Any]:
"""Resume the canonical room session."""
def submit(
@@ -68,21 +59,14 @@ class InternalSessionRPC(Protocol):
) -> Mapping[str, Any]:
"""Submit one fenced room turn and durably report its terminal result."""
- def history(
- self, *, profile: str, session_id: str, source: str
- ) -> Sequence[Mapping[str, Any]]:
+ def history(self, *, profile: str, session_id: str, source: str) -> Sequence[Mapping[str, Any]]:
"""Return normalized session messages in durable order."""
def info(self, *, profile: str, session_id: str, source: str) -> Mapping[str, Any]:
"""Return normalized live status for a session."""
def interrupt(
- self,
- *,
- profile: str,
- session_id: str,
- source: str,
- expected_task_id: str,
+ self, *, profile: str, session_id: str, source: str, expected_task_id: str
) -> Mapping[str, Any] | None:
"""Interrupt only when the current turn still matches the expected task."""
@@ -91,9 +75,7 @@ class MemberTransportResolver(Protocol):
"""Resolve the session transport for one durable room task."""
def __call__(
- self,
- binding: "HostedRoomBinding",
- task: Mapping[str, Any],
+ self, binding: "HostedRoomBinding", task: Mapping[str, Any]
) -> InternalSessionRPC:
"""Return a local or peer transport without changing task identity."""
@@ -121,6 +103,9 @@ class _RecoveryInspection:
status: str | None
+_NO_INSPECTION = _RecoveryInspection(terminal=None, active=False, status=None)
+
+
class HostedRoomRuntime:
"""Run queued hosted-room tasks independently of Desktop connections."""
@@ -148,16 +133,15 @@ class HostedRoomRuntime:
unavailable_retry_max_seconds: float = 30.0,
process_generation: str | None = None,
) -> None:
- if lease_ttl_seconds <= 0:
- raise ValueError("lease_ttl_seconds must be positive")
- if poll_interval_seconds <= 0:
- raise ValueError("poll_interval_seconds must be positive")
- if active_poll_interval_seconds <= 0:
- raise ValueError("active_poll_interval_seconds must be positive")
- if turn_timeout_seconds <= 0:
- raise ValueError("turn_timeout_seconds must be positive")
- if indeterminate_defer_seconds <= 0:
- raise ValueError("indeterminate_defer_seconds must be positive")
+ for name, value in (
+ ("lease_ttl_seconds", lease_ttl_seconds),
+ ("poll_interval_seconds", poll_interval_seconds),
+ ("active_poll_interval_seconds", active_poll_interval_seconds),
+ ("turn_timeout_seconds", turn_timeout_seconds),
+ ("indeterminate_defer_seconds", indeterminate_defer_seconds),
+ ):
+ if value <= 0:
+ raise ValueError(f"{name} must be positive")
if (
isinstance(max_concurrent_rooms, bool)
or not isinstance(max_concurrent_rooms, int)
@@ -210,13 +194,14 @@ class HostedRoomRuntime:
tuple[str, str], dict[str, float]
] = {}
self._blocked_rooms: set[str] = set()
- self._inspected_indeterminate_attempts: set[tuple[str, str, int]] = set()
self._status_lock = threading.Lock()
self._current_tasks: dict[str, state.TaskIdentity] = {}
self._room_schedule_cursor = 0
self._last_error: str | None = None
self._cycles = 0
+ # ------------------------------------------------------------------ lifecycle
+
def start(self) -> None:
"""Start the bounded room-worker supervisor idempotently."""
with self._status_lock:
@@ -252,10 +237,9 @@ class HostedRoomRuntime:
def wakeup(self) -> None:
"""Wake the worker after task admission or a room-state change."""
with self._status_lock:
- # If the supervisor observes this signal while a room still owns a
- # worker slot, remember to revisit it once that thread exits. This
- # closes the race between terminal publication/route repair and the
- # longer idle fallback without turning idle rooms into a busy loop.
+ # Rooms that still own a worker slot are revisited once that thread
+ # exits, closing the race between terminal publication/route repair
+ # and the longer idle fallback without busy-looping idle rooms.
self._rooms_needing_reschedule.update(self._room_threads)
self._wake.set()
@@ -276,6 +260,8 @@ class HostedRoomRuntime:
"cycles": self._cycles,
}
+ # ------------------------------------------------------------------ public ops
+
def cancel(
self,
identity: state.TaskIdentity,
@@ -284,11 +270,10 @@ class HostedRoomRuntime:
) -> dict[str, Any]:
"""Persist a stop intent, then commit cancellation after acknowledgement.
- The worker thread transitions tasks concurrently with cancellation
- (queued -> running -> terminal), so the status read below is only a
- routing hint. Every fast-path failure caused by a concurrent
- transition re-reads and re-routes instead of surfacing a transient
- `InvalidTaskTransitionError`/`StaleTaskError` to the caller.
+ The worker thread transitions tasks concurrently (queued -> running ->
+ terminal), so the status read is only a routing hint: every fast-path
+ failure caused by a concurrent transition re-reads and re-routes instead
+ of surfacing a transient `InvalidTaskTransitionError`/`StaleTaskError`.
"""
for _ in range(_CANCEL_ROUTE_RETRIES):
before = state.get_task(self.db_path, identity)
@@ -308,8 +293,7 @@ class HostedRoomRuntime:
clock=self.clock,
)
except (state.InvalidTaskTransitionError, state.StaleTaskError):
- # Lost the race with the worker; re-read and re-route.
- continue
+ continue # lost the race with the worker; re-route
self.wakeup()
return cancelled
try:
@@ -321,38 +305,21 @@ class HostedRoomRuntime:
clock=self.clock,
)
except (state.InvalidTaskTransitionError, state.StaleTaskError):
- # Task settled or re-queued mid-flight; re-read and re-route.
- continue
+ continue # settled or re-queued mid-flight; re-route
binding = self._binding_for_room(identity.room_id)
try:
if binding is not None:
lease = self._ensure_lease(binding)
if self._peer_stop_acknowledged(binding, stopping):
- stopping = state.complete_task_cancel(
- self.db_path,
- identity,
- cancel_id=cancel_id,
- expected_cancel_generation=stopping["cancel_generation"],
- clock=self.clock,
- )
+ self._complete_cancel(stopping, cancel_id=cancel_id)
elif not self._settle_stopping_completion(
binding, stopping, lease
- ):
- if self._interrupt_stopping_task(binding, stopping):
- stopping = state.complete_task_cancel(
- self.db_path,
- identity,
- cancel_id=cancel_id,
- expected_cancel_generation=stopping[
- "cancel_generation"
- ],
- clock=self.clock,
- )
+ ) and self._interrupt_stopping_task(binding, stopping):
+ self._complete_cancel(stopping, cancel_id=cancel_id)
except Exception as exc:
self._record_error(f"stop remains pending: {exc}")
- stopping = state.get_task(self.db_path, identity)
self.wakeup()
- return stopping
+ return state.get_task(self.db_path, identity)
# Exhausted routing retries under sustained contention: surface the
# live status honestly rather than a transient transition error.
final = state.get_task(self.db_path, identity)
@@ -363,50 +330,6 @@ class HostedRoomRuntime:
f"(last observed state '{final['status']}')"
)
- @staticmethod
- def _info_acknowledges_peer_cancel(
- info: Mapping[str, Any], task: Mapping[str, Any]
- ) -> bool:
- """Accept only one exact peer task attempt's terminal Stop receipt."""
-
- return (
- not bool(info.get("active", info.get("running", False)))
- and str(info.get("status") or "") in {"cancelled", "interrupted"}
- and str(info.get("task_id") or "") == task["identity"].task_id
- and int(info.get("execution_generation") or 0)
- == int(task["execution_generation"])
- )
-
- def _peer_stop_acknowledged(
- self,
- binding: HostedRoomBinding,
- task: Mapping[str, Any],
- ) -> bool:
- """Probe a peer's exact durable terminal status before reading history."""
-
- transport = self._transport_for(binding, task)
- if transport is None or transport is self.rpc:
- return False
- profile = task["payload"]["target_profile"]
- session = transport.resolve_exact(
- profile=profile,
- title=room_session_title(binding.room_id),
- source=ROOM_SESSION_SOURCE,
- )
- if session is None:
- return False
- resumed = transport.resume(
- profile=profile,
- session_id=_session_id(session),
- source=ROOM_SESSION_SOURCE,
- )
- info = transport.info(
- profile=profile,
- session_id=_session_id(resumed),
- source=ROOM_SESSION_SOURCE,
- )
- return self._info_acknowledges_peer_cancel(info, task)
-
def retry_indeterminate(self, identity: state.TaskIdentity) -> dict[str, Any]:
"""Explicitly retry one uncertain attempt under the current room lease."""
task = state.get_task(self.db_path, identity)
@@ -419,107 +342,211 @@ class HostedRoomRuntime:
raise state.RoomUnavailableError("hosted room is unavailable")
lease = self._ensure_lease(binding)
if task["status"] == "deferred":
- retried = state.requeue_deferred_task(
- self.db_path,
- identity,
- lease,
- expected_execution_generation=task["execution_generation"],
- expected_cancel_generation=task["cancel_generation"],
- clock=self.clock,
+ return self._requeue(
+ state.requeue_deferred_task, task, lease, identity.room_id
)
- with self._status_lock:
- self._blocked_rooms.discard(identity.room_id)
- self.wakeup()
- return retried
- # Explicit Retry may resume the exact stored session. Use the returned
- # runtime id for every subsequent history/info probe; an automatic
+ # Explicit Retry may resume the exact stored session; an automatic
# abandoned-attempt scan remains non-resuming for local sessions.
inspection = self._inspect_recovery_session(binding, task)
if inspection.terminal is not None:
- resolved = state.resolve_indeterminate_task(
- self.db_path,
- identity,
- lease,
- expected_execution_generation=task["execution_generation"],
- expected_cancel_generation=task["cancel_generation"],
- settlement_id=inspection.terminal.settlement_id,
- status=inspection.terminal.status,
- result=inspection.terminal.result,
- clock=self.clock,
- )
- if self.publish_terminal is not None:
- self.publish_terminal(binding, resolved)
- return resolved
+ return self._resolve_indeterminate(binding, task, lease, inspection.terminal)
if inspection.status == "cancelled":
- resolved = state.resolve_indeterminate_cancellation(
- self.db_path,
- identity,
- lease,
- expected_execution_generation=task["execution_generation"],
- expected_cancel_generation=task["cancel_generation"],
- cancel_id=f"remote-cancel:{task['execution_generation']}",
- clock=self.clock,
- )
- if self.publish_terminal is not None:
- self.publish_terminal(binding, resolved)
- return resolved
+ return self._resolve_remote_cancel(binding, task, lease)
if inspection.active:
- with self._status_lock:
- self._blocked_rooms.add(identity.room_id)
+ self._set_blocked(identity.room_id, True)
raise state.InvalidTaskTransitionError(
"cannot retry while the original task attempt is still active"
)
- retried = state.requeue_indeterminate_task(
+ return self._requeue(
+ state.requeue_indeterminate_task, task, lease, identity.room_id
+ )
+
+ # ------------------------------------------------------------------ durable-state helpers
+
+ def _publish(self, binding: HostedRoomBinding, task: dict[str, Any]) -> dict[str, Any]:
+ if self.publish_terminal is not None:
+ self.publish_terminal(binding, task)
+ return task
+
+ def _set_blocked(self, room_id: str, blocked: bool) -> None:
+ with self._status_lock:
+ if blocked:
+ self._blocked_rooms.add(room_id)
+ else:
+ self._blocked_rooms.discard(room_id)
+
+ def _requeue(
+ self,
+ requeue: Callable[..., dict[str, Any]],
+ task: Mapping[str, Any],
+ lease: state.DriverLease,
+ room_id: str,
+ ) -> dict[str, Any]:
+ retried = requeue(
self.db_path,
- identity,
+ task["identity"],
lease,
expected_execution_generation=task["execution_generation"],
expected_cancel_generation=task["cancel_generation"],
clock=self.clock,
)
- with self._status_lock:
- self._blocked_rooms.discard(identity.room_id)
+ self._set_blocked(room_id, False)
self.wakeup()
return retried
- def _interrupt_stopping_task(
+ def _complete_cancel(
+ self, task: Mapping[str, Any], *, cancel_id: str | None = None
+ ) -> dict[str, Any]:
+ return state.complete_task_cancel(
+ self.db_path,
+ task["identity"],
+ cancel_id=task["cancel_id"] if cancel_id is None else cancel_id,
+ expected_cancel_generation=task["cancel_generation"],
+ clock=self.clock,
+ )
+
+ def _resolve_indeterminate(
self,
binding: HostedRoomBinding,
task: Mapping[str, Any],
- ) -> bool:
- transport = self._transport_for(binding, task)
- if transport is None:
- return False
- profile = task["payload"]["target_profile"]
+ lease: state.DriverLease,
+ terminal: _TerminalReceipt,
+ *,
+ publish: bool = True,
+ ) -> dict[str, Any]:
+ resolved = state.resolve_indeterminate_task(
+ self.db_path,
+ task["identity"],
+ lease,
+ expected_execution_generation=int(task["execution_generation"]),
+ expected_cancel_generation=task["cancel_generation"],
+ settlement_id=terminal.settlement_id,
+ status=terminal.status,
+ result=terminal.result,
+ clock=self.clock,
+ )
+ return self._publish(binding, resolved) if publish else resolved
+
+ def _resolve_remote_cancel(
+ self,
+ binding: HostedRoomBinding,
+ task: Mapping[str, Any],
+ lease: state.DriverLease,
+ *,
+ publish: bool = True,
+ ) -> dict[str, Any]:
+ resolved = state.resolve_indeterminate_cancellation(
+ self.db_path,
+ task["identity"],
+ lease,
+ expected_execution_generation=task["execution_generation"],
+ expected_cancel_generation=task["cancel_generation"],
+ cancel_id=f"remote-cancel:{task['execution_generation']}",
+ clock=self.clock,
+ )
+ return self._publish(binding, resolved) if publish else resolved
+
+ def _settle_stopping(
+ self,
+ binding: HostedRoomBinding,
+ task: Mapping[str, Any],
+ lease: state.DriverLease,
+ *,
+ settlement_id: str,
+ status: state.TerminalStatus,
+ result: Mapping[str, Any],
+ expected_execution_generation: int | None = None,
+ ) -> dict[str, Any]:
+ settled = state.settle_stopping_task(
+ self.db_path,
+ task["identity"],
+ lease,
+ expected_execution_generation=(
+ int(task["execution_generation"])
+ if expected_execution_generation is None
+ else expected_execution_generation
+ ),
+ expected_cancel_generation=int(task["cancel_generation"]),
+ settlement_id=settlement_id,
+ status=status,
+ result=result,
+ clock=self.clock,
+ )
+ return self._publish(binding, settled)
+
+ # ------------------------------------------------------------------ session probes
+
+ def _resume_exact(
+ self, transport: InternalSessionRPC, room_id: str, profile: str
+ ) -> str | None:
+ """Resolve the canonical room session and return its resumed runtime id."""
session = transport.resolve_exact(
profile=profile,
- title=room_session_title(binding.room_id),
+ title=room_session_title(room_id),
source=ROOM_SESSION_SOURCE,
)
if session is None:
- # A local accepted turn cannot survive without its canonical
- # session. Resolution errors raise; an authoritative absence is a
- # safe Stop acknowledgement. A peer remains uncertain instead.
- return transport is self.rpc
+ return None
resumed = transport.resume(
profile=profile,
session_id=_session_id(session),
source=ROOM_SESSION_SOURCE,
)
- session_id = _session_id(resumed)
+ return _session_id(resumed)
+
+ @staticmethod
+ def _info_acknowledges_peer_cancel(
+ info: Mapping[str, Any], task: Mapping[str, Any]
+ ) -> bool:
+ """Accept only one exact peer task attempt's terminal Stop receipt."""
+ return (
+ not _info_active(info)
+ and str(info.get("status") or "") in _STOP_ACK_STATUSES
+ and str(info.get("task_id") or "") == task["identity"].task_id
+ and int(info.get("execution_generation") or 0)
+ == int(task["execution_generation"])
+ )
+
+ def _peer_stop_acknowledged(
+ self,
+ binding: HostedRoomBinding,
+ task: Mapping[str, Any],
+ ) -> bool:
+ """Probe a peer's exact durable terminal status before reading history."""
+ transport = self._transport_for(binding, task)
+ if transport is None or transport is self.rpc:
+ return False
+ profile = task["payload"]["target_profile"]
+ session_id = self._resume_exact(transport, binding.room_id, profile)
+ if session_id is None:
+ return False
+ info = transport.info(
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
+ )
+ return self._info_acknowledges_peer_cancel(info, task)
+
+ def _interrupt_stopping_task(
+ self,
+ binding: HostedRoomBinding,
+ task: Mapping[str, Any],
+ ) -> bool:
+ transport = self._transport_for(binding, task)
+ if transport is None:
+ return False
+ profile = task["payload"]["target_profile"]
+ session_id = self._resume_exact(transport, binding.room_id, profile)
+ if session_id is None:
+ # A local accepted turn cannot survive without its canonical
+ # session: an authoritative absence is a safe Stop acknowledgement
+ # (resolution errors raise). A peer remains uncertain instead.
+ return transport is self.rpc
info = transport.info(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
)
- active = bool(info.get("active", info.get("running", False)))
- if not active:
- if self._info_acknowledges_peer_cancel(info, task):
- return True
+ if not _info_active(info):
# History was checked immediately before this probe. An exact
- # local session that is no longer active cannot keep executing, and
- # after a restart its process-local task marker is expected to be
- # absent.
+ # session that is no longer active cannot keep executing, and after
+ # a restart its process-local task marker is expected to be absent.
return True
if not _info_is_active_for(info, task["identity"], require_exact=True):
return False
@@ -531,10 +558,10 @@ class HostedRoomRuntime:
)
if result is None:
return False
- return result.get("interrupted") is True or str(result.get("status") or "") in {
- "cancelled",
- "interrupted",
- }
+ return (
+ result.get("interrupted") is True
+ or str(result.get("status") or "") in _STOP_ACK_STATUSES
+ )
def _settle_stopping_completion(
self,
@@ -547,42 +574,26 @@ class HostedRoomRuntime:
if transport is None:
return False
profile = task["payload"]["target_profile"]
- session = transport.resolve_exact(
- profile=profile,
- title=room_session_title(binding.room_id),
- source=ROOM_SESSION_SOURCE,
- )
- if session is None:
+ session_id = self._resume_exact(transport, binding.room_id, profile)
+ if session_id is None:
return False
- resumed = transport.resume(
- profile=profile,
- session_id=_session_id(session),
- source=ROOM_SESSION_SOURCE,
- )
receipt = _find_terminal_receipt(
transport.history(
- profile=profile,
- session_id=_session_id(resumed),
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
),
task["identity"],
int(task["execution_generation"]),
)
if receipt is None:
return False
- settled = state.settle_stopping_task(
- self.db_path,
- task["identity"],
+ self._settle_stopping(
+ binding,
+ task,
lease,
- expected_execution_generation=int(task["execution_generation"]),
- expected_cancel_generation=int(task["cancel_generation"]),
settlement_id=receipt.settlement_id,
status=receipt.status,
result=receipt.result,
- clock=self.clock,
)
- if self.publish_terminal is not None:
- self.publish_terminal(binding, settled)
return True
def _report_pending_action(
@@ -594,10 +605,6 @@ class HostedRoomRuntime:
) -> None:
if self.pending_action is None:
return
- payload = task.get("payload") or {}
- member_id = str(
- payload.get("target_member_id") or payload.get("target_profile") or ""
- )
approval = info.get("pending_approval") or info.get("approval")
action = None
if isinstance(approval, Mapping):
@@ -617,27 +624,19 @@ class HostedRoomRuntime:
"request_id": safe_approval.get("request_id"),
"approval": safe_approval,
}
- self.pending_action(task["identity"].room_id, member_id, action)
+ self.pending_action(task["identity"].room_id, _member_id(task), action)
def _retry_stopping_tasks(
self, binding: HostedRoomBinding, lease: state.DriverLease
) -> bool:
pending = state.list_tasks(
- self.db_path,
- room_id=binding.room_id,
- status="stopping",
+ self.db_path, room_id=binding.room_id, status="stopping"
)
for task in pending:
try:
lease = self._renew_lease_if_needed(binding, lease)
if self._peer_stop_acknowledged(binding, task):
- state.complete_task_cancel(
- self.db_path,
- task["identity"],
- cancel_id=task["cancel_id"],
- expected_cancel_generation=task["cancel_generation"],
- clock=self.clock,
- )
+ self._complete_cancel(task)
continue
if self._settle_stopping_completion(binding, task, lease):
continue
@@ -649,6 +648,8 @@ class HostedRoomRuntime:
return True
return False
+ # ------------------------------------------------------------------ scheduling
+
def _worker_loop(self) -> None:
try:
while not self._stop.is_set():
@@ -728,8 +729,7 @@ class HostedRoomRuntime:
return
except (state.RoomUnavailableError, state.StaleLeaseError) as exc:
self._drop_lease(binding.room_id)
- with self._status_lock:
- self._blocked_rooms.discard(binding.room_id)
+ self._set_blocked(binding.room_id, False)
self._record_error(f"room {binding.room_id}: {exc}")
except Exception as exc:
self._record_error(f"room {binding.room_id}: {exc}")
@@ -750,37 +750,27 @@ class HostedRoomRuntime:
deferred_until = self._ambiguous_rooms.get(binding.room_id)
if deferred_until is not None:
running = state.list_tasks(
- self.db_path,
- room_id=binding.room_id,
- status="running",
+ self.db_path, room_id=binding.room_id, status="running"
)
- if not running:
- self._ambiguous_rooms.pop(binding.room_id, None)
- elif self.clock() < deferred_until:
+ if running and self.clock() < deferred_until:
return
- else:
- self._ambiguous_rooms.pop(binding.room_id, None)
+ self._ambiguous_rooms.pop(binding.room_id, None)
lease = self._ensure_lease(binding)
recovery_key = (lease.room_id, lease.lease_generation)
if recovery_key not in self._recovered_leases:
state.recover_room(self.db_path, lease, clock=self.clock)
self._recovered_leases.add(recovery_key)
if self._retry_stopping_tasks(binding, lease):
- with self._status_lock:
- self._blocked_rooms.add(binding.room_id)
+ self._set_blocked(binding.room_id, True)
return
if self._reconcile_indeterminate(binding, lease):
return
queued = state.list_tasks(
- self.db_path,
- room_id=binding.room_id,
- status="queued",
+ self.db_path, room_id=binding.room_id, status="queued"
)
for task in queued:
- if self._stop.is_set():
- return
- if self._route_retry_is_deferred(task):
+ if self._stop.is_set() or self._route_retry_is_deferred(task):
return
lease = self._renew_lease_if_needed(binding, lease)
attempt = state.start_task(
@@ -795,13 +785,11 @@ class HostedRoomRuntime:
if current["status"] not in state.TERMINAL_STATUSES:
return
+ # ------------------------------------------------------------------ route retry backoff
+
@staticmethod
def _route_retry_key(task: Mapping[str, Any]) -> tuple[str, str]:
- payload = task.get("payload") or {}
- member_id = str(
- payload.get("target_member_id") or payload.get("target_profile") or ""
- )
- return task["identity"].room_id, member_id
+ return task["identity"].room_id, _member_id(task)
def _route_retry_is_deferred(self, task: Mapping[str, Any]) -> bool:
retry = self._unavailable_route_retries.get(self._route_retry_key(task))
@@ -815,10 +803,7 @@ class HostedRoomRuntime:
if previous is None
else min(
self.unavailable_retry_max_seconds,
- max(
- self.unavailable_retry_min_seconds,
- previous["delay"] * 2,
- ),
+ max(self.unavailable_retry_min_seconds, previous["delay"] * 2),
)
)
self._unavailable_route_retries[key] = {
@@ -830,16 +815,16 @@ class HostedRoomRuntime:
def _clear_unavailable_route_retry(self, task: Mapping[str, Any]) -> None:
self._unavailable_route_retries.pop(self._route_retry_key(task), None)
+ # ------------------------------------------------------------------ leases
+
def _ensure_lease(self, binding: HostedRoomBinding) -> state.DriverLease:
with self._status_lock:
current = self._leases.get(binding.room_id)
if current is not None:
try:
- renewed = self._renew_lease_if_needed(binding, current)
+ return self._renew_lease_if_needed(binding, current)
except state.StaleLeaseError:
self._drop_lease(binding.room_id)
- else:
- return renewed
lease = state.acquire_lease(
self.db_path,
@@ -869,15 +854,26 @@ class HostedRoomRuntime:
if not force and self.clock() < renew_at:
return lease
renewed = state.renew_lease(
- self.db_path,
- lease,
- ttl_seconds=self.lease_ttl_seconds,
- clock=self.clock,
+ self.db_path, lease, ttl_seconds=self.lease_ttl_seconds, clock=self.clock
)
with self._status_lock:
self._leases[lease.room_id] = renewed
return renewed
+ def _drop_lease(self, room_id: str) -> None:
+ with self._status_lock:
+ self._leases.pop(room_id, None)
+
+ def _release_idle_leases(self) -> None:
+ for room_id, lease in tuple(self._leases.items()):
+ try:
+ state.release_lease(self.db_path, lease, clock=self.clock)
+ except state.DriverStateError:
+ continue
+ self._drop_lease(room_id)
+
+ # ------------------------------------------------------------------ attempt execution
+
def _execute_attempt(
self,
binding: HostedRoomBinding,
@@ -896,70 +892,6 @@ class HostedRoomRuntime:
# after it, but an unexpected exception at that boundary is
# still ambiguous. Never terminalize it as a proven failure.
submit_attempted = True
-
- def on_terminal(receipt: Mapping[str, Any]) -> None:
- status = receipt.get("status")
- if status == "cancelled":
- self.wakeup()
- return
- terminal_status: state.TerminalStatus = (
- "settled" if status == "settled" else "failed"
- )
- try:
- settled = state.settle_task(
- self.db_path,
- attempt,
- settlement_id=(
- receipt.get("settlement_id")
- or f"reply:{attempt.identity.task_id}:{attempt.execution_generation}"
- ),
- status=terminal_status,
- result=_bounded_terminal_result(receipt),
- clock=self.clock,
- )
- if self.publish_terminal is not None:
- self.publish_terminal(binding, settled)
- except state.StaleTaskError:
- try:
- current = state.get_task(self.db_path, attempt.identity)
- if current["status"] == "stopping":
- settled = state.settle_stopping_task(
- self.db_path,
- attempt.identity,
- attempt.lease,
- expected_execution_generation=attempt.execution_generation,
- expected_cancel_generation=int(
- current["cancel_generation"]
- ),
- settlement_id=(
- receipt.get("settlement_id")
- or f"reply:{attempt.identity.task_id}:{attempt.execution_generation}"
- ),
- status=terminal_status,
- result=_bounded_terminal_result(receipt),
- clock=self.clock,
- )
- if self.publish_terminal is not None:
- self.publish_terminal(binding, settled)
- except (state.StaleLeaseError, state.StaleTaskError):
- pass
- except state.StaleLeaseError:
- # Cancellation, disband, or authority transfer won the
- # durable race. The model result is intentionally
- # discarded; never turn a correct fence into a worker
- # thread exception.
- pass
- except state.DriverStateError as exc:
- # A malformed terminal receipt must not escape the
- # callback and hold the profile lock until the deadline.
- self._settle_failure_if_current(
- attempt,
- RuntimeError(
- f"terminal result could not be committed: {exc}"
- ),
- )
- self.wakeup()
-
deadline_monotonic = time.monotonic() + self.turn_timeout_seconds
transport.submit(
profile=profile,
@@ -968,12 +900,13 @@ class HostedRoomRuntime:
source=ROOM_SESSION_SOURCE,
task=attempt.identity,
execution_generation=attempt.execution_generation,
- on_terminal=on_terminal,
+ on_terminal=lambda receipt: self._on_terminal(
+ binding, attempt, receipt
+ ),
)
self._clear_unavailable_route_retry(task)
receipt = self._wait_for_terminal(
binding,
- task=task,
profile=profile,
session_id=_session_id(session),
attempt=attempt,
@@ -997,13 +930,10 @@ class HostedRoomRuntime:
if submit_attempted and bool(getattr(exc, "not_admitted", False)):
try:
state.requeue_not_admitted_task(
- self.db_path,
- attempt,
- clock=self.clock,
+ self.db_path, attempt, clock=self.clock
)
except (state.StaleLeaseError, state.StaleTaskError) as fence_exc:
- self._drop_lease(binding.room_id)
- self._ambiguous_rooms[binding.room_id] = attempt.lease.expires_at
+ self._mark_ambiguous(binding, attempt)
self._record_error(
f"task {attempt.identity.task_id} not-admitted proof lost "
f"its fence: {fence_exc}"
@@ -1015,8 +945,7 @@ class HostedRoomRuntime:
f"queued for retry in {delay:g}s"
)
elif submit_attempted:
- self._drop_lease(binding.room_id)
- self._ambiguous_rooms[binding.room_id] = attempt.lease.expires_at
+ self._mark_ambiguous(binding, attempt)
self._record_error(
f"task {attempt.identity.task_id} observation failed after submit: {exc}"
)
@@ -1031,11 +960,74 @@ class HostedRoomRuntime:
# thread leaves; idle room scans never set this marker.
self._rooms_needing_reschedule.add(binding.room_id)
+ def _mark_ambiguous(
+ self, binding: HostedRoomBinding, attempt: state.TaskAttempt
+ ) -> None:
+ self._drop_lease(binding.room_id)
+ self._ambiguous_rooms[binding.room_id] = attempt.lease.expires_at
+
+ def _on_terminal(
+ self,
+ binding: HostedRoomBinding,
+ attempt: state.TaskAttempt,
+ receipt: Mapping[str, Any],
+ ) -> None:
+ """Durably commit one in-process terminal receipt for ``attempt``."""
+ status = receipt.get("status")
+ if status == "cancelled":
+ self.wakeup()
+ return
+ terminal_status: state.TerminalStatus = (
+ "settled" if status == "settled" else "failed"
+ )
+ settlement_id = (
+ receipt.get("settlement_id")
+ or f"reply:{attempt.identity.task_id}:{attempt.execution_generation}"
+ )
+ result = _bounded_terminal_result(receipt)
+ try:
+ settled = state.settle_task(
+ self.db_path,
+ attempt,
+ settlement_id=settlement_id,
+ status=terminal_status,
+ result=result,
+ clock=self.clock,
+ )
+ self._publish(binding, settled)
+ except state.StaleTaskError:
+ try:
+ current = state.get_task(self.db_path, attempt.identity)
+ if current["status"] == "stopping":
+ self._settle_stopping(
+ binding,
+ current,
+ attempt.lease,
+ settlement_id=settlement_id,
+ status=terminal_status,
+ result=result,
+ expected_execution_generation=attempt.execution_generation,
+ )
+ except (state.StaleLeaseError, state.StaleTaskError):
+ pass
+ except state.StaleLeaseError:
+ # Cancellation, disband, or authority transfer won the durable
+ # race. The model result is intentionally discarded; never turn a
+ # correct fence into a worker thread exception.
+ pass
+ except state.DriverStateError as exc:
+ # A malformed terminal receipt must not escape the callback and
+ # hold the profile lock until the deadline.
+ self._settle_failure_if_current(
+ attempt,
+ RuntimeError(f"terminal result could not be committed: {exc}"),
+ )
+ self.wakeup()
+
def _wait_for_terminal(
self,
binding: HostedRoomBinding,
*,
- task: Mapping[str, Any],
profile: str,
session_id: str,
attempt: state.TaskAttempt,
@@ -1068,9 +1060,7 @@ class HostedRoomRuntime:
lease = self._renew_lease_if_needed(binding, lease)
receipt = _find_terminal_receipt(
transport.history(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
),
attempt.identity,
attempt.execution_generation,
@@ -1079,9 +1069,7 @@ class HostedRoomRuntime:
return receipt
info = transport.info(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
)
self._report_pending_action(task, session_id=session_id, info=info)
remaining = max(0.0, deadline_monotonic - time.monotonic())
@@ -1089,30 +1077,26 @@ class HostedRoomRuntime:
self._wake.clear()
return None
- @staticmethod
- def _deadline_cancel_id(task: Mapping[str, Any]) -> str:
- return f"deadline:{int(task['execution_generation'])}"
+ # ------------------------------------------------------------------ deadline stops
@staticmethod
def _is_deadline_stop(task: Mapping[str, Any]) -> bool:
return str(task.get("cancel_id") or "").startswith("deadline:")
- def _settle_deadline_failure(
+ def _complete_acknowledged_stop(
self,
binding: HostedRoomBinding,
task: Mapping[str, Any],
lease: state.DriverLease,
) -> dict[str, Any]:
- """Publish the explicit terminal outcome after exact Stop acknowledgement."""
-
- execution_generation = int(task["execution_generation"])
- settled = state.settle_stopping_task(
- self.db_path,
- task["identity"],
+ """Terminalize an acknowledged Stop: deadline stops publish an explicit failure."""
+ if not self._is_deadline_stop(task):
+ return self._complete_cancel(task)
+ return self._settle_stopping(
+ binding,
+ task,
lease,
- expected_execution_generation=execution_generation,
- expected_cancel_generation=int(task["cancel_generation"]),
- settlement_id=f"deadline:{execution_generation}",
+ settlement_id=f"deadline:{int(task['execution_generation'])}",
status="failed",
result={
"error": (
@@ -1122,26 +1106,6 @@ class HostedRoomRuntime:
"reason_code": "turn_deadline_exceeded",
"timeout_seconds": self.turn_timeout_seconds,
},
- clock=self.clock,
- )
- if self.publish_terminal is not None:
- self.publish_terminal(binding, settled)
- return settled
-
- def _complete_acknowledged_stop(
- self,
- binding: HostedRoomBinding,
- task: Mapping[str, Any],
- lease: state.DriverLease,
- ) -> dict[str, Any]:
- if self._is_deadline_stop(task):
- return self._settle_deadline_failure(binding, task, lease)
- return state.complete_task_cancel(
- self.db_path,
- task["identity"],
- cancel_id=task["cancel_id"],
- expected_cancel_generation=task["cancel_generation"],
- clock=self.clock,
)
def _expire_attempt_deadline(
@@ -1151,12 +1115,11 @@ class HostedRoomRuntime:
lease: state.DriverLease,
) -> None:
"""Fence, stop, and terminalize one exact attempt at its deadline."""
-
if task["status"] == "running":
task = state.begin_task_cancel(
self.db_path,
task["identity"],
- cancel_id=self._deadline_cancel_id(task),
+ cancel_id=f"deadline:{int(task['execution_generation'])}",
expected_cancel_generation=int(task["cancel_generation"]),
clock=self.clock,
)
@@ -1176,11 +1139,11 @@ class HostedRoomRuntime:
f"task {task['identity'].task_id} exceeded its deadline; stop remains pending"
)
+ # ------------------------------------------------------------------ recovery
+
def _inspect_abandoned_attempts(self, binding: HostedRoomBinding) -> None:
running = state.list_tasks(
- self.db_path,
- room_id=binding.room_id,
- status="running",
+ self.db_path, room_id=binding.room_id, status="running"
)
for task in running:
if task["run_process_generation"] == self.process_generation:
@@ -1198,6 +1161,21 @@ class HostedRoomRuntime:
# lease or submit a duplicate prompt.
raise state.LeaseHeldError("recovered session turn is still active")
+ def _inspection_from_info(
+ self,
+ task: Mapping[str, Any],
+ *,
+ session_id: str,
+ info: Mapping[str, Any],
+ terminal: _TerminalReceipt | None,
+ ) -> _RecoveryInspection:
+ self._report_pending_action(task, session_id=session_id, info=info)
+ return _RecoveryInspection(
+ terminal=terminal,
+ active=_info_is_active_for(info, task["identity"]),
+ status=str(info.get("status") or "") or None,
+ )
+
def _inspect_recovery_session(
self,
binding: HostedRoomBinding,
@@ -1206,38 +1184,23 @@ class HostedRoomRuntime:
profile = task["payload"]["target_profile"]
transport = self._transport_for(binding, task)
with self.turn_lock(profile):
- session = transport.resolve_exact(
- profile=profile,
- title=room_session_title(task["identity"].room_id),
- source=ROOM_SESSION_SOURCE,
- )
- if session is None:
- return _RecoveryInspection(terminal=None, active=False, status=None)
- resumed = transport.resume(
- profile=profile,
- session_id=_session_id(session),
- source=ROOM_SESSION_SOURCE,
+ session_id = self._resume_exact(
+ transport, task["identity"].room_id, profile
)
- session_id = _session_id(resumed)
+ if session_id is None:
+ return _NO_INSPECTION
receipt = _find_terminal_receipt(
transport.history(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
),
task["identity"],
task["execution_generation"],
)
info = transport.info(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
)
- self._report_pending_action(task, session_id=session_id, info=info)
- return _RecoveryInspection(
- terminal=receipt,
- active=_info_is_active_for(info, task["identity"]),
- status=str(info.get("status") or "") or None,
+ return self._inspection_from_info(
+ task, session_id=session_id, info=info, terminal=receipt
)
def _inspect_local_recovery_session(
@@ -1246,13 +1209,12 @@ class HostedRoomRuntime:
) -> _RecoveryInspection:
"""Check only live process state before explicit local recovery.
- A restart loses the in-process terminal callback identity. The ordinary
- session history is a display projection and cannot prove which durable
- task attempt authored a row, so never hydrate or infer completion from
- it. An inactive abandoned attempt remains indeterminate until the user
+ A restart loses the in-process terminal callback identity. Session
+ history is a display projection that cannot prove which durable task
+ attempt authored a row, so never hydrate or infer completion from it.
+ An inactive abandoned attempt remains indeterminate until the user
explicitly retries it under a new fenced generation.
"""
-
profile = task["payload"]["target_profile"]
with self.turn_lock(profile):
session = self.rpc.resolve_exact(
@@ -1261,18 +1223,13 @@ class HostedRoomRuntime:
source=ROOM_SESSION_SOURCE,
)
if session is None:
- return _RecoveryInspection(terminal=None, active=False, status=None)
+ return _NO_INSPECTION
session_id = _session_id(session)
info = self.rpc.info(
- profile=profile,
- session_id=session_id,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=session_id, source=ROOM_SESSION_SOURCE
)
- self._report_pending_action(task, session_id=session_id, info=info)
- return _RecoveryInspection(
- terminal=None,
- active=_info_is_active_for(info, task["identity"]),
- status=str(info.get("status") or "") or None,
+ return self._inspection_from_info(
+ task, session_id=session_id, info=info, terminal=None
)
def _reconcile_indeterminate(
@@ -1281,46 +1238,27 @@ class HostedRoomRuntime:
lease: state.DriverLease,
) -> bool:
unresolved = state.list_tasks(
- self.db_path,
- room_id=binding.room_id,
- status="indeterminate",
+ self.db_path, room_id=binding.room_id, status="indeterminate"
)
- with self._status_lock:
- if not unresolved:
- self._blocked_rooms.discard(binding.room_id)
- return False
+ if not unresolved:
+ self._set_blocked(binding.room_id, False)
+ return False
+ inspected = self._inspected_indeterminate_attempts
for task in unresolved:
generation = int(task["execution_generation"])
- attempt_key = (
- binding.room_id,
- task["identity"].task_id,
- generation,
- )
+ attempt_key = (binding.room_id, task["identity"].task_id, generation)
if (
self._transport_for(binding, task) is self.rpc
- and attempt_key not in self._inspected_indeterminate_attempts
+ and attempt_key not in inspected
):
inspection = self._inspect_local_recovery_session(task)
- self._inspected_indeterminate_attempts.add(attempt_key)
+ inspected.add(attempt_key)
if inspection.terminal is not None:
- resolved = state.resolve_indeterminate_task(
- self.db_path,
- task["identity"],
- lease,
- expected_execution_generation=generation,
- expected_cancel_generation=task["cancel_generation"],
- settlement_id=inspection.terminal.settlement_id,
- status=inspection.terminal.status,
- result=inspection.terminal.result,
- clock=self.clock,
- )
- self._inspected_indeterminate_attempts.discard(attempt_key)
- if self.publish_terminal is not None:
- self.publish_terminal(binding, resolved)
+ self._resolve_indeterminate(binding, task, lease, inspection.terminal)
+ inspected.discard(attempt_key)
continue
if inspection.active:
- with self._status_lock:
- self._blocked_rooms.add(binding.room_id)
+ self._set_blocked(binding.room_id, True)
return True
deferred_at = float(
task.get("indeterminate_at")
@@ -1329,12 +1267,8 @@ class HostedRoomRuntime:
or self.clock()
)
deadline = deferred_at + self.indeterminate_defer_seconds
- should_inspect = (
- attempt_key not in self._inspected_indeterminate_attempts
- or self.clock() >= deadline
- )
- inspection = _RecoveryInspection(terminal=None, active=False, status=None)
- if should_inspect:
+ inspection = _NO_INSPECTION
+ if attempt_key not in inspected or self.clock() >= deadline:
try:
if self._transport_for(binding, task) is not self.rpc:
inspection = self._inspect_recovery_session(binding, task)
@@ -1342,36 +1276,20 @@ class HostedRoomRuntime:
self._record_error(
f"task {task['identity'].task_id} recovery probe failed: {exc}"
)
- self._inspected_indeterminate_attempts.add(attempt_key)
+ inspected.add(attempt_key)
if inspection.status == "cancelled":
- state.resolve_indeterminate_cancellation(
- self.db_path,
- task["identity"],
- lease,
- expected_execution_generation=task["execution_generation"],
- expected_cancel_generation=task["cancel_generation"],
- cancel_id=f"remote-cancel:{task['execution_generation']}",
- clock=self.clock,
- )
- self._inspected_indeterminate_attempts.discard(attempt_key)
+ # Remote-probe resolutions are not republished here.
+ self._resolve_remote_cancel(binding, task, lease, publish=False)
+ inspected.discard(attempt_key)
continue
if inspection.terminal is not None:
- state.resolve_indeterminate_task(
- self.db_path,
- task["identity"],
- lease,
- expected_execution_generation=generation,
- expected_cancel_generation=task["cancel_generation"],
- settlement_id=inspection.terminal.settlement_id,
- status=inspection.terminal.status,
- result=inspection.terminal.result,
- clock=self.clock,
+ self._resolve_indeterminate(
+ binding, task, lease, inspection.terminal, publish=False
)
- self._inspected_indeterminate_attempts.discard(attempt_key)
+ inspected.discard(attempt_key)
continue
if self.clock() < deadline:
- with self._status_lock:
- self._blocked_rooms.add(binding.room_id)
+ self._set_blocked(binding.room_id, True)
return True
deferred = state.defer_indeterminate_task(
self.db_path,
@@ -1382,11 +1300,9 @@ class HostedRoomRuntime:
reason="member_unavailable",
clock=self.clock,
)
- self._inspected_indeterminate_attempts.discard(attempt_key)
- if self.publish_terminal is not None:
- self.publish_terminal(binding, deferred)
- with self._status_lock:
- self._blocked_rooms.discard(binding.room_id)
+ inspected.discard(attempt_key)
+ self._publish(binding, deferred)
+ self._set_blocked(binding.room_id, False)
return False
def _harvest_previous_attempt(
@@ -1395,17 +1311,16 @@ class HostedRoomRuntime:
task: Mapping[str, Any],
receipt: _TerminalReceipt,
) -> None:
- previous_lease = state.DriverLease(
- room_id=binding.room_id,
- gateway_id=task["run_gateway_id"],
- authority_epoch=binding.authority_epoch,
- process_generation=task["run_process_generation"],
- lease_generation=task["run_lease_generation"],
- expires_at=0.0,
- )
previous_attempt = state.TaskAttempt(
identity=task["identity"],
- lease=previous_lease,
+ lease=state.DriverLease(
+ room_id=binding.room_id,
+ gateway_id=task["run_gateway_id"],
+ authority_epoch=binding.authority_epoch,
+ process_generation=task["run_process_generation"],
+ lease_generation=task["run_lease_generation"],
+ expires_at=0.0,
+ ),
execution_generation=task["execution_generation"],
cancel_generation=task["cancel_generation"],
)
@@ -1419,20 +1334,16 @@ class HostedRoomRuntime:
clock=self.clock,
)
except (state.StaleLeaseError, state.StaleTaskError):
- # Once the previous proof has expired, the current state contract
- # deliberately offers no unsafe "trust this historical output"
- # escape hatch. The subsequent fenced recovery leaves it
- # indeterminate for explicit user action.
+ # Once the previous proof has expired there is deliberately no
+ # "trust this historical output" escape hatch; fenced recovery
+ # leaves the task indeterminate for explicit user action.
return
+ # ------------------------------------------------------------------ misc
+
def _binding_for_room(self, room_id: str) -> HostedRoomBinding | None:
return next(
- (
- binding
- for binding in self._rooms_provider()
- if binding.room_id == room_id
- ),
- None,
+ (b for b in self._rooms_provider() if b.room_id == room_id), None
)
def _transport_for(
@@ -1454,20 +1365,14 @@ class HostedRoomRuntime:
) -> Mapping[str, Any]:
title = room_session_title(room_id)
session = transport.resolve_exact(
- profile=profile,
- title=title,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, title=title, source=ROOM_SESSION_SOURCE
)
if session is None:
return transport.create(
- profile=profile,
- title=title,
- source=ROOM_SESSION_SOURCE,
+ profile=profile, title=title, source=ROOM_SESSION_SOURCE
)
return transport.resume(
- profile=profile,
- session_id=_session_id(session),
- source=ROOM_SESSION_SOURCE,
+ profile=profile, session_id=_session_id(session), source=ROOM_SESSION_SOURCE
)
def _settle_failure_if_current(
@@ -1490,24 +1395,17 @@ class HostedRoomRuntime:
with self._status_lock:
self._last_error = message
- def _drop_lease(self, room_id: str) -> None:
- with self._status_lock:
- self._leases.pop(room_id, None)
-
- def _release_idle_leases(self) -> None:
- for room_id, lease in tuple(self._leases.items()):
- try:
- state.release_lease(self.db_path, lease, clock=self.clock)
- except state.DriverStateError:
- continue
- self._drop_lease(room_id)
-
def room_session_title(room_id: str) -> str:
"""Return the canonical hidden session title for one hosted room."""
return f"Group: {room_id}"
+def _member_id(task: Mapping[str, Any]) -> str:
+ payload = task.get("payload") or {}
+ return str(payload.get("target_member_id") or payload.get("target_profile") or "")
+
+
def _session_id(session: Mapping[str, Any]) -> str:
value = session.get("session_id", session.get("id"))
if not isinstance(value, str) or not value:
@@ -1532,13 +1430,9 @@ def _truncate_utf8(value: Any, *, max_bytes: int) -> tuple[str, bool]:
def _bounded_terminal_result(receipt: Mapping[str, Any]) -> dict[str, Any]:
text, truncated = _truncate_utf8(
- receipt.get("text", ""),
- max_bytes=MAX_TERMINAL_TEXT_BYTES,
- )
- error, error_truncated = _truncate_utf8(
- receipt.get("error", ""),
- max_bytes=4096,
+ receipt.get("text", ""), max_bytes=MAX_TERMINAL_TEXT_BYTES
)
+ error, error_truncated = _truncate_utf8(receipt.get("error", ""), max_bytes=4096)
return {
"message_id": receipt.get("message_id"),
"text": text,
@@ -1553,47 +1447,40 @@ def _find_terminal_receipt(
execution_generation: int,
) -> _TerminalReceipt | None:
for message in reversed(history):
- if message.get("task_id") != identity.task_id:
- continue
- if message.get("execution_generation") != execution_generation:
- continue
- if message.get("role") != "assistant":
- continue
status = message.get("status")
- if status not in {"settled", "failed"}:
+ if (
+ message.get("task_id") != identity.task_id
+ or message.get("execution_generation") != execution_generation
+ or message.get("role") != "assistant"
+ or status not in {"settled", "failed"}
+ ):
continue
- terminal_status = cast(state.TerminalStatus, status)
receipt_id = message.get("message_id")
if not isinstance(receipt_id, str) or not receipt_id:
receipt_id = f"reply:{identity.task_id}:{execution_generation}"
return _TerminalReceipt(
- status=terminal_status,
+ status=cast(state.TerminalStatus, status),
settlement_id=receipt_id,
result=_bounded_terminal_result(
- {
- "message_id": receipt_id,
- "text": message.get("content", ""),
- }
+ {"message_id": receipt_id, "text": message.get("content", "")}
),
)
return None
+def _info_active(info: Mapping[str, Any]) -> bool:
+ return bool(info.get("active", info.get("running", False)))
+
+
def _info_is_active_for(
info: Mapping[str, Any],
identity: state.TaskIdentity,
*,
require_exact: bool = False,
) -> bool:
- if not bool(info.get("active", info.get("running", False))):
+ if not _info_active(info):
return False
active_task_id = info.get("task_id")
if require_exact:
return active_task_id == identity.task_id
return active_task_id in {None, identity.task_id}
-
-
-def null_turn_lock(_profile: str) -> Any:
- """Provide an explicit no-op lock for narrow embedding tests."""
- yield
diff --git a/tui_gateway/hosted_room_peer_http.py b/tui_gateway/hosted_room_peer_http.py
index 6c6c898d375..53a9f56c221 100644
--- a/tui_gateway/hosted_room_peer_http.py
+++ b/tui_gateway/hosted_room_peer_http.py
@@ -14,9 +14,10 @@ import urllib.parse
import urllib.request
from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
-from typing import Any
+from typing import Any, NoReturn
from gateway.hosted_room_peer import (
+ GatewayRoomCatalog,
HostedMemberDispatch,
validate_room_link_url,
)
@@ -27,13 +28,7 @@ logger = logging.getLogger(__name__)
_NOT_ADMITTED_ERRNOS = frozenset(
value
- for name in (
- "ECONNREFUSED",
- "ENETDOWN",
- "ENETUNREACH",
- "EHOSTDOWN",
- "EHOSTUNREACH",
- )
+ for name in ("ECONNREFUSED", "ENETDOWN", "ENETUNREACH", "EHOSTDOWN", "EHOSTUNREACH")
if (value := getattr(errno, name, None)) is not None
)
_ERROR_CODE_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
@@ -44,6 +39,42 @@ MAX_PEER_RESPONSE_BYTES = 16 * 1024 * 1024
MAX_PEER_ERROR_RESPONSE_BYTES = 16 * 1024
_PEER_RESPONSE_CHUNK_BYTES = 64 * 1024
+# Receipt fields that must match between a stored receipt and a dispatch.
+_RECEIPT_SCOPE_FIELDS = (
+ "room_id",
+ "home_install_id",
+ "authority_gateway_id",
+ "authority_epoch",
+ "member_id",
+ "target_install_id",
+ "target_profile",
+)
+_TERMINAL_RUN_STATES = frozenset({"completed", "failed", "interrupted", "cancelled"})
+_ACTIVE_RUN_STATES = frozenset({"queued", "running", "waiting_for_approval", "stopping"})
+_KNOWN_RUN_STATES = _TERMINAL_RUN_STATES | _ACTIVE_RUN_STATES
+# Older target gateways wrap these conditions inside the generic dispatch
+# error; normalize locally until their wire code becomes specific.
+_LEGACY_DISPATCH_MESSAGE_CODES = (
+ ("room grant", "invalid_room_grant"),
+ ("capability catalog changed", "room_capability_catalog_changed"),
+ ("execution policy changed", "room_execution_policy_changed"),
+)
+_REAUTHORIZATION_CODES = frozenset({
+ "invalid_room_grant",
+ "room_capability_catalog_changed",
+ "room_execution_policy_changed",
+ "room_reauthorization_required",
+})
+# (error_code, human message) for the two digest checks after a grant refresh.
+_EXECUTION_POLICY_CHANGED = (
+ "room_execution_policy_changed",
+ "peer room execution policy needs reauthorization",
+)
+_CAPABILITY_CHANGED = (
+ "room_capability_catalog_changed",
+ "peer room capabilities need reauthorization",
+)
+
class _PeerResponseTooLarge(ValueError):
"""A peer response exceeded its endpoint-specific byte budget."""
@@ -57,11 +88,8 @@ def _content_length(response: Any) -> int | None:
headers = getattr(response, "headers", None)
if headers is None or not hasattr(headers, "get"):
return None
- raw = headers.get("Content-Length")
- if raw is None:
- return None
try:
- value = int(raw)
+ value = int(headers.get("Content-Length"))
except (TypeError, ValueError):
return None
return value if value >= 0 else None
@@ -91,12 +119,7 @@ def _set_response_socket_timeout(response: Any, remaining: float) -> None:
frontier = next_frontier
-def _read_bounded_response(
- response: Any,
- *,
- max_bytes: int,
- deadline: float,
-) -> bytes:
+def _read_bounded_response(response: Any, *, max_bytes: int, deadline: float) -> bytes:
declared = _content_length(response)
if declared is not None and declared > max_bytes:
raise _PeerResponseTooLarge
@@ -111,9 +134,7 @@ def _read_bounded_response(
raise _PeerResponseDeadlineExceeded
_set_response_socket_timeout(response, remaining)
try:
- chunk = reader(
- min(_PEER_RESPONSE_CHUNK_BYTES, max_bytes + 1 - len(body))
- )
+ chunk = reader(min(_PEER_RESPONSE_CHUNK_BYTES, max_bytes + 1 - len(body)))
except Exception as exc:
if time.monotonic() >= deadline:
raise _PeerResponseDeadlineExceeded from exc
@@ -138,6 +159,10 @@ def _is_proven_pre_admission_failure(exc: BaseException) -> bool:
return isinstance(reason, OSError) and reason.errno in _NOT_ADMITTED_ERRNOS
+def _valid_code(code: Any) -> str | None:
+ return code if isinstance(code, str) and _ERROR_CODE_RE.fullmatch(code) else None
+
+
def _response_error_code(detail: str) -> str | None:
"""Extract a machine error code without returning response credentials."""
try:
@@ -148,25 +173,27 @@ def _response_error_code(detail: str) -> str | None:
return None
error = payload.get("error")
if isinstance(error, dict) and isinstance(error.get("code"), str):
- code = error["code"]
- if _ERROR_CODE_RE.fullmatch(code) is None:
- return None
- message = str(error.get("message") or "").lower()
- # Older target gateways wrap grant expiry inside the generic dispatch
- # error. Normalize it locally until their wire code becomes specific.
- if code == "invalid_room_dispatch" and "room grant" in message:
- return "invalid_room_grant"
- if code == "invalid_room_dispatch" and "capability catalog changed" in message:
- return "room_capability_catalog_changed"
- if code == "invalid_room_dispatch" and "execution policy changed" in message:
- return "room_execution_policy_changed"
+ code = _valid_code(error["code"])
+ if code == "invalid_room_dispatch":
+ message = str(error.get("message") or "").lower()
+ for needle, normalized in _LEGACY_DISPATCH_MESSAGE_CODES:
+ if needle in message:
+ return normalized
return code
- code = payload.get("code")
- return (
- code
- if isinstance(code, str) and _ERROR_CODE_RE.fullmatch(code) is not None
- else None
- )
+ return _valid_code(payload.get("code"))
+
+
+def _http_error_message(method: str, path: str, status: int, error_code: str | None) -> str:
+ if status in {401, 403} and error_code in {
+ "invalid_room_grant",
+ "room_reauthorization_required",
+ }:
+ return "peer room authorization needs renewal"
+ if status == 403 and error_code == _EXECUTION_POLICY_CHANGED[0]:
+ return _EXECUTION_POLICY_CHANGED[1]
+ if status == 403 and error_code == _CAPABILITY_CHANGED[0]:
+ return _CAPABILITY_CHANGED[1]
+ return f"peer rejected {method} {path} with HTTP {status}"
class PeerRunsHTTPError(RuntimeError):
@@ -191,25 +218,41 @@ class PeerRunsHTTPError(RuntimeError):
self.error_code = error_code
self.error_message = error_message
self.needs_reauthorization = bool(
- status_code in {401, 403}
- and error_code
- in {
- "invalid_room_grant",
- "room_capability_catalog_changed",
- "room_execution_policy_changed",
- "room_reauthorization_required",
- }
+ status_code in {401, 403} and error_code in _REAUTHORIZATION_CODES
)
self.needs_capability_refresh = bool(
- status_code == 403
- and error_code == "room_capability_catalog_changed"
+ status_code == 403 and error_code == _CAPABILITY_CHANGED[0]
)
self.needs_execution_policy_refresh = bool(
- status_code == 403
- and error_code == "room_execution_policy_changed"
+ status_code == 403 and error_code == _EXECUTION_POLICY_CHANGED[0]
)
+def digest_reauthorization_error(
+ catalog: GatewayRoomCatalog,
+ *,
+ capability_digest: str | None,
+ execution_policy_digest: str | None,
+) -> PeerRunsHTTPError | None:
+ """Return the fail-closed error when a refreshed catalog drifted from the frozen digests.
+
+ Execution policy is checked before capabilities; a ``None`` digest skips its check.
+ """
+ for expected, actual, (code, message) in (
+ (
+ execution_policy_digest,
+ catalog.execution_policy.policy_digest,
+ _EXECUTION_POLICY_CHANGED,
+ ),
+ (capability_digest, catalog.catalog_digest, _CAPABILITY_CHANGED),
+ ):
+ if expected is not None and actual != expected:
+ return PeerRunsHTTPError(
+ message, status_code=403, error_code=code, not_admitted=True
+ )
+ return None
+
+
class PeerRunsHTTPClient:
"""Drive a peer's dedicated group session via scoped async Runs APIs."""
@@ -287,28 +330,24 @@ class PeerRunsHTTPClient:
def _bind_dispatch_scope(self, dispatch: HostedMemberDispatch) -> None:
self.bind_room_scope(
- room_id=dispatch.room_id,
- home_install_id=dispatch.home_install_id,
- authority_gateway_id=dispatch.authority_gateway_id,
- authority_epoch=dispatch.authority_epoch,
- member_id=dispatch.member_id,
- target_install_id=dispatch.target_install_id,
- target_profile=dispatch.target_profile,
+ **{field: getattr(dispatch, field) for field in _RECEIPT_SCOPE_FIELDS}
)
- def _receipt_identity(
- self,
- *,
- task_id: str,
- execution_generation: int,
- ) -> dict[str, Any] | None:
- if self._room_scope is None:
- return None
- return {
- **self._room_scope,
- "task_id": task_id,
- "execution_generation": execution_generation,
- }
+ def _receipt(self, task_id: str, execution_generation: int) -> dict[str, Any] | None:
+ """Return the in-memory receipt, falling back to the durable store."""
+ record = self._runs.get((task_id, execution_generation))
+ if record is not None or self.receipt_db_path is None or self._room_scope is None:
+ return record
+ from gateway import hosted_rooms
+
+ return hosted_rooms.remote_run_receipt(
+ self.receipt_db_path,
+ record={
+ **self._room_scope,
+ "task_id": task_id,
+ "execution_generation": execution_generation,
+ },
+ )
def bind_observation(self, *, task_id: str, execution_generation: int) -> None:
"""Pin history/status reads to one exact logical task attempt."""
@@ -342,9 +381,8 @@ class PeerRunsHTTPClient:
),
"Content-Type": "application/json",
"User-Agent": "Hermes-RoomLink/1.0",
+ **(headers or {}),
}
- if headers:
- request_headers.update(headers)
request = urllib.request.Request(
f"{self.base_url}{path}",
data=(
@@ -356,18 +394,13 @@ class PeerRunsHTTPClient:
headers=request_headers,
)
try:
- with open_credentialed_url(
- request, timeout=self.timeout_seconds
- ) as response:
+ with open_credentialed_url(request, timeout=self.timeout_seconds) as response:
raw = _read_bounded_response(
- response,
- max_bytes=MAX_PEER_RESPONSE_BYTES,
- deadline=deadline,
+ response, max_bytes=MAX_PEER_RESPONSE_BYTES, deadline=deadline
).decode("utf-8", "replace")
except _PeerResponseTooLarge as exc:
raise PeerRunsHTTPError(
- "peer response exceeded the RoomLink size limit",
- ambiguous=ambiguous,
+ "peer response exceeded the RoomLink size limit", ambiguous=ambiguous
) from exc
except _PeerResponseDeadlineExceeded as exc:
raise PeerRunsHTTPError(
@@ -376,62 +409,9 @@ class PeerRunsHTTPClient:
ambiguous=ambiguous,
) from exc
except urllib.error.HTTPError as exc:
- pre_admission = bool(
- method == "POST"
- and path == "/v1/runs"
- and 400 <= exc.code < 500
- )
- try:
- detail = _read_bounded_response(
- exc,
- max_bytes=MAX_PEER_ERROR_RESPONSE_BYTES,
- deadline=deadline,
- ).decode("utf-8", "replace")[:500]
- except _PeerResponseTooLarge as body_exc:
- raise PeerRunsHTTPError(
- "peer error response exceeded the RoomLink size limit",
- ambiguous=method == "POST" and exc.code >= 500,
- not_admitted=pre_admission,
- status_code=exc.code,
- ) from body_exc
- except _PeerResponseDeadlineExceeded as body_exc:
- raise PeerRunsHTTPError(
- "peer error response exceeded the RoomLink time budget",
- retryable=True,
- ambiguous=method == "POST" and exc.code >= 500,
- not_admitted=pre_admission,
- status_code=exc.code,
- ) from body_exc
- except Exception:
- detail = ""
- error_code = _response_error_code(detail)
- logger.debug(
- "Peer RoomLink request returned HTTP %s (%s)",
- exc.code,
- error_code or "no-code",
- )
- message = (
- "peer room authorization needs renewal"
- if exc.code in {401, 403}
- and error_code in {"invalid_room_grant", "room_reauthorization_required"}
- else "peer room execution policy needs reauthorization"
- if exc.code == 403 and error_code == "room_execution_policy_changed"
- else "peer room capabilities need reauthorization"
- if exc.code == 403 and error_code == "room_capability_catalog_changed"
- else f"peer rejected {method} {path} with HTTP {exc.code}"
- )
- raise PeerRunsHTTPError(
- message,
- retryable=exc.code in {408, 425, 429} or exc.code >= 500,
- ambiguous=method == "POST" and exc.code >= 500,
- not_admitted=pre_admission,
- status_code=exc.code,
- error_code=error_code,
- ) from exc
+ self._raise_http_error(exc, method=method, path=path, deadline=deadline)
except (urllib.error.URLError, TimeoutError, OSError) as exc:
- not_admitted = method == "POST" and _is_proven_pre_admission_failure(
- exc
- )
+ not_admitted = ambiguous and _is_proven_pre_admission_failure(exc)
raise PeerRunsHTTPError(
"peer RoomLink endpoint is unreachable",
retryable=True,
@@ -446,6 +426,42 @@ class PeerRunsHTTPClient:
raise PeerRunsHTTPError("peer returned a non-object response")
return payload
+ @staticmethod
+ def _raise_http_error(
+ exc: urllib.error.HTTPError, *, method: str, path: str, deadline: float
+ ) -> NoReturn:
+ """Raise the classified PeerRunsHTTPError for an HTTP error response."""
+ ambiguous = method == "POST" and exc.code >= 500
+ # A 4xx on admission proves the peer never admitted the run.
+ pre_admission = method == "POST" and path == "/v1/runs" and 400 <= exc.code < 500
+ flags = {"ambiguous": ambiguous, "not_admitted": pre_admission, "status_code": exc.code}
+ try:
+ detail = _read_bounded_response(
+ exc, max_bytes=MAX_PEER_ERROR_RESPONSE_BYTES, deadline=deadline
+ ).decode("utf-8", "replace")[:500]
+ except _PeerResponseTooLarge as body_exc:
+ raise PeerRunsHTTPError(
+ "peer error response exceeded the RoomLink size limit", **flags
+ ) from body_exc
+ except _PeerResponseDeadlineExceeded as body_exc:
+ raise PeerRunsHTTPError(
+ "peer error response exceeded the RoomLink time budget",
+ retryable=True,
+ **flags,
+ ) from body_exc
+ except Exception:
+ detail = ""
+ error_code = _response_error_code(detail)
+ logger.debug(
+ "Peer RoomLink request returned HTTP %s (%s)", exc.code, error_code or "no-code"
+ )
+ raise PeerRunsHTTPError(
+ _http_error_message(method, path, exc.code, error_code),
+ retryable=exc.code in {408, 425, 429} or exc.code >= 500,
+ error_code=error_code,
+ **flags,
+ ) from exc
+
def prepare(
self,
*,
@@ -461,9 +477,7 @@ class PeerRunsHTTPClient:
self._require_room_grant(grant)
logical_session = (
"roomlink_"
- + hashlib.sha256(f"{room_id}\0{profile}".encode("utf-8")).hexdigest()[
- :32
- ]
+ + hashlib.sha256(f"{room_id}\0{profile}".encode("utf-8")).hexdigest()[:32]
)
if expected_session_id and expected_session_id != logical_session:
raise PeerRunsHTTPError("peer room session identity changed")
@@ -473,12 +487,10 @@ class PeerRunsHTTPClient:
"source": source,
}
- def dispatch(
- self,
- *,
- dispatch: Mapping[str, Any],
- grant: str,
- ) -> Mapping[str, Any]:
+ def _checked_dispatch(
+ self, dispatch: Mapping[str, Any], grant: str
+ ) -> HostedMemberDispatch:
+ """Validate a dispatch, its grant, and pin scope + observation to it."""
checked = HostedMemberDispatch.from_mapping(dispatch)
self._require_room_grant(grant)
self._bind_dispatch_scope(checked)
@@ -486,6 +498,15 @@ class PeerRunsHTTPClient:
task_id=checked.task_id,
execution_generation=checked.execution_generation,
)
+ return checked
+
+ def dispatch(
+ self,
+ *,
+ dispatch: Mapping[str, Any],
+ grant: str,
+ ) -> Mapping[str, Any]:
+ checked = self._checked_dispatch(dispatch, grant)
return self._admit_dispatch(checked, grant=grant)
def recover_dispatch(
@@ -495,45 +516,22 @@ class PeerRunsHTTPClient:
grant: str,
) -> Mapping[str, Any]:
"""Recover one exact admission by receipt or idempotent POST replay."""
- checked = HostedMemberDispatch.from_mapping(dispatch)
- self._require_room_grant(grant)
- self._bind_dispatch_scope(checked)
- self.bind_observation(
- task_id=checked.task_id,
- execution_generation=checked.execution_generation,
- )
+ checked = self._checked_dispatch(dispatch, grant)
existing = self._receipt_for_dispatch(checked)
if existing is not None:
- expected = (
- checked.room_id,
- checked.home_install_id,
- checked.authority_gateway_id,
- checked.authority_epoch,
- checked.member_id,
- checked.target_install_id,
- checked.target_profile,
- )
- stored = (
- existing["room_id"],
- existing["home_install_id"],
- existing["authority_gateway_id"],
- existing["authority_epoch"],
- existing["member_id"],
- existing["target_install_id"],
- existing["target_profile"],
- )
- if stored != expected:
+ if any(
+ existing[field] != getattr(checked, field)
+ for field in _RECEIPT_SCOPE_FIELDS
+ ):
raise PeerRunsHTTPError(
"peer run receipt conflicts with the recovered dispatch"
)
- return {
- "status": "accepted",
- "task_id": checked.task_id,
- "execution_generation": checked.execution_generation,
- "run_id": str(existing["run_id"]),
- "session_id": str(existing["session_id"]),
- "replayed": True,
- }
+ return self._accepted(
+ checked,
+ run_id=str(existing["run_id"]),
+ session_id=str(existing["session_id"]),
+ replayed=True,
+ )
key = (checked.task_id, checked.execution_generation)
now = self.clock()
backoff = self._recovery_backoff.get(key)
@@ -549,15 +547,25 @@ class PeerRunsHTTPClient:
if exc.retryable or exc.ambiguous:
delay = self._next_poll_delay(backoff)
self._recovery_backoff = {
- key: {
- "delay": delay,
- "next_attempt_at": now + delay,
- }
+ key: {"delay": delay, "next_attempt_at": now + delay}
}
raise
self._recovery_backoff.pop(key, None)
return recovered
+ @staticmethod
+ def _accepted(
+ checked: HostedMemberDispatch, *, run_id: str, session_id: str, replayed: bool
+ ) -> dict[str, Any]:
+ return {
+ "status": "accepted",
+ "task_id": checked.task_id,
+ "execution_generation": checked.execution_generation,
+ "run_id": run_id,
+ "session_id": session_id,
+ "replayed": replayed,
+ }
+
def _admit_dispatch(
self,
checked: HostedMemberDispatch,
@@ -592,33 +600,22 @@ class PeerRunsHTTPClient:
receipt = {
"run_id": run_id,
"session_id": session_id,
- "room_id": checked.room_id,
- "home_install_id": checked.home_install_id,
- "authority_gateway_id": checked.authority_gateway_id,
- "authority_epoch": checked.authority_epoch,
- "member_id": checked.member_id,
+ **{field: getattr(checked, field) for field in _RECEIPT_SCOPE_FIELDS},
"task_id": checked.task_id,
"execution_generation": checked.execution_generation,
- "target_install_id": checked.target_install_id,
- "target_profile": checked.target_profile,
}
if self.receipt_db_path is not None:
from gateway import hosted_rooms
- hosted_rooms.upsert_remote_run_receipt(
- self.receipt_db_path,
- record=receipt,
- )
+ hosted_rooms.upsert_remote_run_receipt(self.receipt_db_path, record=receipt)
self._runs[(checked.task_id, checked.execution_generation)] = receipt
self._status_cache.pop(run_id, None)
- return {
- "status": "accepted",
- "task_id": checked.task_id,
- "execution_generation": checked.execution_generation,
- "run_id": run_id,
- "session_id": session_id,
- "replayed": bool(result.get("replayed", False)),
- }
+ return self._accepted(
+ checked,
+ run_id=run_id,
+ session_id=session_id,
+ replayed=bool(result.get("replayed", False)),
+ )
def _session_id(self, dispatch: HostedMemberDispatch, *, grant: str) -> str:
existing = self._receipt_for_dispatch(dispatch)
@@ -638,22 +635,9 @@ class PeerRunsHTTPClient:
def _observation_receipt(
self, *, room_id: str, profile: str, session_id: str
) -> dict[str, Any] | None:
- record = None
- if self._observation_key is not None:
- task_id, execution_generation = self._observation_key
- record = self._runs.get(self._observation_key)
- if record is None and self.receipt_db_path is not None:
- from gateway import hosted_rooms
-
- identity = self._receipt_identity(
- task_id=task_id,
- execution_generation=execution_generation,
- )
- if identity is not None:
- record = hosted_rooms.remote_run_receipt(
- self.receipt_db_path,
- record=identity,
- )
+ if self._observation_key is None:
+ return None
+ record = self._receipt(*self._observation_key)
if record is None:
return None
if (
@@ -668,36 +652,19 @@ class PeerRunsHTTPClient:
def _compact_run_status(status: Mapping[str, Any]) -> dict[str, Any]:
return {
key: status[key]
- for key in (
- "run_id",
- "status",
- "output",
- "error",
- "approval",
- "last_event",
- )
+ for key in ("run_id", "status", "output", "error", "approval", "last_event")
if key in status
}
def _next_poll_delay(self, cached: Mapping[str, Any] | None) -> float:
previous = (
- float(cached["delay"])
- if cached is not None
- else self.poll_min_seconds / 2
- )
- return min(
- self.poll_max_seconds,
- max(self.poll_min_seconds, previous * 2),
+ float(cached["delay"]) if cached is not None else self.poll_min_seconds / 2
)
+ return min(self.poll_max_seconds, max(self.poll_min_seconds, previous * 2))
@staticmethod
def _run_is_terminal(status: Mapping[str, Any]) -> bool:
- return status.get("status") in {
- "completed",
- "failed",
- "interrupted",
- "cancelled",
- }
+ return status.get("status") in _TERMINAL_RUN_STATES
def _poll_receipt(
self,
@@ -717,6 +684,7 @@ class PeerRunsHTTPClient:
if isinstance(error, PeerRunsHTTPError):
raise error
return status
+ delay = self._next_poll_delay(cached)
try:
status = self._compact_run_status(
self._request(
@@ -726,21 +694,10 @@ class PeerRunsHTTPClient:
)
if (
str(status.get("run_id") or "") != run_id
- or status.get("status")
- not in {
- "queued",
- "running",
- "waiting_for_approval",
- "stopping",
- "completed",
- "failed",
- "interrupted",
- "cancelled",
- }
+ or status.get("status") not in _KNOWN_RUN_STATES
):
raise PeerRunsHTTPError("peer returned a mismatched run status")
except PeerRunsHTTPError as exc:
- delay = self._next_poll_delay(cached)
self._status_cache = {
run_id: {
"status": cached["status"] if cached is not None else {},
@@ -750,13 +707,8 @@ class PeerRunsHTTPClient:
}
}
raise
- delay = self._next_poll_delay(cached)
self._status_cache = {
- run_id: {
- "status": status,
- "delay": delay,
- "next_poll_at": now + delay,
- }
+ run_id: {"status": status, "delay": delay, "next_poll_at": now + delay}
}
if self._run_is_terminal(status):
self._terminal_receipts.add(
@@ -767,22 +719,7 @@ class PeerRunsHTTPClient:
def _receipt_for_dispatch(
self, dispatch: HostedMemberDispatch
) -> dict[str, Any] | None:
- key = (dispatch.task_id, dispatch.execution_generation)
- record = self._runs.get(key)
- if record is not None or self.receipt_db_path is None:
- return record
- from gateway import hosted_rooms
-
- identity = self._receipt_identity(
- task_id=dispatch.task_id,
- execution_generation=dispatch.execution_generation,
- )
- if identity is None:
- return None
- return hosted_rooms.remote_run_receipt(
- self.receipt_db_path,
- record=identity,
- )
+ return self._receipt(dispatch.task_id, dispatch.execution_generation)
def history(
self,
@@ -793,9 +730,7 @@ class PeerRunsHTTPClient:
grant: str,
) -> Sequence[Mapping[str, Any]]:
receipt = self._observation_receipt(
- room_id=room_id,
- profile=profile,
- session_id=session_id,
+ room_id=room_id, profile=profile, session_id=session_id
)
if receipt is None:
return []
@@ -823,16 +758,13 @@ class PeerRunsHTTPClient:
grant: str,
) -> Mapping[str, Any]:
receipt = self._observation_receipt(
- room_id=room_id,
- profile=profile,
- session_id=session_id,
+ room_id=room_id, profile=profile, session_id=session_id
)
if receipt is None:
return {"active": False, "task_id": None}
status = self._poll_receipt(receipt, grant=grant)
- active_states = {"queued", "running", "waiting_for_approval", "stopping"}
return {
- "active": status.get("status") in active_states,
+ "active": status.get("status") in _ACTIVE_RUN_STATES,
"task_id": receipt["task_id"],
"execution_generation": receipt["execution_generation"],
"status": status.get("status"),
@@ -850,32 +782,28 @@ class PeerRunsHTTPClient:
grant: str,
) -> Mapping[str, Any] | None:
"""Resolve approval for the exact durable remote run."""
- record = self._runs.get((task_id, execution_generation))
- if record is None and self.receipt_db_path is not None:
- from gateway import hosted_rooms
-
- identity = self._receipt_identity(
- task_id=task_id,
- execution_generation=execution_generation,
- )
- if identity is not None:
- record = hosted_rooms.remote_run_receipt(
- self.receipt_db_path,
- record=identity,
- )
+ record = self._receipt(task_id, execution_generation)
if record is None:
return None
request_id = str(request_id or "").strip()
if not request_id:
raise PeerRunsHTTPError("an exact approval request_id is required")
self._require_room_grant(grant)
+ return self._post_run_action(
+ record, "approval", body={"choice": choice, "request_id": request_id}, grant=grant
+ )
+
+ def _post_run_action(
+ self, record: Mapping[str, Any], action: str, *, body: dict[str, Any], grant: str
+ ) -> dict[str, Any]:
+ run_id = str(record["run_id"])
result = self._request(
- f"/v1/runs/{urllib.parse.quote(str(record['run_id']), safe='')}/approval",
+ f"/v1/runs/{urllib.parse.quote(run_id, safe='')}/{action}",
method="POST",
- body={"choice": choice, "request_id": request_id},
+ body=body,
room_grant=grant,
)
- self._status_cache.pop(str(record["run_id"]), None)
+ self._status_cache.pop(run_id, None)
return result
def stop(
@@ -900,28 +828,12 @@ class PeerRunsHTTPClient:
grant: str,
) -> Mapping[str, Any] | None:
"""Stop the exact durable remote run after a home restart."""
- record = self._runs.get((task_id, execution_generation))
- if record is None and self.receipt_db_path is not None:
- from gateway import hosted_rooms
-
- identity = self._receipt_identity(
- task_id=task_id,
- execution_generation=execution_generation,
- )
- if identity is not None:
- record = hosted_rooms.remote_run_receipt(
- self.receipt_db_path,
- record=identity,
- )
+ record = self._receipt(task_id, execution_generation)
if record is None:
return None
- result = self._request(
- f"/v1/runs/{urllib.parse.quote(str(record['run_id']), safe='')}/stop",
- method="POST",
- body={},
- room_grant=self._require_room_grant(grant),
+ result = self._post_run_action(
+ record, "stop", body={}, grant=self._require_room_grant(grant)
)
- self._status_cache.pop(str(record["run_id"]), None)
if self._run_is_terminal(result):
self._terminal_receipts.add((str(task_id), int(execution_generation)))
return result
@@ -971,12 +883,8 @@ class PeerRunsHTTPClient:
execution_policy_digest: str | None = None,
) -> Mapping[str, Any]:
"""Renew dispatch access only while its frozen authority is unchanged."""
- self._require_room_grant(grant)
- refreshed = self._request(
- "/v1/room-members/grants/refresh",
- method="POST",
- body={"ttl_seconds": ttl_seconds},
- room_grant=grant,
+ refreshed = self._scoped_post(
+ "/v1/room-members/grants/refresh", grant, body={"ttl_seconds": ttl_seconds}
)
replacement = str(refreshed.get("grant") or "")
if not replacement:
@@ -984,49 +892,27 @@ class PeerRunsHTTPClient:
# Persist only after the target proves the replacement can authorize
# the same scoped capability endpoint.
probe = self.probe(grant=replacement)
- from gateway.hosted_room_peer import GatewayRoomCatalog
-
- catalog = GatewayRoomCatalog.from_mapping(probe.get("catalog"))
- if (
- execution_policy_digest is not None
- and catalog.execution_policy.policy_digest
- != execution_policy_digest
- ):
- raise PeerRunsHTTPError(
- "peer room execution policy needs reauthorization",
- status_code=403,
- error_code="room_execution_policy_changed",
- not_admitted=True,
- )
- if (
- capability_digest is not None
- and catalog.catalog_digest != capability_digest
- ):
- raise PeerRunsHTTPError(
- "peer room capabilities need reauthorization",
- status_code=403,
- error_code="room_capability_catalog_changed",
- not_admitted=True,
- )
+ error = digest_reauthorization_error(
+ GatewayRoomCatalog.from_mapping(probe.get("catalog")),
+ capability_digest=capability_digest,
+ execution_policy_digest=execution_policy_digest,
+ )
+ if error is not None:
+ raise error
return {**refreshed, "catalog": probe.get("catalog")}
def revoke_grant(self, *, grant: str) -> Mapping[str, Any]:
"""Revoke this grant's exact room/home/target/profile scope."""
- self._require_room_grant(grant)
- return self._request(
- "/v1/room-members/grants/revoke",
- method="POST",
- body={},
- room_grant=grant,
- )
+ return self._scoped_post("/v1/room-members/grants/revoke", grant, body={})
def probe(self, *, grant: str) -> Mapping[str, Any]:
"""Verify gateway reachability and the live scoped capability catalog."""
self._require_room_grant(grant)
- return self._request(
- "/v1/room-members/capabilities",
- room_grant=grant,
- )
+ return self._request("/v1/room-members/capabilities", room_grant=grant)
+
+ def _scoped_post(self, path: str, grant: str, *, body: dict[str, Any]) -> dict[str, Any]:
+ self._require_room_grant(grant)
+ return self._request(path, method="POST", body=body, room_grant=grant)
@staticmethod
def _require_room_grant(grant: str) -> str:
diff --git a/tui_gateway/mcp_oauth_sessions.py b/tui_gateway/mcp_oauth_sessions.py
index e549f59c475..25011a6dc3a 100644
--- a/tui_gateway/mcp_oauth_sessions.py
+++ b/tui_gateway/mcp_oauth_sessions.py
@@ -1,42 +1,26 @@
"""Session-backed MCP OAuth flows for the gateway (mcp.servers.oauth.*).
-This mirrors the *provider* OAuth model used by the dashboard
-(``/api/providers/oauth/{id}/start`` + ``/poll/{session_id}``) rather than the
-FastAPI-request-coupled MCP dashboard flow: a ``start`` primitive kicks off a
-background worker and returns ``{session_id, auth_url, flow}``; a ``poll``
-primitive reports ``{status: pending|approved|error}`` until the tokens land on
-disk for that server in that profile.
-
-The underlying token machinery is the *same* one the CLI ``hermes mcp login``
-uses — ``hermes_cli.mcp_config._probe_single_server`` under
-``tools.mcp_oauth.force_interactive_oauth`` — so no OAuth logic is reimplemented
-here. The only new piece is decoupling the two browser callbacks (authorization
-URL out, ``code``/``state`` back in) from a FastAPI ``Request``:
-
-* ``tools.mcp_dashboard_oauth.DashboardOAuthFlow`` already provides the two
- thread-safe rendezvous points (``publish_authorization_url`` /
- ``deliver_callback``). We reuse it verbatim as the bridge object.
-* Instead of routing the browser redirect through a FastAPI callback route, we
- run a tiny loopback HTTP listener on ``127.0.0.1:<port>/callback`` and set the
- flow's ``redirect_uri`` to it. When the provider redirects the user's browser
- there, the listener calls ``flow.deliver_callback(...)``. This is the same
- loopback strategy the CLI uses by default, just wired to the shared bridge.
-
-Client contract (what the desktop plugin does):
- 1. call ``mcp.servers.oauth.start(profile, name)`` → ``{session_id, auth_url}``
- 2. open ``auth_url`` in the native browser (``openExternal``)
- 3. poll ``mcp.servers.oauth.poll(profile, name, session_id)`` until
- ``status == "approved"`` (tokens persisted) or ``"error"``.
-
-Remote-backend variant (client-side callback): when the desktop app runs on a
-DIFFERENT machine than the gateway (SSH/Tailscale remote backend), the
-gateway-side ``127.0.0.1`` listener is unreachable from the user's browser —
-the redirect lands on the user's machine where nothing is listening, and the
-flow times out. For that topology the client binds its OWN loopback listener
-(same pattern as the desktop's native gateway login), passes its
-``redirect_uri`` to ``start`` (``client_redirect_uri``), and relays the
-provider redirect back via ``deliver_callback_flow`` /
-``mcp.servers.oauth.callback``. State verification stays server-side in
+Mirrors the *provider* OAuth model used by the dashboard rather than the
+FastAPI-request-coupled MCP dashboard flow: ``start`` kicks off a background
+worker and returns ``{session_id, auth_url, flow}``; ``poll`` reports
+``{status: pending|approved|error}`` until tokens land on disk for that server
+in that profile.
+
+No OAuth logic is reimplemented here — the token machinery is the same one
+``hermes mcp login`` uses (``_probe_single_server`` under
+``force_interactive_oauth``). ``DashboardOAuthFlow`` is reused verbatim as the
+thread-safe bridge (``publish_authorization_url`` / ``deliver_callback``); the
+only new piece is a tiny loopback HTTP listener on ``127.0.0.1:<port>/callback``
+that feeds ``deliver_callback`` instead of a FastAPI route.
+
+Client contract: ``start(profile, name)`` → open ``auth_url`` in the browser →
+poll until ``status`` is ``approved`` (tokens persisted) or ``error``.
+
+Remote-backend variant: when the desktop app runs on a DIFFERENT machine than
+the gateway, a gateway-side ``127.0.0.1`` listener is unreachable from the
+user's browser. The client binds its OWN loopback listener, passes its
+``client_redirect_uri`` to ``start``, and relays the redirect back via
+``deliver_callback_flow``. State verification stays server-side in
``DashboardOAuthFlow.deliver_callback`` — a relayed code with the wrong
``state`` is rejected exactly like a forged loopback hit.
"""
@@ -51,8 +35,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
from urllib.parse import parse_qs, urlparse
-# Session registry: session_id -> record. A record wraps the shared
-# DashboardOAuthFlow bridge plus a bit of gateway bookkeeping.
+# session_id -> record wrapping the shared DashboardOAuthFlow bridge plus bookkeeping.
_sessions: Dict[str, Dict[str, Any]] = {}
_sessions_lock = threading.Lock()
@@ -75,26 +58,23 @@ def _gc_sessions() -> None:
def _shutdown_listener(rec: Dict[str, Any]) -> None:
server = rec.get("httpd")
- if server is not None:
+ if server is None:
+ return
+ for stop in (server.shutdown, server.server_close):
try:
- server.shutdown()
+ stop()
except Exception:
pass
- try:
- server.server_close()
- except Exception:
- pass
- rec["httpd"] = None
+ rec["httpd"] = None
def _validate_client_redirect_uri(uri: str) -> str:
"""Validate a client-supplied loopback redirect URI.
- Only plain-http loopback URLs are accepted (``http://127.0.0.1:<port>/...``
- or ``http://localhost:<port>/...``), mirroring RFC 8252 native-app rules —
- the client hosts a one-shot listener on ITS machine, so anything else
- (public hosts, https proxies, schemes) is rejected to keep the gateway from
- pinning an attacker-controlled redirect into a DCR registration.
+ Only plain-http loopback URLs (``http://127.0.0.1:<port>/...`` or
+ ``localhost``) are accepted, per RFC 8252 native-app rules — anything else
+ is rejected so the gateway can't pin an attacker-controlled redirect into a
+ DCR registration.
"""
parsed = urlparse(str(uri or "").strip())
host = (parsed.hostname or "").lower()
@@ -115,10 +95,9 @@ def _validate_client_redirect_uri(uri: str) -> str:
def _start_loopback_listener(flow) -> "http.server.HTTPServer":
"""Bind a loopback callback listener that feeds the flow's deliver_callback.
- Returns the running HTTPServer (already serving on a daemon thread). The
- bound port is read back off ``server.server_address`` so the caller can set
- ``flow.redirect_uri`` to the matching ``/callback`` URL BEFORE the worker
- starts the OAuth flow (the redirect URI must be pinned at authorization).
+ Returns the HTTPServer already serving on a daemon thread; the caller reads
+ the bound port off ``server_address`` to pin ``flow.redirect_uri`` BEFORE the
+ worker starts the flow (the redirect URI is fixed at authorization).
"""
class _Handler(http.server.BaseHTTPRequestHandler):
@@ -129,9 +108,7 @@ def _start_loopback_listener(flow) -> "http.server.HTTPServer":
self.end_headers()
return
qs = parse_qs(parsed.query)
- code = (qs.get("code") or [None])[0]
- state = (qs.get("state") or [None])[0]
- error = (qs.get("error") or [None])[0]
+ code, state, error = ((qs.get(k) or [None])[0] for k in ("code", "state", "error"))
body = b"<h1>Authorization received</h1><p>You can close this tab and return to Hermes.</p>"
status = 200
try:
@@ -163,12 +140,12 @@ def _start_loopback_listener(flow) -> "http.server.HTTPServer":
def _worker(session_id: str, hermes_home: str, server_name: str, cfg: dict, reconnect_live: bool) -> None:
"""Drive the interactive MCP OAuth probe under the shared dashboard bridge.
- Structurally identical to ``web_server._run_dashboard_mcp_oauth`` — the same
- HERMES_HOME override + secret-scope + force_interactive_oauth +
- dashboard_oauth_flow wrapping around ``_probe_single_server`` — but keyed to
- our session record instead of a FastAPI request. On success the token file
- exists on disk (verified via ``_oauth_tokens_present``) and the server config
- is (re)saved into the profile's config.yaml.
+ Same HERMES_HOME override + secret-scope + force_interactive_oauth +
+ dashboard_oauth_flow wrapping around ``_probe_single_server`` as
+ ``web_server._run_dashboard_mcp_oauth``, keyed to our session record. On
+ success the token file exists on disk and the server config is (re)saved
+ into the profile's config.yaml; on failure the prior token/manager state is
+ restored.
"""
from hermes_cli.mcp_config import (
_oauth_tokens_present,
@@ -231,11 +208,9 @@ def _worker(session_id: str, hermes_home: str, server_name: str, cfg: dict, reco
try:
from tools.mcp_oauth import humanize_oauth_registration_error
- humanized = humanize_oauth_registration_error(
+ msg = humanize_oauth_registration_error(
server_name, exc, server_url=cfg.get("url") if isinstance(cfg, dict) else None
- )
- if humanized:
- msg = humanized
+ ) or msg
except Exception:
pass
if flow is not None:
@@ -258,16 +233,15 @@ def start_flow(
) -> Dict[str, Any]:
"""Begin an MCP OAuth flow and return ``{session_id, auth_url, flow}``.
- ``cfg`` is the server's resolved config dict (must have ``url`` and be
- OAuth-capable). ``hermes_home`` is the already-resolved profile home dir
- string. Blocks up to ``url_timeout`` for the worker to publish the browser
- authorization URL, then returns it.
+ ``cfg`` is the server's resolved config (must have ``url`` and be
+ OAuth-capable); ``hermes_home`` the resolved profile home. Blocks up to
+ ``url_timeout`` for the worker to publish the authorization URL.
- ``client_redirect_uri`` (remote-backend variant): a loopback callback URL
- the CLIENT hosts on its own machine. When set (and valid), no gateway-side
- listener is bound — the OAuth ``redirect_uri`` is pinned to the client's
- listener, and the client relays the redirect's ``code``/``state`` back via
- ``deliver_callback_flow``. Invalid values raise ``ValueError``.
+ ``client_redirect_uri`` (remote-backend variant): a loopback URL the CLIENT
+ hosts. When set and valid, no gateway-side listener is bound — the OAuth
+ ``redirect_uri`` is pinned to the client's listener and the client relays
+ ``code``/``state`` via ``deliver_callback_flow``. Invalid values raise
+ ``ValueError``.
"""
from tools.mcp_dashboard_oauth import DashboardOAuthFlow
@@ -277,19 +251,10 @@ def start_flow(
_gc_sessions()
with _sessions_lock:
- pending = sum(
- 1
- for r in _sessions.values()
- if not r["flow"].worker_done
- )
- if pending >= _MAX_PENDING:
+ active = [r for r in _sessions.values() if not r["flow"].worker_done]
+ if len(active) >= _MAX_PENDING:
raise RuntimeError("Too many MCP OAuth flows are already in progress")
- if any(
- r["server_name"] == server_name
- and r["hermes_home"] == hermes_home
- and not r["flow"].worker_done
- for r in _sessions.values()
- ):
+ if any(r["server_name"] == server_name and r["hermes_home"] == hermes_home for r in active):
raise RuntimeError(f"MCP OAuth for '{server_name}' is already in progress")
session_id = secrets.token_urlsafe(24)
@@ -302,16 +267,13 @@ def start_flow(
reconnect_live=reconnect_live,
)
if client_redirect_uri:
- # Remote-backend variant: the CLIENT hosts the callback listener on its
- # own machine and relays the code via deliver_callback_flow(). No
- # gateway-side listener is bound — a 127.0.0.1 port here would be
+ # Client hosts the callback listener; a 127.0.0.1 port here would be
# unreachable from the user's browser anyway.
httpd = None
flow.redirect_uri = client_redirect_uri
else:
httpd = _start_loopback_listener(flow)
- port = httpd.server_address[1]
- flow.redirect_uri = f"http://127.0.0.1:{port}/callback"
+ flow.redirect_uri = f"http://127.0.0.1:{httpd.server_address[1]}/callback"
rec = {
"session_id": session_id,
@@ -353,36 +315,38 @@ def start_flow(
return {
"session_id": session_id,
"auth_url": auth_url,
- # "pkce" mirrors the provider-OAuth ``flow`` discriminator: the client
- # opens a URL then polls (no user_code to type, unlike device_code).
+ # Mirrors the provider-OAuth ``flow`` discriminator: open a URL then poll
+ # (no user_code to type, unlike device_code).
"flow": "pkce",
}
+def _lookup(session_id: str, server_name: str) -> "tuple[Dict[str, Any] | None, str | None]":
+ """Find a session record; returns ``(rec, None)`` or ``(None, error_message)``."""
+ with _sessions_lock:
+ rec = _sessions.get(session_id)
+ if rec is None:
+ return None, "OAuth session not found or expired"
+ if rec["server_name"] != server_name:
+ return None, "server name mismatch for session"
+ return rec, None
+
+
def poll_flow(session_id: str, server_name: str) -> Dict[str, Any]:
"""Poll a session's status → ``{status, error_message?, auth_url?, tools?}``.
- ``status`` is one of ``pending`` | ``approved`` | ``error`` — the same
- vocabulary as the provider poll endpoint (``authorization_required`` from
- the underlying bridge maps to ``pending`` since the client only needs to
- know whether to keep waiting).
+ ``status`` is ``pending`` | ``approved`` | ``error`` — the provider poll
+ vocabulary (``authorization_required`` from the bridge maps to ``pending``
+ since the client only needs to know whether to keep waiting).
"""
- with _sessions_lock:
- rec = _sessions.get(session_id)
+ rec, err = _lookup(session_id, server_name)
if rec is None:
- return {"status": "error", "error_message": "OAuth session not found or expired"}
- if rec["server_name"] != server_name:
- return {"status": "error", "error_message": "server name mismatch for session"}
+ return {"status": "error", "error_message": err}
flow = rec["flow"]
snap = flow.snapshot()
raw = snap.get("status")
- if raw == "approved":
- status = "approved"
- elif raw == "error":
- status = "error"
- else:
- status = "pending"
+ status = raw if raw in ("approved", "error") else "pending"
out: Dict[str, Any] = {
"session_id": session_id,
"status": status,
@@ -404,26 +368,16 @@ def deliver_callback_flow(
) -> Dict[str, Any]:
"""Relay a client-captured OAuth redirect into a session's flow.
- Remote-backend companion to ``start_flow(client_redirect_uri=...)``: the
- desktop app's loopback listener caught the provider redirect on the USER'S
- machine and forwards ``code``/``state`` (or ``error``) here. Security
- properties are unchanged from the gateway-listener path — the underlying
- ``DashboardOAuthFlow.deliver_callback`` verifies ``state`` against the
- pinned authorization request (constant-time compare) and rejects replays,
- so a forged or replayed relay fails identically to a forged loopback hit.
-
- Returns ``{ok: true}`` on acceptance or ``{ok: false, error_message}``.
+ Remote-backend companion to ``start_flow(client_redirect_uri=...)``.
+ Security is unchanged from the gateway-listener path — the underlying
+ ``DashboardOAuthFlow.deliver_callback`` verifies ``state`` (constant-time)
+ and rejects replays. Returns ``{ok: true}`` or ``{ok: false, error_message}``.
"""
- with _sessions_lock:
- rec = _sessions.get(session_id)
+ rec, err = _lookup(session_id, server_name)
if rec is None:
- return {"ok": False, "error_message": "OAuth session not found or expired"}
- if rec["server_name"] != server_name:
- return {"ok": False, "error_message": "server name mismatch for session"}
-
- flow = rec["flow"]
+ return {"ok": False, "error_message": err}
try:
- flow.deliver_callback(code=code, state=state, error=error)
+ rec["flow"].deliver_callback(code=code, state=state, error=error)
except ValueError as exc:
return {"ok": False, "error_message": str(exc)}
return {"ok": True, "session_id": session_id}
diff --git a/tui_gateway/mcp_rpc_helpers.py b/tui_gateway/mcp_rpc_helpers.py
index 60290cfa9eb..f593d743753 100644
--- a/tui_gateway/mcp_rpc_helpers.py
+++ b/tui_gateway/mcp_rpc_helpers.py
@@ -1,10 +1,9 @@
"""Shared helpers for the per-profile MCP lifecycle RPCs (mcp.servers.*).
-These live in their own module (not methods_tools) because methods_tools
-handlers are rebound onto ``tui_gateway.server``'s globals at install time
-(see method_ctx.HandlerRegistry.install); a plain module-level def in
-methods_tools would not be reachable from a rebound handler body. Handlers
-import these at call time instead.
+Kept out of methods_tools because its handlers are rebound onto
+``tui_gateway.server``'s globals at install time (method_ctx.HandlerRegistry),
+so a module-level def there would be unreachable from a rebound handler body.
+Handlers import these at call time instead.
"""
from __future__ import annotations
@@ -15,10 +14,9 @@ from typing import Any, Dict, Optional, Tuple
def resolve_profile(rid, params, err_fn) -> Tuple[Optional[Any], Optional[dict]]:
"""Resolve the optional ``profile`` param to a HERMES_HOME override token.
- Returns ``(token, error)``: ``token`` is None for the launch profile (no
- override) or an opaque reset token; ``error`` is a JSON-RPC error dict
- (built via ``err_fn``) when the named profile doesn't exist. Callers reset
- ``token`` in a finally via :func:`reset_profile`.
+ Returns ``(token, error)``: ``token`` is None for the launch profile or an
+ opaque reset token for :func:`reset_profile`; ``error`` is a JSON-RPC error
+ dict (via ``err_fn``) when the named profile doesn't exist.
"""
profile = str(params.get("profile") or "").strip()
if not profile:
@@ -33,21 +31,22 @@ def resolve_profile(rid, params, err_fn) -> Tuple[Optional[Any], Optional[dict]]
def reset_profile(token) -> None:
- if token is not None:
- try:
- from hermes_constants import reset_hermes_home_override
+ if token is None:
+ return
+ try:
+ from hermes_constants import reset_hermes_home_override
- reset_hermes_home_override(token)
- except Exception:
- pass
+ reset_hermes_home_override(token)
+ except Exception:
+ pass
def summarize_server(name: str, cfg: dict) -> Dict[str, Any]:
"""Serialize one server's config for a UI (no secret values).
- Mirrors web_server._mcp_server_summary plus an ``oauth_tokens_present``
- flag so a UI can tell an OAuth server that still needs authentication from
- one already authenticated.
+ Mirrors web_server._mcp_server_summary plus ``oauth_tokens_present`` so a UI
+ can tell an OAuth server that still needs authentication from one already
+ authenticated.
"""
from hermes_cli.mcp_config import _oauth_tokens_present
@@ -55,11 +54,8 @@ def summarize_server(name: str, cfg: dict) -> Dict[str, Any]:
transport = "http" if cfg.get("url") else ("stdio" if cfg.get("command") else "unknown")
auth = cfg.get("auth")
headers = cfg.get("headers") or {}
- if not auth and isinstance(headers, dict) and any(
- str(key).lower() == "authorization" for key in headers
- ):
+ if not auth and isinstance(headers, dict) and any(str(key).lower() == "authorization" for key in headers):
auth = "header"
- tokens_present = _oauth_tokens_present(name) if auth == "oauth" else None
return {
"name": name,
"transport": transport,
@@ -68,7 +64,7 @@ def summarize_server(name: str, cfg: dict) -> Dict[str, Any]:
"args": list(cfg.get("args") or []),
"env": sorted(str(k) for k in (cfg.get("env") or {})),
"auth": auth,
- "oauth_tokens_present": tokens_present,
+ "oauth_tokens_present": _oauth_tokens_present(name) if auth == "oauth" else None,
"enabled": cfg.get("enabled", True) is not False,
"tools": cfg.get("tools"),
}
diff --git a/tui_gateway/method_ctx.py b/tui_gateway/method_ctx.py
index a72f802bfae..866454666de 100644
--- a/tui_gateway/method_ctx.py
+++ b/tui_gateway/method_ctx.py
@@ -1,25 +1,61 @@
-"""Seam for the server.py @method handler split (mechanical move).
-
-server.py's ~130 JSON-RPC handlers close over its module globals
-(``_sessions``, ``_ok``, ``_err``, config helpers, ...). To move them
-out of the 19K-line module without rewriting a single handler body,
-each ``methods_*`` module defines its handlers under a local
-:class:`HandlerRegistry` and server.py calls :meth:`HandlerRegistry.install`
-at the end of its own import, once every global the handlers close over
-exists. ``install()`` rebinds each handler's ``__globals__`` to
-server.py's namespace with ``types.FunctionType``, so handler bodies
-stay byte-identical and ``global X`` statements inside handlers keep
-mutating server.py state exactly as before the split.
-
-No import cycle: ``methods_*`` modules never import server at module
-level — server imports them and passes itself to ``register()``.
+"""Seam for the server.py handler/helper split.
+
+server.py's JSON-RPC handlers and many helpers close over its module globals
+(``_sessions``, ``_ok``, ``_err``, config helpers, ...). To move them out
+without rewriting a single body, each split module defines its code normally
+and server.py calls :func:`bind_module` at the end of its own import, once
+every global the code closes over exists. Function bodies are re-created with
+``types.FunctionType`` against server.py's namespace, so they stay
+byte-identical and ``global X`` statements keep mutating server.py state.
+
+No import cycle: split modules never import server at module level — server
+imports them and passes itself in.
"""
+import contextlib
import types
+# contextlib.contextmanager wraps the generator; rebind the generator (found via
+# __wrapped__) and re-wrap, otherwise only the wrapper would see server globals.
+_CM_HELPER_CODE = contextlib.contextmanager(lambda: (yield)).__code__
+
+
+def rebind(fn, g: dict, _seen=None):
+ """Copy ``fn`` with globals ``g``.
+
+ Closure cells holding functions from the same module are rebound too, so
+ handlers produced by import-time decorator factories keep working.
+ """
+ _seen = {} if _seen is None else _seen
+ if id(fn) in _seen:
+ return _seen[id(fn)]
+ wrapped = getattr(fn, "__wrapped__", None)
+ if wrapped is not None and fn.__code__ is _CM_HELPER_CODE:
+ return contextlib.contextmanager(rebind(wrapped, g, _seen))
+ closure = fn.__closure__
+ if closure:
+ cells = []
+ for cell in closure:
+ try:
+ val = cell.cell_contents
+ except ValueError: # empty cell
+ cells.append(cell)
+ continue
+ if isinstance(val, types.FunctionType) and val.__module__ == fn.__module__:
+ cells.append(types.CellType(rebind(val, g, _seen)))
+ else:
+ cells.append(cell)
+ closure = tuple(cells)
+ real = types.FunctionType(fn.__code__, g, fn.__name__, fn.__defaults__, closure)
+ real.__kwdefaults__ = fn.__kwdefaults__
+ real.__doc__ = fn.__doc__
+ real.__dict__.update(fn.__dict__)
+ _seen[id(fn)] = real
+ return real
+
class HandlerRegistry:
- """Deferred @method registrar used by the methods_* split modules."""
+ """Deferred @method registrar used by the split modules."""
def __init__(self) -> None:
self._pending: list[tuple[str, types.FunctionType]] = []
@@ -42,12 +78,43 @@ class HandlerRegistry:
"""Rebind pending handlers onto ``server``'s globals and register them."""
g = vars(server)
for name, fn in self._pending:
- real = types.FunctionType(
- fn.__code__, g, fn.__name__, fn.__defaults__, fn.__closure__
- )
- real.__kwdefaults__ = fn.__kwdefaults__
- real.__doc__ = fn.__doc__
- real.__dict__.update(fn.__dict__)
+ real = rebind(fn, g)
if getattr(fn, "_hermes_profile_scoped", False):
real = server._profile_scoped(real)
server._methods[name] = real
+
+
+_PLUMBING = {"HandlerRegistry", "method", "_profile_scoped", "register", "rebind", "logger"}
+
+
+def bind_module(module, server, *, skip=()) -> None:
+ """Publish everything ``module`` defines onto ``server``, rebound to its globals.
+
+ Functions are rebound; classes get their methods rebound in place; other
+ values (constants, ``global``-mutated state seeds) are copied as-is.
+ Imported modules/functions, dunders and registry plumbing are skipped, so a
+ split module needs no hand-maintained export list. Finally the module's
+ ``_registry`` (if any) installs its @method handlers.
+ """
+ g = vars(server)
+ for name, obj in list(vars(module).items()):
+ if name.startswith("__") or name in _PLUMBING or name in skip:
+ continue
+ if isinstance(obj, (types.ModuleType, HandlerRegistry)):
+ continue
+ if isinstance(obj, types.FunctionType):
+ if obj.__module__ != module.__name__:
+ continue
+ obj = rebind(obj, g)
+ elif isinstance(obj, type):
+ if obj.__module__ != module.__name__:
+ continue
+ for attr, val in list(vars(obj).items()):
+ if isinstance(val, types.FunctionType):
+ setattr(obj, attr, rebind(val, g))
+ elif isinstance(val, (staticmethod, classmethod)):
+ setattr(obj, attr, type(val)(rebind(val.__func__, g)))
+ setattr(server, name, obj)
+ registry = getattr(module, "_registry", None)
+ if isinstance(registry, HandlerRegistry):
+ registry.install(server)
diff --git a/tui_gateway/project_tree.py b/tui_gateway/project_tree.py
index 0b4310ddaa7..bee7e9d6d56 100644
--- a/tui_gateway/project_tree.py
+++ b/tui_gateway/project_tree.py
@@ -1,14 +1,11 @@
"""Authoritative project -> repo -> lane -> session tree builder.
-This is the single source of truth for how the desktop sidebar groups sessions
-into projects, repos, and lanes. It is pure (all git resolution is injected via
-``resolve``) so it can be unit-tested with fixtures and reused by the gateway's
+Single source of truth for how the desktop sidebar groups sessions. Pure (git
+resolution is injected via ``resolve``) so it is unit-testable and shared by the
``projects.tree`` / ``projects.project_sessions`` RPCs.
-It deliberately mirrors the desktop's former client-side grouping (the old
-``workspace-groups.ts``) so the emitted ids and lane keys stay byte-compatible
-with the renderer's persisted state (pins, manual ordering, dismissal), which
-all key off these exact strings:
+Emitted ids and lane keys must stay byte-compatible with the renderer's persisted
+state (pins, manual ordering, dismissal), which keys off these exact strings:
- explicit project id .......... ``p_<hex>`` (from projects.db)
- auto/discovered project id ... the repo root path
@@ -18,10 +15,9 @@ all key off these exact strings:
- kanban bucket lane id ........ ``<repoRoot>::kanban``
- linked worktree lane id ...... the worktree path
-The one correctness upgrade over the client version: linked worktrees are folded
-under their MAIN repo via a git common-dir probe (injected as ``resolve``),
-instead of being treated as separate repos (``git rev-parse --show-toplevel``
-returns the worktree's own root, which is why the client double-counted them).
+Linked worktrees are folded under their MAIN repo via a git common-dir probe
+(``git rev-parse --show-toplevel`` returns the worktree's own root, which is why
+the old client-side grouping double-counted them).
"""
from __future__ import annotations
@@ -29,46 +25,38 @@ from __future__ import annotations
import re
from typing import Any, Callable, Optional
-# A cwd -> git identity resolver. Returns ``{"repo_root", "worktree_root"}`` where
-# ``repo_root`` is the COMMON (main) repo root shared across worktrees and
-# ``worktree_root`` is this cwd's own checkout root. Returns ``None`` when the
-# cwd is not in a git repo (or cannot be probed, e.g. a remote backend).
+# cwd -> ``{"repo_root", "worktree_root"}``: ``repo_root`` is the COMMON (main)
+# repo root shared across worktrees, ``worktree_root`` this cwd's own checkout
+# root. ``None`` when not in a git repo or unprobeable (remote backend).
Resolve = Callable[[str], Optional[dict]]
-# A "does this directory still exist?" predicate, injected for the same reason
-# ``Resolve`` is: the builder stays pure and unit-testable. Defaults to assuming
-# everything exists, which preserves the previous behavior for callers that
-# can't stat (remote backends), where guessing "gone" would wrongly hide a
-# project that lives on the other host.
+# "does this directory still exist?" predicate. Defaults to True-for-everything
+# so callers that can't stat (remote backends) don't wrongly hide a project that
+# lives on the other host.
Exists = Callable[[str], bool]
-# Only KANBAN-TASK worktrees (`<repo>/.worktrees/t_<hex>`, the `t_…` id kanban_db
-# mints) collapse into one lane; user-named "New worktree" dirs under
-# `.worktrees/` stay as their own lanes.
+# Only KANBAN-TASK worktrees (`<repo>/.worktrees/t_<hex>`, the id kanban_db mints)
+# collapse into one lane; user-named dirs under `.worktrees/` stay their own lanes.
_KANBAN_DIR_RE = re.compile(r"^(.*[/\\]\.worktrees)[/\\]t_[0-9a-f]+[/\\]?$")
+_TRAILING_SEP_RE = re.compile(r"[/\\]+$")
_TRUNK_BRANCHES = {"main", "master", "trunk", "develop"}
DEFAULT_BRANCH_LABEL = "main"
-# The synthetic bucket holding every session no project claimed — a chat with no
-# cwd at all, or one whose folder can't be promoted (the bare home dir, HERMES
-# state, a workspace that has since been deleted). Without it those sessions are
-# invisible in the grouped view. The desktop labels it "Home"; the id/flag stay
-# named for what the bucket MEANS, since that's what membership keys off.
+# Synthetic bucket for every session no project claimed (no cwd, bare home dir,
+# HERMES state, deleted workspace). The desktop labels it "Home"; the id/flag
+# name what the bucket MEANS since membership keys off them.
NO_PROJECT_ID = "__no_project__"
NO_PROJECT_LABEL = "Home"
-# How many sibling candidates to try when recovering a deleted worktree's parent
-# repo (see ``_probe_sibling_worktree``). Each miss costs a git probe, so keep it
-# tight — real suffixes are one or two segments.
+# Sibling candidates tried when recovering a deleted worktree's parent repo
+# (``_probe_sibling_worktree``). Each miss costs a git probe; real suffixes are
+# one or two segments.
_MAX_SIBLING_PROBES = 4
def stamp_profile(projects: list[dict], profile: str) -> None:
- """Make every session row self-describing for cross-profile routing.
-
- A scoped project tree is built from one profile's state.db, so the request
- scope is authoritative even for legacy rows whose ``profile_name`` is NULL.
- """
+ """Stamp every session row with the request-scope profile (authoritative even
+ for legacy rows whose ``profile_name`` is NULL) for cross-profile routing."""
for project in projects:
for session in project.get("previewSessions") or []:
session["profile"] = profile
@@ -97,21 +85,17 @@ def _segments(path: str) -> list[str]:
def _is_windows_path(path: str) -> bool:
- value = (path or "").strip()
# Drive-letter (`C:\…`), UNC (`\\srv`, `//srv`), or any backslash-rooted path
- # — the root-relative `\wsl.localhost\…` / `\Users\…` spellings included. A
- # single leading `/` stays POSIX (case-sensitive).
+ # (`\wsl.localhost\…`, `\Users\…`). A single leading `/` stays POSIX.
+ value = (path or "").strip()
return bool(re.match(r"^[A-Za-z]:[/\\]", value)) or value.startswith(("\\", "//"))
def _comparison_segments(path: str) -> list[str]:
- """Path segments suitable for identity comparisons on any host.
-
- Windows paths remain case-insensitive even when tests or remote backends run
- on POSIX. Display paths and emitted IDs keep their original spelling.
- """
+ """Segments for identity comparison: Windows paths casefold (even when running
+ on POSIX); display paths and emitted IDs keep their spelling."""
segs = _segments(path)
- return [segment.casefold() for segment in segs] if _is_windows_path(path) else segs
+ return [s.casefold() for s in segs] if _is_windows_path(path) else segs
def _path_key(path: str) -> str:
@@ -120,11 +104,8 @@ def _path_key(path: str) -> str:
def _lane_key(path_or_lane: str) -> str:
- """Canonicalize only the path portion of a lane id.
-
- Branch labels remain byte-preserved; repo/worktree paths follow platform path
- identity so equivalent Windows spellings do not create duplicate lanes.
- """
+ """Canonicalize only the path portion of a lane id; branch labels stay
+ byte-preserved so equivalent Windows spellings don't fork lanes."""
for marker in ("::branch::", "::kanban"):
if marker in path_or_lane:
root, suffix = path_or_lane.split(marker, 1)
@@ -143,18 +124,31 @@ def kanban_worktree_dir(path: str) -> Optional[str]:
return m.group(1) if m else None
-def _is_path_under(folder: str, target: str) -> bool:
- """True when ``target`` equals ``folder`` or is nested under it (segment-wise)."""
- f = _comparison_segments(folder)
- t = _comparison_segments(target)
- if not f or len(f) > len(t):
- return False
- return all(f[i] == t[i] for i in range(len(f)))
+def _strip_trailing_sep(path: str) -> str:
+ return _TRAILING_SEP_RE.sub("", path or "")
def _with_base_name(path: str, name: str) -> str:
- stripped = re.sub(r"[/\\]+$", "", path)
- return re.sub(r"[^/\\]+$", name, stripped)
+ return re.sub(r"[^/\\]+$", name, _strip_trailing_sep(path))
+
+
+def _parent_dir(path: str) -> str:
+ """The containing directory of ``path`` (``""`` once the root is passed)."""
+ return _strip_trailing_sep(_with_base_name(path, ""))
+
+
+def _branch_label(branch: str) -> str:
+ # An unrecorded branch folds into the one trunk lane so a repo never shows two
+ # "main" lanes (recorded "main" + the empty-branch bucket).
+ return (branch or "").strip() or DEFAULT_BRANCH_LABEL
+
+
+def _session_time(session: dict) -> float:
+ return float(session.get("last_active") or session.get("started_at") or 0)
+
+
+def _last_active(sessions: list[dict]) -> float:
+ return max((_session_time(s) for s in sessions), default=0.0)
# ---------------------------------------------------------------------------
@@ -163,12 +157,7 @@ def _with_base_name(path: str, name: str) -> str:
def _placement(
- repo_root: str,
- lane_key: str,
- lane_label: str,
- lane_path: str,
- is_main: bool,
- is_kanban: bool,
+ repo_root: str, lane_key: str, lane_label: str, lane_path: str, is_main: bool, is_kanban: bool
) -> dict:
return {
"repo_key": repo_root,
@@ -182,31 +171,29 @@ def _placement(
}
-def _parent_dir(path: str) -> str:
- """The containing directory of ``path`` (``""`` once the root is passed)."""
- stripped = re.sub(r"[/\\]+$", "", path or "")
- return re.sub(r"[/\\]+$", "", re.sub(r"[^/\\]+$", "", stripped))
+def _trunk_placement(repo_root: str, branch: str) -> dict:
+ b = _branch_label(branch)
+ return _placement(repo_root, _branch_lane_id(repo_root, b), b, repo_root, True, False)
+
+
+def _kanban_placement(repo_root: str, kanban_dir: str) -> dict:
+ return _placement(repo_root, _kanban_lane_id(repo_root), "kanban", kanban_dir, False, True)
def _probe_sibling_worktree(cwd: str, resolve: Resolve) -> str:
"""The parent repo root of a deleted ``<repo>-<suffix>`` worktree, else ``""``.
- A deleted worktree dir can't be probed, so walk back up its name — trimming
- one ``-<segment>`` at a time — and return the first sibling that resolves.
-
- The session's cwd is frequently a SUBDIR of the deleted worktree (an agent
- that ``cd``-ed into ``<repo>-<suffix>/apps/desktop``), whose basename shares
- nothing with the repo. So the trim is applied to each ANCESTOR, deepest
- first, not just to the leaf — otherwise the probe silently no-ops and the
- dead path gets minted as its own top-level project. Probes are bounded in
- total (each costs a git invocation) and served from the shared probe cache.
+ A deleted dir can't be probed, so trim one ``-<segment>`` at a time off its
+ name and return the first sibling that resolves. The cwd is frequently a
+ SUBDIR of the deleted worktree (``<repo>-<suffix>/apps/desktop``) whose
+ basename shares nothing with the repo, so the trim is applied to each
+ ANCESTOR, deepest first — otherwise the dead path gets minted as its own
+ project. Probes are bounded in total (each is a git invocation).
"""
probes = 0
- path = re.sub(r"[/\\]+$", "", cwd or "")
-
+ path = _strip_trailing_sep(cwd)
while path and probes < _MAX_SIBLING_PROBES:
parts = base_name(path).split("-")
-
for i in range(len(parts) - 1, 0, -1):
if probes >= _MAX_SIBLING_PROBES:
break
@@ -214,9 +201,7 @@ def _probe_sibling_worktree(cwd: str, resolve: Resolve) -> str:
info = resolve(_with_base_name(path, "-".join(parts[:i])))
if info and info.get("repo_root"):
return (info["repo_root"] or "").strip()
-
path = _parent_dir(path)
-
return ""
@@ -225,61 +210,56 @@ def _place_by_heuristic(path: str) -> Optional[dict]:
base = base_name(path)
if not base:
return None
-
kanban_dir = kanban_worktree_dir(path)
if kanban_dir:
- repo_path = re.sub(r"[/\\]+$", "", _with_base_name(kanban_dir, ""))
- return _placement(repo_path, _kanban_lane_id(repo_path), "kanban", kanban_dir, False, True)
-
+ return _kanban_placement(_strip_trailing_sep(_with_base_name(kanban_dir, "")), kanban_dir)
m = re.match(r"^(.+)-wt-(.+)$", base)
if m:
- repo_path = _with_base_name(path, m.group(1))
- return _placement(repo_path, path, m.group(2), path, False, False)
-
+ return _placement(_with_base_name(path, m.group(1)), path, m.group(2), path, False, False)
return _placement(path, _branch_lane_id(path, DEFAULT_BRANCH_LABEL), base, path, True, False)
def _place(cwd: str, branch: str, resolve: Optional[Resolve], persisted_root: str) -> Optional[dict]:
info = resolve(cwd) if resolve else None
-
if info and info.get("repo_root") and info.get("worktree_root"):
- repo_root = info["repo_root"]
- worktree_root = info["worktree_root"]
- is_main = _path_key(worktree_root) == _path_key(repo_root) or bool(info.get("is_main"))
-
- if is_main:
- # Unrecorded branch folds into the one trunk lane, so a repo never
- # shows two "main" lanes (recorded "main" + the empty-branch bucket).
- b = (branch or "").strip() or DEFAULT_BRANCH_LABEL
- return _placement(repo_root, _branch_lane_id(repo_root, b), b, repo_root, True, False)
-
+ repo_root, worktree_root = info["repo_root"], info["worktree_root"]
+ if _path_key(worktree_root) == _path_key(repo_root) or info.get("is_main"):
+ return _trunk_placement(repo_root, branch)
kanban_dir = kanban_worktree_dir(worktree_root)
if kanban_dir:
- return _placement(repo_root, _kanban_lane_id(repo_root), "kanban", kanban_dir, False, True)
-
+ return _kanban_placement(repo_root, kanban_dir)
label = base_name(worktree_root) or worktree_root
return _placement(repo_root, worktree_root, label, worktree_root, False, False)
- # No live probe: trust the backend-persisted root (group by it, split main by
- # the session's recorded branch). Kanban tasks still collapse by path shape.
+ # No live probe: trust the backend-persisted root (split main by the recorded
+ # branch). Kanban tasks still collapse by path shape.
if persisted_root:
kanban_dir = kanban_worktree_dir(cwd)
if kanban_dir:
- return _placement(persisted_root, _kanban_lane_id(persisted_root), "kanban", kanban_dir, False, True)
- b = (branch or "").strip() or DEFAULT_BRANCH_LABEL
- return _placement(persisted_root, _branch_lane_id(persisted_root, b), b, persisted_root, True, False)
+ return _kanban_placement(persisted_root, kanban_dir)
+ return _trunk_placement(persisted_root, branch)
- # Unresolvable cwd: a deleted ``<repo>-<suffix>`` worktree still belongs to
- # its parent. It has no checkout to return to, so absorb it into the trunk
- # lane rather than stranding a dead-path lane in the project forever.
+ # Unresolvable cwd: a deleted ``<repo>-<suffix>`` worktree still belongs to its
+ # parent; absorb it into the trunk lane rather than stranding a dead-path lane.
sibling_root = _probe_sibling_worktree(cwd, resolve) if resolve else ""
if sibling_root:
- b = (branch or "").strip() or DEFAULT_BRANCH_LABEL
- return _placement(sibling_root, _branch_lane_id(sibling_root, b), b, sibling_root, True, False)
-
+ return _trunk_placement(sibling_root, branch)
return _place_by_heuristic(cwd)
+def _place_session(session: dict, resolve: Optional[Resolve]) -> Optional[dict]:
+ """``_place`` for a session row; ``None`` when it has no cwd."""
+ cwd = (session.get("cwd") or "").strip()
+ if not cwd:
+ return None
+ return _place(
+ cwd,
+ (session.get("git_branch") or "").strip(),
+ resolve,
+ (session.get("git_repo_root") or "").strip(),
+ )
+
+
def _session_repo_root(session: dict, resolve: Optional[Resolve]) -> str:
"""The COMMON repo root a session belongs to (folds linked worktrees)."""
cwd = (session.get("cwd") or "").strip()
@@ -299,20 +279,14 @@ def _lane_sort_key(group: dict) -> tuple:
# Trunk pins to the top; the kanban aggregate sinks to the bottom; the rest
# (branches + linked worktrees) sort by most-recent activity, then label.
is_trunk = bool(group.get("isMain")) and group["label"].lower() in _TRUNK_BRANCHES
- is_kanban = bool(group.get("isKanban"))
- activity = max((_session_time(s) for s in group.get("sessions") or []), default=0.0)
return (
0 if is_trunk else 1,
- 1 if is_kanban else 0,
- -activity,
+ 1 if group.get("isKanban") else 0,
+ -_last_active(group.get("sessions") or []),
group["label"].lower(),
)
-def _sort_lanes(groups: list[dict]) -> list[dict]:
- return sorted(groups, key=_lane_sort_key)
-
-
def _disambiguate_labels(items: list[dict]) -> None:
"""Grow colliding basenames into path-prefixed labels (in place)."""
by_label: dict[str, list[dict]] = {}
@@ -323,21 +297,17 @@ def _disambiguate_labels(items: list[dict]) -> None:
pathed = [g for g in bucket if g.get("path")]
if len(pathed) < 2:
continue
-
parents = {id(g): _segments(g["path"])[:-1] for g in pathed}
max_depth = max(len(p) for p in parents.values())
- depth = 1
- while depth <= max_depth:
+ for depth in range(1, max_depth + 1):
counts: dict[str, int] = {}
for g in pathed:
- segs = parents[id(g)]
- prefix = "/".join(segs[-depth:]) if depth else ""
+ prefix = "/".join(parents[id(g)][-depth:])
base = base_name(g["path"]) or g["path"]
g["label"] = f"{prefix}/{base}" if prefix else base
counts[g["label"]] = counts.get(g["label"], 0) + 1
if all(c == 1 for c in counts.values()):
break
- depth += 1
# ---------------------------------------------------------------------------
@@ -345,33 +315,21 @@ def _disambiguate_labels(items: list[dict]) -> None:
# ---------------------------------------------------------------------------
-def _session_time(session: dict) -> float:
- return float(session.get("last_active") or session.get("started_at") or 0)
+def _repo_node(root: str, label: str) -> dict:
+ return {"id": root, "label": label, "path": root, "groups": [], "sessionCount": 0}
def _build_repos(sessions: list[dict], resolve: Optional[Resolve], hydrate: bool) -> list[dict]:
"""Build the ``repo -> lane -> sessions`` subtree for a set of sessions."""
- lanes: dict[str, dict] = {} # lane_key -> {group, repo_key, repo_label, repo_path}
-
+ lanes: dict[str, tuple[dict, dict]] = {} # lane identity -> (group, placement)
for session in sessions:
- cwd = (session.get("cwd") or "").strip()
- if not cwd:
- continue
-
- placement = _place(
- cwd,
- (session.get("git_branch") or "").strip(),
- resolve,
- (session.get("git_repo_root") or "").strip(),
- )
+ placement = _place_session(session, resolve)
if not placement:
continue
-
lane_identity = _lane_key(placement["lane_key"])
- entry = lanes.get(lane_identity)
- if entry is None:
- entry = {
- "group": {
+ if lane_identity not in lanes:
+ lanes[lane_identity] = (
+ {
"id": placement["lane_key"],
"label": placement["lane_label"],
"path": placement["lane_path"],
@@ -379,43 +337,26 @@ def _build_repos(sessions: list[dict], resolve: Optional[Resolve], hydrate: bool
"isKanban": placement["is_kanban"],
"sessions": [],
},
- "repo_key": placement["repo_key"],
- "repo_label": placement["repo_label"],
- "repo_path": placement["repo_path"],
- }
- lanes[lane_identity] = entry
- entry["group"]["sessions"].append(session)
+ placement,
+ )
+ lanes[lane_identity][0]["sessions"].append(session)
repos: dict[str, dict] = {}
- for entry in lanes.values():
- group = entry["group"]
+ for group, placement in lanes.values():
group["sessions"].sort(key=_session_time, reverse=True)
- count = len(group["sessions"])
-
- repo_identity = _path_key(entry["repo_key"])
- repo = repos.get(repo_identity)
- if repo is None:
- repo = {
- "id": entry["repo_key"],
- "label": entry["repo_label"],
- "path": entry["repo_path"],
- "groups": [],
- "sessionCount": 0,
- }
- repos[repo_identity] = repo
+ repo = repos.setdefault(
+ _path_key(placement["repo_key"]),
+ _repo_node(placement["repo_key"], placement["repo_label"]),
+ )
repo["groups"].append(group)
- repo["sessionCount"] += count
+ repo["sessionCount"] += len(group["sessions"])
repo_list = list(repos.values())
for repo in repo_list:
- repo["groups"] = _sort_lanes(repo["groups"])
+ repo["groups"] = sorted(repo["groups"], key=_lane_sort_key)
_disambiguate_labels(repo["groups"])
- # Drop per-lane session rows only AFTER sorting: _lane_sort_key ranks
- # non-trunk lanes by most-recent activity, which it derives from the
- # session rows. Clearing them earlier makes every lane look inactive on
- # the overview (hydrate=False) path and collapses the sort to
- # alphabetical. Counts were already captured above, so the payload stays
- # slim without losing the recency order.
+ # Drop per-lane rows only AFTER sorting: _lane_sort_key derives recency
+ # from them. Counts were captured above, so the overview payload stays slim.
if not hydrate:
for group in repo["groups"]:
group["sessions"] = []
@@ -423,44 +364,29 @@ def _build_repos(sessions: list[dict], resolve: Optional[Resolve], hydrate: bool
return repo_list
-def _seed_folder_repos(
- repos: list[dict], folders: list[dict], resolve: Optional[Resolve]
-) -> list[dict]:
+def _seed_folder_repos(repos: list[dict], folders: list[dict], resolve: Optional[Resolve]) -> list[dict]:
"""Ensure every declared project folder shows as a repo, even with 0 sessions.
- A brand-new project (or any project whose sessions haven't loaded yet) has an
- empty session-derived ``repos`` list. That breaks two things on the desktop:
- the entered-project view renders blank (it early-returns on no repos), and the
- optimistic live-session overlay has no lane to drop a freshly-created session
- into — so a new session in the project only appears after a full tree refresh.
- Seeding each folder as an empty repo fixes both: the overlay matches a new
- session's cwd under the folder root, and the drill-in renders a real (if
- empty) project body. Folders already covered by a session-derived repo (same
- git root) are left untouched.
+ Without it the desktop's entered-project view renders blank (early-returns on
+ no repos) and the optimistic live-session overlay has no lane to drop a
+ fresh session into until a full tree refresh. Folders already covered by a
+ session-derived repo (same git root) are left untouched.
"""
- seen = {
- _path_key(value)
- for repo in repos
- for value in (repo.get("id"), repo.get("path"))
- if value
- }
+ seen = {_path_key(v) for repo in repos for v in (repo.get("id"), repo.get("path")) if v}
seeded = list(repos)
-
for folder in folders or []:
raw = (folder.get("path") or "").strip()
if not raw:
continue
info = resolve(raw) if resolve else None
- root = (info or {}).get("repo_root") or re.sub(r"[/\\]+$", "", raw)
+ root = (info or {}).get("repo_root") or _strip_trailing_sep(raw)
root_key = _path_key(root)
if not root_key or root_key in seen:
continue
- seeded.append({"id": root, "label": base_name(root) or root, "path": root, "groups": [], "sessionCount": 0})
+ seeded.append(_repo_node(root, base_name(root) or root))
seen.add(root_key)
-
if len(seeded) != len(repos):
_disambiguate_labels(seeded)
-
return seeded
@@ -470,11 +396,9 @@ def _seed_folder_repos(
class _FolderIndex:
- """Maps a normalized folder path → (owning project, depth), so a session is
- matched to its project by walking its cwd's ancestors (O(path depth) dict
- lookups) instead of scanning every project × folder per session — the
- difference between O(sessions × projects) and O(sessions) at power-user scale.
- """
+ """Normalized folder path -> (owning project, depth), so a session is matched
+ by walking its cwd's ancestors (O(path depth) lookups) instead of scanning
+ every project x folder per session."""
def __init__(self, projects: list[dict]) -> None:
self._by_path: dict[str, tuple[dict, int]] = {}
@@ -484,16 +408,14 @@ class _FolderIndex:
if not segs:
continue
key = "/".join(segs)
- depth = len(segs)
# Deepest folder wins; ties keep the first project (scan order).
existing = self._by_path.get(key)
- if existing is None or depth > existing[1]:
- self._by_path[key] = (project, depth)
+ if existing is None or len(segs) > existing[1]:
+ self._by_path[key] = (project, len(segs))
def match(self, target: str) -> tuple[Optional[dict], int]:
"""Owning project for ``target`` by longest ancestor folder, + its depth."""
segs = _comparison_segments(target or "")
- # Longest prefix first → deepest (most specific) folder wins.
for end in range(len(segs), 0, -1):
hit = self._by_path.get("/".join(segs[:end]))
if hit:
@@ -501,24 +423,17 @@ class _FolderIndex:
return None, -1
-def _project_for_path(index: _FolderIndex, target: str) -> Optional[dict]:
- return index.match(target)[0]
-
-
def _project_for_session(session: dict, index: _FolderIndex, resolve: Optional[Resolve]) -> Optional[dict]:
cwd = (session.get("cwd") or "").strip()
if not cwd:
return None
repo_root = _session_repo_root(session, resolve)
candidates = [cwd, repo_root] if repo_root and repo_root != cwd else [cwd]
-
- best: Optional[dict] = None
- best_len = -1
+ best, best_len = None, -1
for target in candidates:
match, length = index.match(target)
if match and length > best_len:
- best_len = length
- best = match
+ best, best_len = match, length
return best
@@ -530,9 +445,8 @@ def _project_for_session(session: dict, index: _FolderIndex, resolve: Optional[R
def _session_cost(session: dict) -> float:
"""A session's spend, billed if the provider reported it, else estimated."""
for key in ("actual_cost_usd", "estimated_cost_usd"):
- value = session.get(key)
- if value:
- return float(value)
+ if session.get(key):
+ return float(session[key])
return 0.0
@@ -561,9 +475,8 @@ def _project_node(
"isNoProject": is_no_project,
"sessionCount": session_count,
"lastActive": last_active,
- # Totals over the same sessions `sessionCount` counts, so a project's
- # header can add up what its rows show. The window the caller loaded is
- # the whole truth either way — count and totals can't disagree.
+ # Totals over the same sessions `sessionCount` counts, so a project header
+ # adds up to what its rows show.
"totalTokens": sum((s.get("input_tokens") or 0) + (s.get("output_tokens") or 0) for s in sessions or []),
"totalCostUsd": sum(_session_cost(s) for s in sessions or []),
"repos": repos,
@@ -586,22 +499,20 @@ def build_tree(
"""Build the authoritative project tree.
``projects`` are ``projects_db.Project.to_dict()`` shapes (non-archived).
- ``sessions`` are projected session-row dicts (must carry ``id``, ``cwd``,
- ``git_branch``, ``git_repo_root``, ``started_at``, ``last_active``).
- ``discovered_repos`` are ``{"root", "label", "sessions", "last_active"}``.
- ``is_junk_root`` flags git roots that must never become an AUTO project (the
- bare home dir, the HERMES_HOME subtree). ``is_junk_cwd`` is the narrower
- policy for non-git session folders: selected descendants may be intentional
- workspaces even when their parent tree contains Hermes state. User-created
- projects are honored regardless. ``exists`` reports whether a directory is
- still on disk, so a session whose workspace was DELETED (a removed worktree,
- a scratch dir under /tmp) doesn't get promoted to a phantom AUTO project;
- omit it (remote backends) to keep every candidate.
-
- Returns ``{"projects": [...], "scoped_session_ids": [...]}``. When
- ``hydrate`` is False (overview), lane ``sessions`` arrays are emptied but
- every count is preserved and each project carries up to ``preview_limit``
- ``previewSessions``. When True (drill-in), lanes carry full session rows.
+ ``sessions`` are projected session-row dicts (``id``, ``cwd``, ``git_branch``,
+ ``git_repo_root``, ``started_at``, ``last_active``). ``discovered_repos`` are
+ ``{"root", "label", "sessions", "last_active"}``. ``is_junk_root`` flags git
+ roots that must never become an AUTO project (bare home dir, HERMES_HOME);
+ ``is_junk_cwd`` is the narrower policy for non-git session folders (selected
+ descendants may be intentional workspaces). User-created projects are honored
+ regardless. ``exists`` keeps a DELETED workspace (removed worktree, /tmp
+ scratch) from being promoted to a phantom AUTO project; omit it (remote
+ backends) to keep every candidate.
+
+ Returns ``{"projects": [...], "scoped_session_ids": [...]}``. With
+ ``hydrate`` False (overview) lane ``sessions`` are emptied but counts are
+ preserved and each project carries up to ``preview_limit`` ``previewSessions``;
+ True (drill-in) keeps full session rows.
"""
active_projects = [p for p in projects if not p.get("archived")]
_junk = is_junk_root or (lambda _root: False)
@@ -619,25 +530,20 @@ def build_tree(
unowned.append(session)
scoped_ids: list[str] = []
+ result: list[dict] = []
def _previews(project_sessions: list[dict]) -> list[dict]:
if preview_limit <= 0:
return []
- ordered = sorted(project_sessions, key=_session_time, reverse=True)
- return ordered[:preview_limit]
+ return sorted(project_sessions, key=_session_time, reverse=True)[:preview_limit]
- def _last_active(project_sessions: list[dict]) -> float:
- return max((_session_time(s) for s in project_sessions), default=0.0)
-
- result: list[dict] = []
+ def _scope(project_sessions: list[dict]) -> None:
+ scoped_ids.extend(s["id"] for s in project_sessions if s.get("id"))
# Tier 1: explicit, user-created projects (always shown, even with 0 sessions).
for project in active_projects:
psessions = by_project.get(project["id"], [])
- scoped_ids.extend(s["id"] for s in psessions if s.get("id"))
- repos = _seed_folder_repos(
- _build_repos(psessions, resolve, hydrate), project.get("folders") or [], resolve
- )
+ _scope(psessions)
result.append(
_project_node(
pid=project["id"],
@@ -645,7 +551,7 @@ def build_tree(
path=project.get("primary_path"),
color=project.get("color"),
icon=project.get("icon"),
- repos=repos,
+ repos=_seed_folder_repos(_build_repos(psessions, resolve, hydrate), project.get("folders") or [], resolve),
session_count=len(psessions),
last_active=_last_active(psessions),
preview_sessions=_previews(psessions),
@@ -654,50 +560,38 @@ def build_tree(
)
# Tier 2: auto projects from leftover sessions. Prefer the common git repo
- # root, then fall back to the session cwd for historical/non-git workspaces.
- # The pre-Projects desktop grouped every non-empty cwd; keeping that fallback
- # prevents upgrades from flattening those sessions into Recents.
+ # root, then fall back to the session cwd for historical/non-git workspaces
+ # (the pre-Projects desktop grouped every non-empty cwd; dropping that would
+ # flatten those sessions into Recents on upgrade).
by_auto_root: dict[str, dict] = {}
- # Every session no tier could place. These are the Home bucket's rows.
- homeless: list[dict] = []
+ homeless: list[dict] = [] # every session no tier could place -> Home bucket
def _add_auto(root: str, session: dict) -> None:
key = _path_key(root)
if not key:
homeless.append(session)
return
- bucket = by_auto_root.setdefault(key, {"root": root, "sessions": []})
- bucket["sessions"].append(session)
+ by_auto_root.setdefault(key, {"root": root, "sessions": []})["sessions"].append(session)
for session in unowned:
root = _session_repo_root(session, resolve)
if root:
- # A real git root uses the stricter repo policy. Do not reinterpret a
- # filtered internal repo as a cwd-only project. A root that no longer
- # exists is a stale persisted value (the repo was deleted after the
- # session ran) and must not resurrect as a project.
+ # A real git root uses the stricter repo policy; never reinterpret a
+ # filtered internal repo as a cwd-only project. A root no longer on
+ # disk is a stale persisted value and must not resurrect as a project.
if not _junk(root) and _exists(root):
_add_auto(root, session)
else:
homeless.append(session)
continue
-
cwd = (session.get("cwd") or "").strip()
if not cwd or _junk_cwd(cwd):
homeless.append(session)
continue
- placement = _place(
- cwd,
- (session.get("git_branch") or "").strip(),
- resolve,
- (session.get("git_repo_root") or "").strip(),
- )
- # A placement that only echoes back the unresolvable cwd is the
- # path-only heuristic guessing — it never found a repo. When that dir is
- # also gone from disk (a deleted worktree whose name shares no prefix
- # with its parent, a removed /tmp scratch dir), promoting it mints a
- # phantom project that can never be opened and can only be dismissed by
- # hand. The session goes to Home instead.
+ placement = _place_session(session, resolve)
+ # A placement that only echoes back an unresolvable cwd is the path-only
+ # heuristic guessing. If that dir is also gone from disk, promoting it
+ # mints a phantom project that can only be dismissed by hand -> Home.
if placement and _exists(placement["repo_key"]):
_add_auto(placement["repo_key"], session)
else:
@@ -705,23 +599,17 @@ def build_tree(
seen: set[str] = set()
for bucket in by_auto_root.values():
- auto_root = bucket["root"]
- auto_sessions = bucket["sessions"]
+ auto_root, auto_sessions = bucket["root"], bucket["sessions"]
auto_key = _path_key(auto_root)
repos = _build_repos(auto_sessions, resolve, hydrate)
repo_node = next(
- (
- repo
- for repo in repos
- if _path_key(repo.get("id") or repo.get("path") or "") == auto_key
- ),
- None,
+ (r for r in repos if _path_key(r.get("id") or r.get("path") or "") == auto_key), None
)
if repo_node is None:
homeless.extend(auto_sessions)
continue
seen.add(auto_key)
- scoped_ids.extend(s["id"] for s in auto_sessions if s.get("id"))
+ _scope(auto_sessions)
result.append(
_project_node(
pid=auto_root,
@@ -745,7 +633,7 @@ def build_tree(
info = resolve(raw_root) if resolve else None
root = (info or {}).get("repo_root") or raw_root
root_key = _path_key(root)
- if root_key in seen or _junk(root) or _project_for_path(folder_index, root):
+ if root_key in seen or _junk(root) or folder_index.match(root)[0]:
continue
seen.add(root_key)
label = repo.get("label") or base_name(root) or root
@@ -754,7 +642,7 @@ def build_tree(
pid=root,
label=label,
path=root,
- repos=[{"id": root, "label": label, "path": root, "groups": [], "sessionCount": 0}],
+ repos=[_repo_node(root, label)],
session_count=int(repo.get("sessions") or 0),
last_active=float(repo.get("last_active") or 0),
preview_sessions=[],
@@ -762,18 +650,16 @@ def build_tree(
)
)
- # Auto projects are labelled by repo basename, which can collide (two "app"
- # repos in different parents). Grow path prefixes so each is distinct.
- # Explicit projects keep their user-chosen names untouched.
+ # Auto projects are labelled by repo basename, which can collide; grow path
+ # prefixes so each is distinct. Explicit projects keep their user-chosen names.
_disambiguate_labels([p for p in result if p.get("isAuto")])
- # Tier 0: everything the tiers above could not place, so the grouped view
- # loses no session. It has no folder, hence no repo/lane structure — the one
- # synthetic lane exists purely to carry the rows in the tree's shape. Leads
- # the list; omitted entirely when empty, so a project-less install is blank.
+ # Tier 0: everything above could not place, so the grouped view loses no
+ # session. No folder => no repo/lane structure; the one synthetic lane just
+ # carries the rows. Leads the list; omitted entirely when empty.
if homeless:
homeless.sort(key=_session_time, reverse=True)
- scoped_ids.extend(s["id"] for s in homeless if s.get("id"))
+ _scope(homeless)
lane = {
"id": NO_PROJECT_ID,
"label": NO_PROJECT_LABEL,
@@ -782,21 +668,20 @@ def build_tree(
"isKanban": False,
"sessions": homeless if hydrate else [],
}
+ home_repo = {
+ "id": NO_PROJECT_ID,
+ "label": NO_PROJECT_LABEL,
+ "path": None,
+ "groups": [lane],
+ "sessionCount": len(homeless),
+ }
result.insert(
0,
_project_node(
pid=NO_PROJECT_ID,
label=NO_PROJECT_LABEL,
path=None,
- repos=[
- {
- "id": NO_PROJECT_ID,
- "label": NO_PROJECT_LABEL,
- "path": None,
- "groups": [lane],
- "sessionCount": len(homeless),
- }
- ],
+ repos=[home_repo],
session_count=len(homeless),
last_active=_last_active(homeless),
preview_sessions=_previews(homeless),
diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.py
index 7066a62f434..7e55e22949a 100644
--- a/tui_gateway/slash_worker.py
+++ b/tui_gateway/slash_worker.py
@@ -6,12 +6,9 @@ Protocol: reads JSON lines from stdin {id, command}, writes {id, ok, output|erro
# Stop a ``utils/`` (or ``proxy/``, ``ui/``) package in the launch directory
# from shadowing Hermes's own top-level modules. This worker is spawned as
# ``-m tui_gateway.slash_worker`` and inherits the user's CWD, so the ``import
-# cli`` below would otherwise resolve ``utils`` to a colliding local package
-# and crash the child in a retry loop (issue #51286). ``hermes_bootstrap``
-# lives at the repo root, so importing it is safe before the guard runs (its
-# name won't collide with a user package), and it owns the canonical
-# path-hardening logic shared with the other entry points — #51693 added the
-# guard to ``entry.py``/``acp_adapter/entry.py`` but missed this child.
+# cli`` below would otherwise resolve ``utils`` to a colliding local package and
+# crash the child in a retry loop. ``hermes_bootstrap`` lives at the repo root
+# (no collision risk), so importing it before the guard runs is safe.
import hermes_bootstrap
hermes_bootstrap.harden_import_path()
@@ -28,26 +25,13 @@ import time
import cli as cli_mod
from cli import HermesCLI
+from tui_gateway._env import env_float
from tui_gateway._stdin_recovery import handle_spurious_eof
from rich.console import Console
# Env-overridable so the integration test can drive sub-second timing.
-def _env_float(name: str, default: float) -> float:
- """Parse a float env knob, falling back to ``default`` on absent/malformed
- values. A bare ``float(os.environ.get(...))`` would raise ValueError at
- import time on a typo (e.g. ``HERMES_SLASH_WATCHDOG_POLL_S=2s``) and kill
- the worker before it can serve a single command."""
- raw = os.environ.get(name)
- if not raw:
- return default
- try:
- return float(raw)
- except (TypeError, ValueError):
- return default
-
-
-_WATCHDOG_POLL_S = max(0.05, _env_float("HERMES_SLASH_WATCHDOG_POLL_S", 2.0))
-_ORPHAN_GRACE_S = max(0.0, _env_float("HERMES_SLASH_WATCHDOG_GRACE_S", 5.0))
+_WATCHDOG_POLL_S = max(0.05, env_float("HERMES_SLASH_WATCHDOG_POLL_S", 2.0))
+_ORPHAN_GRACE_S = max(0.0, env_float("HERMES_SLASH_WATCHDOG_GRACE_S", 5.0))
_in_flight = threading.Event() # set while a command is executing
logger = logging.getLogger(__name__)
@@ -61,20 +45,11 @@ def _prepare_slash_worker_runtime() -> None:
"""Start bounded MCP discovery before HermesCLI snapshots tools.
Each slash_worker child is its own process — the parent ``hermes serve``
- discovery thread does not populate this registry (issue #61891).
+ discovery thread does not populate this registry.
"""
- import logging
-
- from hermes_cli.mcp_startup import (
- start_background_mcp_discovery,
- wait_for_mcp_discovery,
- )
-
- logger = logging.getLogger(__name__)
- start_background_mcp_discovery(
- logger=logger,
- thread_name="slash-worker-mcp-discovery",
- )
+ from hermes_cli.mcp_startup import start_background_mcp_discovery, wait_for_mcp_discovery
+
+ start_background_mcp_discovery(logger=logger, thread_name="slash-worker-mcp-discovery")
wait_for_mcp_discovery()
@@ -99,9 +74,8 @@ def _run(cli: HermesCLI, command: str) -> str:
buf = io.StringIO()
- # Rich Console captures its file handle at construction time, so
- # contextlib.redirect_stdout won't affect it. Swap the console's
- # underlying file to our buffer so self.console.print() is captured.
+ # Rich Console captures its file handle at construction, so redirect_stdout
+ # won't affect it; swap the console's file so self.console.print() is captured.
cli.console = Console(file=buf, force_terminal=True, width=120)
old = getattr(cli_mod, "_cprint", None)
@@ -115,11 +89,9 @@ def _run(cli: HermesCLI, command: str) -> str:
if old is not None:
cli_mod._cprint = old
- # Desktop chat bubbles render plain text, not ANSI. A worker-routed command
- # that emits Rich color (e.g. /journey building its own Console, which picks
- # up truecolor from the gateway's inherited COLORTERM) would otherwise leak
- # raw escapes; strip them at the single choke point. (The TUI opens /journey
- # as an overlay, so it never travels this path.)
+ # Desktop chat bubbles render plain text, not ANSI. A command that emits
+ # Rich color (e.g. /journey building its own Console under the gateway's
+ # inherited COLORTERM) would leak raw escapes; strip at this single choke point.
from tools.ansi_strip import strip_ansi
return strip_ansi(buf.getvalue().rstrip())
@@ -136,16 +108,14 @@ def main():
# Start before the (hundreds-of-ms) HermesCLI build — that window is itself
# an orphan risk if the gateway dies mid-spawn.
- orig_ppid = os.getppid()
- _start_parent_death_watchdog(orig_ppid)
+ _start_parent_death_watchdog(os.getppid())
_prepare_slash_worker_runtime()
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
cli = HermesCLI(model=args.model or None, compact=True, resume=args.session_key, verbose=False)
- # Spurious stdin-EOF recovery (same O_NONBLOCK shared file-description
- # issue as the gateway entry point — any child inheriting fd 0 can flip
- # the flag and launder EAGAIN into an apparent EOF).
+ # Spurious stdin-EOF recovery (same shared-file-description O_NONBLOCK issue
+ # as the gateway entry point — any child inheriting fd 0 can flip the flag).
_sw_recovery_times: list[float] = []
def _sw_log(reason: str) -> None:
@@ -175,21 +145,16 @@ def main():
sys.stdout.flush()
finally:
_in_flight.clear()
- # Workers persist for the TUI session, so release allocator pages at
- # the same command boundary as other long-lived gateway processes.
- # trim_memory's shared cooldown coalesces this with nearby activity.
+ # Workers persist for the TUI session: release allocator pages at the
+ # command boundary like other long-lived gateway processes
+ # (trim_memory's shared cooldown coalesces nearby activity).
try:
from hermes_cli.mem_trim import trim_memory
trim_memory(reason="slash worker command completion")
except Exception as exc:
- # debug, not warning — a persistent failure would repeat on
- # every slash command forever.
- logger.debug(
- "slash worker memory trim failed: %s: %s",
- type(exc).__name__,
- exc,
- )
+ # debug, not warning — a persistent failure would repeat every command.
+ logger.debug("slash worker memory trim failed: %s: %s", type(exc).__name__, exc)
if __name__ == "__main__":
diff --git a/tui_gateway/synthetic_turn.py b/tui_gateway/synthetic_turn.py
index 17a8a913f85..a1df1965a5e 100644
--- a/tui_gateway/synthetic_turn.py
+++ b/tui_gateway/synthetic_turn.py
@@ -1,31 +1,22 @@
"""Synthetic GIL-heavy turn driver for the AC-4 isolation certify harness.
-Mechanism B (the class ``docs/desktop/2026-07-04-dashboard-process-isolation-PRD.md``
-targets) is interpreter-wide GIL starvation: concurrent heavy agent turns run
-compute in threads of the SERVING process, and CPython's single GIL lets those
-threads starve the event loop that flushes WebSocket frames for MINUTES. A
-2026-07-04 ``sample`` showed the loop thread parked in ``take_gil`` while worker
-threads burned the interpreter — NOT blocked on I/O.
-
-To certify the fix (AC-4) without spending real tokens on 6 concurrent 100K+
-context model calls, the harness needs a turn driver that reproduces THAT
-regime: sustained pure-Python CPU that holds the GIL for the turn's duration.
-A network/sleep stub is WRONG here — it would release the GIL during I/O and
-never reproduce ``take_gil`` contention, so a dry-run green off it is a fake
-green (the spec says so explicitly).
-
-This module is a **test seam**: it is dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN``
-is set. When armed, ``tui_gateway.server._make_agent`` returns a
-:class:`SyntheticHeavyAgent` instead of a real ``AIAgent``. Because both the
-in-process ``_pool`` path (isolation OFF) and the compute-host child path
-(isolation ON) build their agent through ``_make_agent``, the SAME synthetic
-turn exercises whichever dispatch path is under test — the isolation boundary
-is the only variable between an OFF run and an ON run.
-
-The per-turn intensity (wall duration, CPU chunk size, streamed-delta cadence,
-token accounting) is carried in the prompt text as a small JSON spec so the
-harness has full control and the server seam stays dumb. Any prompt that is not
-a JSON object falls back to env / built-in defaults.
+The regime under test is interpreter-wide GIL starvation: concurrent heavy agent
+turns run compute in threads of the SERVING process and starve the event loop
+that flushes WebSocket frames (loop thread parked in ``take_gil`` — NOT blocked
+on I/O). To certify the isolation fix without spending real tokens, the turn
+driver must reproduce THAT: sustained pure-Python CPU holding the GIL for the
+turn's duration. A network/sleep stub is WRONG — it releases the GIL during I/O
+and never reproduces ``take_gil`` contention, so a green off it is fake.
+
+This module is a **test seam**: dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN=1``.
+When armed, ``tui_gateway.server._make_agent`` returns a
+:class:`SyntheticHeavyAgent` instead of a real ``AIAgent``. Both the in-process
+``_pool`` path (isolation OFF) and the compute-host child path (isolation ON)
+build through ``_make_agent``, so the isolation boundary is the only variable.
+
+Per-turn intensity (wall duration, CPU chunk size, delta cadence, token
+accounting) rides in the prompt text as a JSON object; any other prompt falls
+back to env / built-in defaults.
"""
from __future__ import annotations
@@ -36,35 +27,21 @@ import threading
import time
from typing import Any, Callable, Optional
+from tui_gateway._env import env_float as _env_float, env_int as _env_int
+
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"
-def _env_float(name: str, default: float) -> float:
- try:
- return float(os.environ.get(name, "") or default)
- except (TypeError, ValueError):
- return default
-
-
-def _env_int(name: str, default: int) -> int:
- try:
- return int(os.environ.get(name, "") or default)
- except (TypeError, ValueError):
- return default
-
-
class SyntheticHeavyAgent:
"""An AIAgent-shaped object whose turn is a GIL-holding CPU burn.
Presents only the surface ``tui_gateway.server``'s turn path and status
- helpers read: ``run_conversation``/``interrupt``/``clear_interrupt`` plus a
- handful of ``model``/``provider``/``session_*`` attributes consumed by
- ``_get_usage`` and ``_session_info``. It never opens a socket or spawns a
- subprocess, so the only work it does is the deterministic Python loop below —
- exactly the ``take_gil`` regime under test.
+ helpers read (``run_conversation``/``interrupt``/``clear_interrupt`` plus the
+ ``model``/``provider``/``session_*`` attributes consumed by ``_get_usage`` and
+ ``_session_info``). Never opens a socket or spawns a subprocess.
"""
def __init__(self, session_id: str, *, model: str = "synthetic-heavy") -> None:
@@ -106,39 +83,31 @@ class SyntheticHeavyAgent:
"""No-op teardown (session lifecycle calls agent.close() on some paths)."""
self._interrupt.set()
- # ── spec parsing ───────────────────────────────────────────────────
@staticmethod
def _parse_spec(message: Any) -> dict[str, Any]:
spec: dict[str, Any] = {}
- if isinstance(message, str):
- text = message.strip()
- if text.startswith("{"):
- try:
- parsed = json.loads(text)
- if isinstance(parsed, dict):
- spec = parsed
- except (ValueError, TypeError):
- spec = {}
+ if isinstance(message, str) and message.strip().startswith("{"):
+ try:
+ parsed = json.loads(message.strip())
+ except (ValueError, TypeError):
+ parsed = None
+ if isinstance(parsed, dict):
+ spec = parsed
return {
- # Primary control: wall-clock seconds of GIL-holding compute.
+ # 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 integer ops per interrupt-check chunk. Small enough
- # that an interrupt is honored within a few ms; large enough that
- # the loop stays hot on the GIL between checks.
+ # 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 (seconds). Each delta is a loop wakeup that
- # marshals a frame across the transport — the serving-path pressure.
+ # 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 attributed per streamed delta (drives the
- # 100K+-token "heavy turn" proxy in usage/metadata).
+ # 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 to model a lighter/mixed regime (0 = pure
- # burn). --dry-run uses a short duration, NOT a sleep, so the smoke
- # path still exercises the real dispatch seam.
+ # 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)),
}
- # ── the turn ───────────────────────────────────────────────────────
def run_conversation(
self,
message: Any,
@@ -156,10 +125,8 @@ class SyntheticHeavyAgent:
sleep_s = max(0.0, spec["sleep_s"])
base_history = list(conversation_history if conversation_history is not None else self.history)
- start = time.monotonic()
- last_delta = start
- acc = 0
- deltas = 0
+ start = last_delta = time.monotonic()
+ acc = deltas = 0
interrupted = False
while True:
@@ -169,9 +136,8 @@ class SyntheticHeavyAgent:
now = time.monotonic()
if now - start >= duration:
break
- # GIL-holding pure-Python work. A tight integer loop runs one
- # bytecode step per iteration and NEVER releases the GIL — this is
- # the exact interpreter contention that starves the serving loop.
+ # A tight integer loop never releases the GIL — the exact contention
+ # that starves the serving loop.
for _ in range(chunk):
acc = (acc * 1_000_003 + 12_345) & 0xFFFFFFFFFFFFFFFF
if sleep_s:
@@ -186,8 +152,8 @@ class SyntheticHeavyAgent:
last_delta = now
self.session_api_calls += 1
- # Fold the checksum into the reply so the loop is not dead-code-eliminated
- # and the turn produces a deterministic, inspectable result.
+ # Fold the checksum into the reply so the loop can't be eliminated and
+ # the turn is deterministic and inspectable.
final = (
f"[synthetic heavy turn] deltas={deltas} "
f"out_tokens={self.session_output_tokens} "
@@ -211,8 +177,8 @@ class SyntheticHeavyAgent:
def maybe_build_synthetic_agent(session_id: str, model_override: Any = None) -> SyntheticHeavyAgent | None:
"""Return a :class:`SyntheticHeavyAgent` when the seam is armed, else ``None``.
- ``model_override`` (dict or str) only influences the reported ``model`` label
- so status frames look plausible; it never changes the compute.
+ ``model_override`` (dict or str) only influences the reported ``model`` label;
+ it never changes the compute.
"""
if not synth_turn_armed():
return None
diff --git a/tui_gateway/turn_marker.py b/tui_gateway/turn_marker.py
index 933f384f37d..dfb58e4f8c6 100644
--- a/tui_gateway/turn_marker.py
+++ b/tui_gateway/turn_marker.py
@@ -1,21 +1,19 @@
"""Durable interrupted-turn markers for the desktop/TUI auto-continue path.
A running turn's progress lives only in process memory (the agent flushes to
-SQLite at turn end, not mid-turn), so an app/backend/machine death mid-turn
-leaves no durable trace of the interrupted prompt. This sidecar is that
-trace: a marker is written when a turn starts running and cleared when the
-turn concludes — success, handled error, or interrupt all clear it, so only
-a process death leaves one behind. ``session.resume`` reads the marker to
-decide whether to auto-continue the interrupted turn (see
-``_maybe_schedule_auto_continue`` in ``tui_gateway/server.py``).
-
-Markers are stored per ``HERMES_HOME`` (callers pass the session's home so
-profile sessions keep their state in their own profile directory) and the
-file is bounded: writes prune entries older than ``_MAX_AGE_SECS`` and cap
-the total count, so an unlucky streak of crashes can't grow it unboundedly.
-
-Every function is best-effort by design — marker bookkeeping must never
-break a turn — so I/O errors degrade to "no marker" instead of raising.
+SQLite at turn end), so an app/backend/machine death mid-turn leaves no durable
+trace of the interrupted prompt. A marker is written when a turn starts and
+cleared when it concludes — success, handled error, or interrupt all clear it —
+so only a process death leaves one behind. ``session.resume`` reads it to
+decide whether to auto-continue (``_maybe_schedule_auto_continue`` in
+``tui_gateway/server.py``).
+
+Markers are stored per ``HERMES_HOME`` (profile sessions keep state in their own
+profile dir) and the file is bounded: writes prune entries older than
+``_MAX_AGE_SECS`` and cap the count, so a crash streak can't grow it unboundedly.
+
+Every function is best-effort — marker bookkeeping must never break a turn — so
+I/O errors degrade to "no marker" instead of raising.
"""
from __future__ import annotations
@@ -35,8 +33,8 @@ _MARKER_DIR = "desktop"
_MARKER_FILE = "interrupted_turns.json"
_MAX_AGE_SECS = 24 * 3600
_MAX_ENTRIES = 32
-# Enough to re-submit any realistic prompt; guards the sidecar against a
-# pathological multi-megabyte paste being journaled on every turn.
+# Enough to re-submit any realistic prompt; guards against a multi-megabyte
+# paste being journaled on every turn.
_MAX_PROMPT_CHARS = 64_000
_lock = threading.Lock()
@@ -46,6 +44,10 @@ def _marker_path(home: Path | str) -> Path:
return Path(home) / _MARKER_DIR / _MARKER_FILE
+def _started_at(entry: dict) -> float:
+ return float(entry.get("started_at") or 0)
+
+
def _load(path: Path) -> dict[str, dict]:
try:
with open(path, encoding="utf-8") as f:
@@ -61,19 +63,11 @@ def _load(path: Path) -> dict[str, dict]:
def _prune(entries: dict[str, dict], now: float) -> dict[str, dict]:
- fresh = {
- key: entry
- for key, entry in entries.items()
- if now - float(entry.get("started_at") or 0) <= _MAX_AGE_SECS
- }
+ fresh = {k: e for k, e in entries.items() if now - _started_at(e) <= _MAX_AGE_SECS}
if len(fresh) <= _MAX_ENTRIES:
return fresh
- newest = sorted(
- fresh.items(),
- key=lambda item: float(item[1].get("started_at") or 0),
- reverse=True,
- )[:_MAX_ENTRIES]
- return dict(newest)
+ newest = sorted(fresh.items(), key=lambda item: _started_at(item[1]), reverse=True)
+ return dict(newest[:_MAX_ENTRIES])
def _store(path: Path, entries: dict[str, dict]) -> None:
@@ -152,7 +146,7 @@ def read_turn_marker(home: Path | str, session_key: str) -> dict[str, Any] | Non
if not prompt.strip():
return None
try:
- started_at = float(entry.get("started_at") or 0)
+ started_at = _started_at(entry)
attempts = max(0, int(entry.get("attempts") or 0))
except (TypeError, ValueError):
return None
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 145aa70b69a..215e501d485 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -1,20 +1,13 @@
"""WebSocket transport for the tui_gateway JSON-RPC server.
-Reuses :func:`tui_gateway.server.dispatch` verbatim so every RPC method, every
-slash command, every approval/clarify/sudo flow, and every agent event flows
-through the same handlers whether the client is Ink over stdio or an iOS /
-web client over WebSocket.
-
-Wire protocol
--------------
-Identical to stdio: newline-delimited JSON-RPC in both directions. The server
-emits a ``gateway.ready`` event immediately after connection accept, then
-echoes responses/events for inbound requests. No framing differences.
-
-Mounting
---------
- from fastapi import WebSocket
- from tui_gateway.ws import handle_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.
+
+Mounting::
@app.websocket("/api/ws")
async def ws(ws: WebSocket):
@@ -37,10 +30,10 @@ from tui_gateway.event_replay import replay_epoch
_log = logging.getLogger(__name__)
-# Scale-to-zero: tell the (separate) gateway process that 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 mtime write per 5s per process is
-# plenty and keeps the volume quiet. 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. Clients ping every 15s; one write per 5s per process is plenty.
+# See gateway/scale_to_zero.py.
_DASHBOARD_CLIENT_TOUCH_MIN_INTERVAL_S = 5.0
_dashboard_client_touched_at = 0.0
_dashboard_client_touch_lock = threading.Lock()
@@ -61,32 +54,23 @@ def _note_dashboard_client_activity(*, force: bool = False) -> None:
except Exception: # noqa: BLE001 - liveness garnish must never break the WS
_log.debug("dashboard client heartbeat touch failed", exc_info=True)
-# Max seconds a pool-dispatched handler will block waiting for the event loop
-# to flush a WS frame before we mark the transport dead. Protects handler
-# threads from a wedged socket.
+
+# 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 event loop once per token. A model reply
-# emits hundreds of these in a burst, and each one is a loop wakeup competing
-# with the agent turn for the GIL — coalescing cuts that churn (CF-2). The task
-# that introduced this called them "agent.token"/"agent.thinking"; in this
-# codebase the per-token frames are the ``*.delta`` stream events below. Keep
-# this set to genuinely high-frequency, display-only events — anything a client
-# must see promptly (tool/approval/status/completion frames) 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 before flush (~30 fps). Short
-# enough to stay imperceptible to the live token cadence.
+# 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
-# Keep starlette optional at import time; handle_ws uses the real class when
-# it's available and falls back to a generic Exception sentinel otherwise.
+# starlette stays optional at import time; fall back to a generic sentinel.
try:
from starlette.websockets import WebSocketDisconnect as _WebSocketDisconnect
except ImportError: # pragma: no cover - starlette is a required install path
@@ -96,17 +80,10 @@ except ImportError: # pragma: no cover - starlette is a required install path
class WSTransport:
"""Per-connection WS transport.
- ``write`` is safe to call from any thread *other than* the event loop
- thread that owns the socket. Pool workers (the only real caller) run in
- their own threads, so marshalling onto the loop via
- :func:`asyncio.run_coroutine_threadsafe` + ``future.result()`` is correct
- and deadlock-free there.
-
- When called from the loop thread itself (e.g. by ``handle_ws`` for an
- inline response) the same call would deadlock: we'd schedule work onto
- the loop we're currently blocking. We detect that case and fire-and-
- forget instead. Callers that need to know when the bytes are on the wire
- should use :meth:`write_async` from the loop thread.
+ ``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``.
"""
def __init__(
@@ -120,91 +97,60 @@ class WSTransport:
self._ws = ws
self._loop = loop
self._peer = peer
- #: Server-verified identity carried from the WS-upgrade credential
- #: (dashboard ticket / internal credential) — stamped by
- #: ``hermes_cli.web_server._ws_auth_reason`` onto the WS object and
- #: passed through ``handle_ws``. None for transports that
- #: authenticated via the legacy token path or stdio. 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
- self._last_inbound_at = time.monotonic()
- # Token-coalescing buffer (CF-2). Streamed token frames land here and a
- # short timer flushes the batch. The lock guards the buffer + the
- # "armed" flag against the worker threads that call 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
- # Buffer mutation is protected by the thread lock above; actual socket
- # writes need an async boundary because several batches can be queued on
+ # 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()
- @property
- def closed(self) -> bool:
- return self._closed
-
- @property
- def last_inbound_at(self) -> float:
- return self._last_inbound_at
-
- def mark_inbound(self) -> None:
- self._last_inbound_at = time.monotonic()
-
@staticmethod
def _is_streaming_frame(obj: dict) -> bool:
- """True for high-frequency per-token frames eligible for coalescing."""
params = obj.get("params") if isinstance(obj, dict) else None
- if not isinstance(params, dict):
- return False
- return params.get("type") in _STREAMING_EVENT_TYPES
+ return isinstance(params, dict) and params.get("type") in _STREAMING_EVENT_TYPES
def write(self, obj: dict) -> bool:
if self._closed:
return False
-
line = json.dumps(obj, ensure_ascii=False)
-
try:
on_loop = asyncio.get_running_loop() is self._loop
except RuntimeError:
on_loop = False
- # Coalesce streamed token frames: buffer this frame and arm a short
- # flush timer instead of waking the loop right now. Cheap and
- # non-blocking — the worker returns immediately. Ordering is preserved
- # because every non-streaming frame (below) drains the buffer ahead of
- # itself.
+ # 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)
if not self._token_flush_armed:
self._token_flush_armed = True
- # call_soon_threadsafe arms the call_later timer on the loop
- # thread and is safe to call from a worker or the loop.
self._loop.call_soon_threadsafe(self._arm_token_flush)
return not self._closed
- # Non-streaming frame (RPC response, control frame, non-token event):
- # append it behind any buffered tokens and flush the whole batch NOW so
- # it can never overtake the tokens that preceded it. The send is
- # scheduled INSIDE the lock so the on-the-wire order matches the 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:
self._pending_tokens.append(line)
- batch = self._pending_tokens
- self._pending_tokens = []
+ batch, self._pending_tokens = self._pending_tokens, []
if on_loop:
- # Fire-and-forget — don't block the loop waiting on itself.
self._loop.create_task(self._safe_send_many(batch))
return True
- fut = safe_schedule_threadsafe(
- self._safe_send_many(batch), self._loop
- )
+ fut = safe_schedule_threadsafe(self._safe_send_many(batch), self._loop)
if fut is None:
self._closed = True
return False
@@ -213,13 +159,10 @@ class WSTransport:
fut.result(timeout=_WS_WRITE_TIMEOUT_S)
return not self._closed
except concurrent.futures.TimeoutError: # builtin TimeoutError on 3.11+
- # The event loop is stalled (GIL-heavy agent turn, delegation
- # running N children), NOT the socket dead. The send coroutine is
- # already scheduled and will flush once the loop breathes — latching
- # _closed here permanently silenced live windows after one slow
- # write (the "subagent window shows zero streaming" bug). Unblock
- # the worker thread and keep the transport alive; _safe_send_many
- # latches on a real socket error when the frame actually fails.
+ # 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,
@@ -234,40 +177,28 @@ class WSTransport:
return False
def _arm_token_flush(self) -> None:
- """Arm the coalesce timer. Runs on the loop thread (call_soon_threadsafe)."""
+ """Arm the coalesce timer. Runs on the loop thread."""
if self._closed:
return
- self._token_flush_handle = self._loop.call_later(
- _TOKEN_COALESCE_S, self._flush_tokens
- )
+ self._token_flush_handle = self._loop.call_later(_TOKEN_COALESCE_S, self._flush_tokens)
def _flush_tokens(self) -> None:
- """Send buffered tokens as one batch. Runs on the loop thread (timer).
-
- The send is scheduled under the lock so its wire order is fixed relative
- to a concurrent non-streaming flush in :meth:`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
- if not self._pending_tokens or self._closed:
- self._pending_tokens = []
- return
- batch = self._pending_tokens
- self._pending_tokens = []
- self._loop.create_task(self._safe_send_many(batch))
+ batch, self._pending_tokens = self._pending_tokens, []
+ if batch and not self._closed:
+ self._loop.create_task(self._safe_send_many(batch))
async def write_async(self, obj: dict) -> bool:
- """Send from the owning event loop. Awaits until the frame is on the wire."""
+ """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
- # Flush any buffered streamed tokens ahead of this frame (RPC response /
- # control frame) as ONE serialized batch. Sending them in two lock
- # acquisitions would let a later batch slip between the pending tokens
- # and the frame that drained them.
with self._token_lock:
- batch = self._pending_tokens
- self._pending_tokens = []
+ batch, self._pending_tokens = self._pending_tokens, []
batch.append(json.dumps(obj, ensure_ascii=False))
await self._safe_send_many(batch)
return not self._closed
@@ -283,9 +214,8 @@ class WSTransport:
return
await self._ws.send_text(line)
except Exception as exc:
- # Latch while still holding the writer lock so queued batches
- # observe the failure before they get a chance to touch 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",
@@ -294,8 +224,7 @@ class WSTransport:
def close(self) -> None:
self._closed = True
- # Cancel any pending coalesce flush. close() runs on the loop thread
- # (the handle_ws finally), so touching the TimerHandle here is safe.
+ # Runs on the loop thread (handle_ws finally), so the TimerHandle is safe.
handle = self._token_flush_handle
if handle is not None:
handle.cancel()
@@ -303,7 +232,7 @@ class WSTransport:
def _ws_peer_label(ws: Any) -> str:
- """Return ``host:port`` when available, else a stable placeholder."""
+ """``host:port`` when available, else a stable placeholder."""
client = getattr(ws, "client", None)
if client is None:
return "unknown"
@@ -313,12 +242,13 @@ def _ws_peer_label(ws: Any) -> str:
def _disable_nagle(ws: Any) -> None:
- """Disable Nagle so streamed JSON-RPC frames go out individually.
+ """Disable Nagle + enable TCP keepalive on the raw socket (best-effort).
- Without it the kernel coalesces the small per-token frames, so a burst after
- the model's think-pause lands on the client in one tick and no client-side
- smoothing can recover the cadence. GUI/WS only; chat platforms don't hit
- this path. Best-effort — skip silently if the socket isn't reachable.
+ 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 {}
@@ -326,10 +256,6 @@ def _disable_nagle(ws: Any) -> None:
sock = transport.get_extra_info("socket") if transport is not None else None
if sock is not None:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
- # Dead-peer detection: without keepalive a silently-dropped client
- # (SSH tunnel reset, client sleep) leaves the TCP leg half-open
- # forever, receive_text() blocks indefinitely, and the disconnect
- # teardown (detach + orphan reap + resume replay) never runs.
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, "TCP_KEEPIDLE"): # Linux
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 30)
@@ -341,6 +267,10 @@ def _disable_nagle(ws: Any) -> None:
_log.debug("ws TCP_NODELAY skip: %s", exc)
+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,
*,
@@ -350,20 +280,25 @@ async def handle_ws(
"""Run one WebSocket session. Wire-compatible with ``tui_gateway.entry``.
*auth_identity* is the server-minted ``{user_id, provider}`` recorded at
- WS-upgrade authentication (``hermes_cli.web_server._ws_auth_reason``); it
- is stored on the transport as ``WSTransport.auth_identity`` and is the
- only identity authority for browser-controller registration. Existing
- callers (stdio-free harnesses, the embedded TUI child) omit it and get a
- ``None`` transport identity — unchanged behaviour.
+ 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
- messages = 0
- parse_errors = 0
- dispatch_crashes = 0
- send_failures = 0
+ messages = parse_errors = dispatch_crashes = send_failures = 0
disconnect_reason = "not_connected"
+ async def _reply(frame: dict, reason: str, msg: str, *args: Any) -> bool:
+ """write_async; on failure record *reason* and log *msg*. False => break."""
+ nonlocal disconnect_reason, send_failures
+ if await transport.write_async(frame):
+ return True
+ disconnect_reason = reason
+ send_failures += 1
+ _log.warning(msg, *args)
+ return False
+
try:
if subprotocol:
await ws.accept(subprotocol=subprotocol)
@@ -373,25 +308,13 @@ async def handle_ws(
# 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)
- # Push small streamed frames out immediately instead of letting Nagle
- # batch them — keeps the live token cadence intact for GUI clients.
_disable_nagle(ws)
_log.info("ws accepted peer=%s", peer)
- transport = WSTransport(
- ws,
- asyncio.get_running_loop(),
- peer=peer,
- auth_identity=auth_identity,
- )
+ transport = WSTransport(ws, asyncio.get_running_loop(), peer=peer, auth_identity=auth_identity)
- # resolve_skin() reads config + initializes the skin engine —
- # synchronous I/O + CPU work that should not block the event loop
- # during the cold-start window. Run it in the thread pool so the
- # WS read loop stays free to drain the frontend's initial RPC
- # burst (setup.status, session.list, ...) without a stall
- # (#60800). The skin payload is small (a dict of strings/arrays),
- # so the to_thread overhead is negligible.
+ # 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(
{
@@ -399,41 +322,32 @@ async def handle_ws(
"method": "event",
"params": {
"type": "gateway.ready",
- # change_events: this backend broadcasts pet.changed /
- # cron.changed / sessions.changed, so clients can demote
- # their legacy polls to slow backstops.
+ # 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,
- # Replay-contract process identity: lets reconnecting
- # clients detect a backend restart and reset their
- # per-session seq watermarks (see event_replay).
+ # Lets reconnecting clients detect a backend restart and
+ # reset their per-session seq watermarks (event_replay).
"replay_epoch": replay_epoch(),
},
},
}
)
if ready_ok:
- # Live-apply skins Hermes activates mid-conversation.
+ # 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()
- # Track this peer for session-less global broadcasts (skin.changed
- # from the background watcher) — write_json can't route those.
server.register_live_transport(transport)
- # Cross-backend liveness (#94895): register a heartbeat row so
- # the startup orphan sweep can distinguish "row owned by a live
- # but idle backend" from "row truly orphaned". The stdio TUI's
- # entry.main() does the same; idempotent + once-per-process so a
- # stdio TUI that already started the refresher is a no-op here.
+ # 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()).
try:
server._start_backend_heartbeat_refresher()
except Exception:
_log.warning("backend heartbeat refresher start failed", exc_info=True)
- # Same once-per-process startup pass for session rows orphaned by a
- # previous gateway process (#65194): the desktop app and web dashboard
- # reach the agent through this WS sidecar, not entry.main(). Idempotent
- # + config-gated inside, so a stdio TUI that already scheduled is a
- # no-op.
try:
server._schedule_startup_orphan_sweep()
except Exception:
@@ -463,7 +377,6 @@ async def handle_ws(
line = raw.strip()
if not line:
continue
- transport.mark_inbound()
messages += 1
try:
@@ -472,110 +385,65 @@ async def handle_ws(
parse_errors += 1
_log.warning(
"ws parse error peer=%s index=%d error=%s payload=%r",
- peer,
- messages,
- exc,
- line[:_WS_LOG_PAYLOAD_PREVIEW],
- )
- ok = await transport.write_async(
- {
- "jsonrpc": "2.0",
- "error": {"code": -32700, "message": "parse error"},
- "id": None,
- }
+ peer, messages, exc, line[:_WS_LOG_PAYLOAD_PREVIEW],
)
- if not ok:
- disconnect_reason = "send_failed_after_parse_error"
- send_failures += 1
- _log.warning("ws parse-error reply send failed peer=%s", peer)
+ if not await _reply(
+ _error_frame(-32700, "parse error", None),
+ "send_failed_after_parse_error",
+ "ws parse-error reply send failed peer=%s", peer,
+ ):
break
continue
- # dispatch() may schedule long handlers on the pool; it returns
- # None in that case and the worker writes the response itself via
- # the transport we pass in (a separate thread, so transport.write
- # is the safe path there). For inline handlers it returns the
- # response dict, which we write here from the loop.
req_id = req.get("id") if isinstance(req, dict) else None
req_method = req.get("method") if isinstance(req, dict) else None
if req_method == "gateway.ping":
- ok = await transport.write_async(
- {
- "jsonrpc": "2.0",
- "result": {"ok": True},
- "id": req_id,
- }
- )
- if not ok:
- disconnect_reason = "send_failed_after_heartbeat"
- send_failures += 1
- _log.warning("ws heartbeat reply send failed peer=%s id=%s", peer, req_id)
+ 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,
+ ):
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.
try:
resp = await asyncio.to_thread(server.dispatch, req, transport)
except Exception:
dispatch_crashes += 1
- _log.exception(
- "ws dispatch crash peer=%s id=%s method=%s",
- peer,
- req_id,
- req_method,
- )
- ok = await transport.write_async(
- {
- "jsonrpc": "2.0",
- "error": {"code": -32603, "message": "internal error"},
- "id": req_id if req_id is not None else None,
- }
- )
- if not ok:
- disconnect_reason = "send_failed_after_dispatch_crash"
- send_failures += 1
- _log.warning(
- "ws dispatch-crash reply send failed peer=%s id=%s method=%s",
- peer,
- req_id,
- req_method,
- )
+ _log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)
+ if not await _reply(
+ _error_frame(-32603, "internal error", req_id),
+ "send_failed_after_dispatch_crash",
+ "ws dispatch-crash reply send failed peer=%s id=%s method=%s", peer, req_id, req_method,
+ ):
break
continue
- if resp is not None and not await transport.write_async(resp):
- disconnect_reason = "send_failed_after_response"
- send_failures += 1
- _log.warning(
- "ws response send failed peer=%s id=%s method=%s",
- peer,
- req_id,
- req_method,
- )
+ if resp is not None and not await _reply(
+ resp,
+ "send_failed_after_response",
+ "ws response send failed peer=%s id=%s method=%s", peer, req_id, req_method,
+ ):
break
finally:
- reaped_sessions = 0
- detached_sessions = 0
+ reaped_sessions = detached_sessions = 0
if transport is not None:
server.unregister_live_transport(transport)
- # Owner-safely park browser controllers this transport registered.
- # A reconnect with the same stable identity may deliver a terminal
- # result for work already in flight; no new dispatch is admitted
- # while the controller is offline.
- #
- # Offloaded via to_thread: disconnect acquires the controller's
- # send_lock, which a worker-thread dispatch may hold while blocking
- # on THIS loop to transmit its frame (run_coroutine_threadsafe +
- # result(timeout=10)). Acquiring it synchronously here would park
- # the whole event loop behind that 10s send bridge.
+ # 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,
- )
+ from gateway.browser_control_broker import get_browser_control_broker
- await asyncio.to_thread(
- get_browser_control_broker().disconnect_owner, transport
- )
+ await asyncio.to_thread(get_browser_control_broker().disconnect_owner, transport)
except Exception:
_log.exception("ws browser-controller disconnect failed peer=%s", peer)
@@ -586,23 +454,15 @@ async def handle_ws(
except Exception:
_log.exception("ws wake-word teardown failed peer=%s", peer)
- # Reap sessions this transport owned (close_on_disconnect sidecar
- # sessions) or detach the rest to the drop sentinel so later emits
- # don't crash into a closed socket or fall through to desktop stdout
- # logs. Detached sessions are handed to the grace-windowed WS-orphan
- # reaper inside _close_sessions_for_transport (a quick reconnect /
- # session.resume cancels it). This is the single WS-disconnect
- # teardown path.
- #
- # Offloaded: _close_session_by_id does a blocking worker.close()
- # (terminate + waits) plus a synchronous DB write — inline that
- # would freeze the uvicorn event loop for every other live
- # connection.
+ # 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(
- server._close_sessions_for_transport,
- transport,
- end_reason="ws_disconnect",
+ server._close_sessions_for_transport, transport, end_reason="ws_disconnect"
)
except Exception:
_log.exception("ws transport teardown failed peer=%s", peer)
@@ -613,12 +473,6 @@ async def handle_ws(
_log.info(
"ws closed peer=%s reason=%s messages=%d parse_errors=%d "
"dispatch_crashes=%d send_failures=%d reaped_sessions=%d detached_sessions=%d",
- peer,
- disconnect_reason,
- messages,
- parse_errors,
- dispatch_crashes,
- send_failures,
- reaped_sessions,
- detached_sessions,
+ peer, disconnect_reason, messages, parse_errors,
+ dispatch_crashes, send_failures, reaped_sessions, detached_sessions,
)