Skip to content

The agent that grows with you

refactor(tui): session_lifecycle/workdir/reaper — lease retry helper, fold single-caller helpers, drop empty registries, compact docstrings

Tekniume4cec29a52f9
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index c84ab68013c..6b6efc09be4 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -1,17 +1,13 @@
"""Session lifecycle: active-session slot leases, finalize/teardown/close, turn interrupt,
-WS-orphan reap scheduling, transport-scoped close.
-
-Bodies are rebound onto server.py's globals at install time (method_ctx.bind_module),
-so they reference server.py globals bare.
+WS-orphan reap scheduling, transport-scoped close. Bodies are rebound onto server.py's
+globals at install time (method_ctx.bind_module), so they reference server.py globals bare.
"""
from __future__ import annotations
import contextlib
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
def _notify_session_boundary(event_type: str, session_id: str | None, platform: str | None = None) -> None:
@@ -25,9 +21,7 @@ def _notify_session_boundary(event_type: str, session_id: str | None, platform:
_SESSION_OWNERSHIP_UNAVAILABLE = "Hermes could not safely reserve this session. Try again."
-
-_AUTOMATIC_SESSION_END_REASONS = frozenset({
- "ws_orphan_reap", "ws_disconnect", "idle_timeout", "lru_evict", "tui_shutdown"})
+_AUTOMATIC_SESSION_END_REASONS = frozenset({"ws_orphan_reap", "ws_disconnect", "idle_timeout", "lru_evict", "tui_shutdown"})
def _claim_active_session_slot(
@@ -36,23 +30,20 @@ def _claim_active_session_slot(
try:
from hermes_cli.active_sessions import try_acquire_active_session
return try_acquire_active_session(
- session_id=session_key, surface=surface, config=_load_cfg(),
- metadata={"live_session_id": live_session_id}, registry_home=profile_home,
+ session_id=session_key, surface=surface, config=_load_cfg(), registry_home=profile_home,
+ metadata={"live_session_id": live_session_id},
track_liveness=str(surface or "").strip().lower() == "desktop")
except Exception as exc:
logger.warning("Failed to claim active session slot: %s", exc)
- # Fail CLOSED regardless of surface: an errored claim has NOT proven the session
- # unowned, and proceeding lease-less is a silent double-writer hole.
+ # Fail CLOSED regardless of surface: an errored claim has NOT proven the session unowned, and
+ # proceeding lease-less is a silent double-writer hole.
return (None, _SESSION_OWNERSHIP_UNAVAILABLE)
def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
- """Claim this session's cap slot on its first real turn; None when ok.
-
- session.create/resume deliberately do NOT claim: tile paints, reconnect-resumes and
- abandoned drafts would hold invisible slots (no DB row) that starve the messaging
- gateway sharing the cap. Anything holding a slot must be user-visible.
- """
+ """Claim this session's cap slot on its first real turn; None when ok. session.create/resume deliberately
+ do NOT claim: tile paints, reconnect-resumes and abandoned drafts would hold invisible slots (no DB row)
+ that starve the messaging gateway sharing the cap. Anything holding a slot must be user-visible."""
if session.get("active_session_lease") is not None:
return None
lease, limit_message = _claim_active_session_slot(
@@ -63,21 +54,28 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
return limit_message
+def _lease_retry(attempts: int, fn) -> Exception | None:
+ """Call ``fn`` up to ``attempts`` times (50ms*n backoff, registry writes contend across processes); the
+ last exception when every try failed, else None."""
+ for attempt in range(attempts):
+ try:
+ fn()
+ return None
+ except Exception as exc:
+ last_error = exc
+ if attempt + 1 < attempts:
+ time.sleep(0.05 * (attempt + 1))
+ return last_error
+
+
def _release_active_session_slot(session: dict | None) -> bool:
"""Release the session's lease (liveness-tracked leases get 3 tries); True when released."""
lease = session.get("active_session_lease") if session else None
if lease is None:
return True
- attempts = 3 if getattr(lease, "track_liveness", False) else 1
- for attempt in range(attempts):
- try:
- lease.release()
- break
- except Exception:
- if attempt + 1 >= attempts:
- logger.warning("Failed to release active session slot", exc_info=True)
- return False
- time.sleep(0.05 * (attempt + 1))
+ if (err := _lease_retry(3 if getattr(lease, "track_liveness", False) else 1, lease.release)) is not None:
+ logger.warning("Failed to release active session slot", exc_info=err)
+ return False
if not (getattr(lease, "released", True) or not getattr(lease, "enabled", True)):
return False
if session.get("active_session_lease") is lease:
@@ -87,10 +85,9 @@ def _release_active_session_slot(session: dict | None) -> bool:
@contextlib.contextmanager
def _other_runtime_lease_guard(session_id: str, session: dict):
- """Release this runtime and lock sibling ownership through the DB write.
-
- Yields True (another runtime owns the lifecycle -> preserve) when the guard cannot be
- loaded or entered after 3 tries: an unknown ownership state must never end a row."""
+ """Release this runtime and lock sibling ownership through the DB write. Yields True (another runtime
+ owns the lifecycle -> preserve) when the guard cannot be loaded or entered after 3 tries: an unknown
+ ownership state must never end a row."""
lease = session.get("active_session_lease")
try:
from hermes_cli.active_sessions import active_session_liveness_guard, release_active_session_liveness_guard
@@ -98,29 +95,24 @@ def _other_runtime_lease_guard(session_id: str, session: dict):
logger.warning("Failed to load active session ownership guard; preserving session %s: %s", session_id, exc)
yield True
return
-
- last_error: Exception | None = None
stack = contextlib.ExitStack()
- for attempt in range(3):
- try:
- if lease is not None and getattr(lease, "enabled", False):
- guard = release_active_session_liveness_guard(lease, session_id)
- else:
- guard = active_session_liveness_guard(session_id, registry_home=session.get("profile_home"))
- active = stack.enter_context(guard)
- break
- except Exception as exc:
- stack.close()
- stack = contextlib.ExitStack()
- last_error = exc
- if attempt < 2:
- time.sleep(0.05 * (attempt + 1))
- else:
+ active: list = []
+
+ def _enter() -> None:
+ stack.close() # drop anything a half-failed previous attempt left behind
+ if lease is not None and getattr(lease, "enabled", False):
+ guard = release_active_session_liveness_guard(lease, session_id)
+ else:
+ guard = active_session_liveness_guard(session_id, registry_home=session.get("profile_home"))
+ active[:] = [stack.enter_context(guard)]
+
+ if (last_error := _lease_retry(3, _enter)) is not None:
+ stack.close()
logger.warning("Failed to inspect active session leases; preserving session %s: %s", session_id, last_error)
yield True
return
try:
- yield active
+ yield active[0]
finally:
stack.close()
if lease is not None and getattr(lease, "released", False) and session.get("active_session_lease") is lease:
@@ -141,10 +133,9 @@ def _transfer_active_session_slot(sid: str, session: dict, *, new_session_id: st
logger.debug("Failed to transfer active session slot", exc_info=True)
if getattr(lease, "track_liveness", False):
return False
-
- # Fallback (entry pruned / pid-check transiently failed): reserve the new slot BEFORE
- # releasing the old one so a gateway at the cap can't grab the freed slot and leave
- # this session lease-less. On reserve failure KEEP the old lease.
+ # Fallback (entry pruned / pid-check transiently failed): reserve the new slot BEFORE releasing the old one
+ # so a gateway at the cap can't grab the freed slot and leave this session lease-less. On reserve failure
+ # KEEP the old lease.
new_lease, limit_message = _claim_active_session_slot(
new_session_id, live_session_id=sid, surface=_session_source(session), profile_home=session.get("profile_home"))
if new_lease is None:
@@ -154,28 +145,24 @@ def _transfer_active_session_slot(sid: str, session: dict, *, new_session_id: st
"sid=%s new_session_id=%s reason=%s",
sid, new_session_id, limit_message)
return False
- old_lease = session.pop("active_session_lease", None)
- if old_lease is not None:
- try:
- old_lease.release()
- except Exception:
- logger.debug("Failed to release stale active session slot", exc_info=True)
+ if (old := session.pop("active_session_lease", None)) is not None and (err := _lease_retry(1, old.release)):
+ logger.debug("Failed to release stale active session slot", exc_info=err)
session["active_session_lease"] = new_lease
return True
-# Sources this backend must never end in state.db: the messaging gateway owns those
-# sessions and the TUI is only a viewer (ending one causes the Groundhog Day routing
-# loop, see _finalize_session). Self-created and CLI sources are NOT gateway-owned.
+# Sources this backend must never end in state.db: the messaging gateway owns those sessions and the TUI is
+# only a viewer (ending one causes the Groundhog Day routing loop, see _finalize_session). Self-created and
+# CLI sources are NOT gateway-owned.
_NON_GATEWAY_SOURCES = frozenset({
"", "tui", "cli", "webui", "desktop", "cron", "kanban", "subagent", "test",
"local", "acp", "webhook", "api_server", "msgraph_webhook"})
def _is_gateway_owned_source(source: str) -> bool:
- """True when ``source`` resolves to a gateway ``Platform`` (enum member or plugin via
- ``Platform._missing_``), so new platforms are covered automatically; self-owned sources
- (``local``/``webhook``/``api_server`` are Platform members) are excluded explicitly."""
+ """True when ``source`` resolves to a gateway ``Platform`` (enum member or plugin via ``Platform._missing_``),
+ so new platforms are covered automatically; self-owned sources that are Platform members
+ (``local``/``webhook``/``api_server``) are excluded explicitly."""
src = (source or "").strip().lower()
if src in _NON_GATEWAY_SOURCES:
return False
@@ -197,8 +184,8 @@ def _lifecycle_own_sid(session: dict, sid_hint: str = "") -> str:
def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> None:
- """Best-effort finalize hook + memory commit; mirrors the CLI exit path so a
- force-quit mid-turn (double Ctrl-C, terminal close, SIGHUP) loses nothing."""
+ """Best-effort finalize hook + memory commit; mirrors the CLI exit path so a force-quit mid-turn (double
+ Ctrl-C, terminal close, SIGHUP) loses nothing."""
if not session or session.get("_finalized"):
return
session["_finalized"] = True
@@ -208,37 +195,31 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
history_ready.set()
_desktop_automatic_cleanup = (
end_reason in _AUTOMATIC_SESSION_END_REASONS and _session_source(session).strip().lower() == "desktop")
- # Automatic Desktop cleanup releases its lease inside the lock-held lifecycle guard
- # below; explicit close and non-Desktop paths keep force/end semantics.
+ # Automatic Desktop cleanup releases its lease inside the lock-held lifecycle guard below; explicit close
+ # and non-Desktop paths keep force/end semantics.
if not _desktop_automatic_cleanup:
_release_active_session_slot(session)
if (stop_event := session.get("_notif_stop")) is not None:
stop_event.set()
-
agent = session.get("agent")
lock = session.get("history_lock")
with (lock if lock is not None else contextlib.nullcontext()):
history = list(session.get("history", []))
-
- # Persist via ``_persist_session``'s marker-based dedup (same contract as the
- # gateway-shutdown flush). Do NOT pass ``conversation_history``: ``session["history"]``
- # and ``_session_messages`` alias the SAME list after a turn, so the flush would treat
- # every message as durable and skip it — data loss when finalize is the sole persist
- # path after a WS disconnect/restart.
- if agent is not None and hasattr(agent, "_persist_session") and (snapshot := getattr(agent, "_session_messages", None)):
+ # Persist via ``_persist_session``'s marker-based dedup (same contract as the gateway-shutdown flush). Do
+ # NOT pass ``conversation_history``: ``session["history"]`` and ``_session_messages`` alias the SAME list
+ # after a turn, so the flush would treat every message as durable and skip it — data loss when finalize
+ # is the sole persist path after a WS disconnect/restart.
+ if hasattr(agent, "_persist_session") and (snapshot := getattr(agent, "_session_messages", None)):
with contextlib.suppress(Exception):
agent._persist_session(snapshot)
-
# interrupted=True so crash-recovery plugins can flush state (mirrors cli.py atexit).
if agent is not None:
with contextlib.suppress(Exception):
from hermes_cli.lifecycle import invoke_hook
invoke_hook(
- "on_session_end",
+ "on_session_end", completed=False, interrupted=True,
session_id=getattr(agent, "session_id", None) or session.get("session_key", ""),
- completed=False, interrupted=True,
- model=getattr(agent, "model", "unknown"),
- platform=getattr(agent, "platform", None) or "tui")
+ model=getattr(agent, "model", "unknown"), platform=getattr(agent, "platform", None) or "tui")
if agent is not None and history and hasattr(agent, "commit_memory_session"):
with contextlib.suppress(Exception):
agent.commit_memory_session(history)
@@ -246,16 +227,14 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
session_key = session.get("session_key")
session_id = getattr(agent, "session_id", None) or session_key
_notify_session_boundary("on_session_finalize", session_id, _session_source(session))
-
- # End the state.db row so it doesn't linger as a ghost in /resume. Use session_id
- # (agent.session_id), not session_key: after compression the key may be the stale
- # ended parent while session_id is the live continuation.
+ # End the state.db row so it doesn't linger as a ghost in /resume. Use session_id (agent.session_id), not
+ # session_key: after compression the key may be the stale ended parent while session_id is the live
+ # continuation.
if _desktop_automatic_cleanup and not session_id:
_release_active_session_slot(session)
_lifecycle_guard = (
_other_runtime_lease_guard(session_id, session)
- if _desktop_automatic_cleanup and session_id
- else contextlib.nullcontext(False))
+ if _desktop_automatic_cleanup and session_id else contextlib.nullcontext(False))
with _lifecycle_guard as _other_runtime_owns_lifecycle:
_tui_owns_lifecycle = not _other_runtime_owns_lifecycle
if _other_runtime_owns_lifecycle:
@@ -265,42 +244,37 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
# The *session's* profile state.db (app-global remote mode), not the launch profile's.
with contextlib.suppress(Exception), _session_db(session) as db:
if db is not None:
- # Never end gateway-originated sessions (Groundhog Day loop: the
- # gateway's self-heal recovers to the parent, compression splits back
- # to the reaped child, repeat on every message).
- row = db.get_session(session_id)
- if _is_gateway_owned_source((row or {}).get("source", "")):
+ # Never end gateway-originated sessions (Groundhog Day loop: the gateway's self-heal
+ # recovers to the parent, compression splits back to the reaped child, repeat forever).
+ if _is_gateway_owned_source((db.get_session(session_id) or {}).get("source", "")):
_tui_owns_lifecycle = False
elif _tui_owns_lifecycle:
db.end_session(session_id, end_reason)
-
- # In-flight async delegations end WITH the session (no return address left). Always
- # interrupt by THIS live UI sid; by durable session_key only when the TUI owns the
- # lifecycle — closing a viewer tab must not kill the gateway's own background work.
+ # In-flight async delegations end WITH the session (no return address left). Always interrupt by THIS
+ # live UI sid; by durable session_key only when the TUI owns the lifecycle — closing a viewer tab must
+ # not kill the gateway's own background work.
with contextlib.suppress(Exception):
from tools.async_delegation import interrupt_for_session
interrupt_for_session(
session_key=str(session_key or "") if _tui_owns_lifecycle else "",
origin_ui_session_id=_lifecycle_own_sid(session), reason=end_reason)
- # Close the slash-worker in this single ``_finalized``-guarded chokepoint so a direct
- # _finalize_session caller can't leak it. Idempotent: close() is poll()-guarded.
+ # Close the slash-worker in this single ``_finalized``-guarded chokepoint so a direct _finalize_session
+ # caller can't leak it. Idempotent: close() is poll()-guarded.
with contextlib.suppress(Exception):
if worker := session.get("slash_worker"):
worker.close()
-# End reasons where the BACKEND reclaimed a session the client never asked to close;
-# without a signal the client's next prompt fails against a forgotten id. Client-initiated
-# reasons (``tui_close`` etc.) are deliberately absent.
+# End reasons where the BACKEND reclaimed a session the client never asked to close; without a signal the
+# client's next prompt fails against a forgotten id. Client-initiated reasons (``tui_close`` etc.) are
+# deliberately absent.
_RECLAIM_END_REASONS = frozenset({"idle_timeout", "lru_evict", "ws_orphan_reap"})
def _announce_session_reclaimed(session: dict, end_reason: str) -> None:
- """Tell connected clients a session was reclaimed out from under them.
-
- Broadcast, not session-targeted: reap paths run on timer threads with no contextvar
- binding and the WS-orphan case has lost its transport, so ``_emit`` would bottom out
- on stdio. Best-effort; never breaks teardown."""
+ """Tell connected clients a session was reclaimed out from under them. Broadcast, not session-targeted:
+ reap paths run on timer threads with no contextvar binding and the WS-orphan case has lost its
+ transport, so ``_emit`` would bottom out on stdio. Best-effort; never breaks teardown."""
if end_reason not in _RECLAIM_END_REASONS:
return
try:
@@ -313,9 +287,9 @@ def _announce_session_reclaimed(session: dict, end_reason: str) -> None:
def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") -> None:
- """Fully tear down a session: finalize, unregister notifier, close agent. Shared by
- ``session.close`` and the orphaned-WS reaper. The slash-worker is closed in
- ``_finalize_session`` (the single chokepoint), NOT here. Idempotent via ``_finalized``."""
+ """Fully tear down a session: finalize, unregister notifier, close agent. Shared by ``session.close`` and
+ the orphaned-WS reaper. The slash-worker is closed in ``_finalize_session`` (the single chokepoint), NOT
+ here. Idempotent via ``_finalized``."""
if not session:
return
_finalize_session(session, end_reason=end_reason)
@@ -325,14 +299,13 @@ def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") ->
if key := session.get("session_key"):
unregister_gateway_notify(key)
with contextlib.suppress(Exception):
- agent = session.get("agent")
- if agent is not None and hasattr(agent, "close"):
+ if hasattr(agent := session.get("agent"), "close"):
agent.close()
def _attach_worker(sid: str, session: dict, worker) -> None:
- """Store worker on session iff sid still maps to it, else close it — a
- concurrent teardown already popped the session and would orphan the worker."""
+ """Store worker on session iff sid still maps to it, else close it — a concurrent teardown already popped
+ the session and would orphan the worker."""
with _sessions_lock:
if _sessions.get(sid) is session:
session["slash_worker"] = worker
@@ -341,17 +314,15 @@ def _attach_worker(sid: str, session: dict, worker) -> None:
def _pop_session_by_id(sid: str) -> dict | None:
- """Atomically detach one live session from the registry — the ownership claim for
- teardown (a concurrent close/reaper then no-ops). Separate from ``_teardown_session``
- because finalization does slow external work that must not run under
- ``_session_resume_lock``."""
+ """Atomically detach one live session from the registry — the ownership claim for teardown (a concurrent
+ close/reaper then no-ops). Separate from ``_teardown_session`` because finalization does slow external
+ work that must not run under ``_session_resume_lock``."""
with _sessions_lock:
session = _sessions.pop(sid, None)
if session is not None:
session["_closing"] = True
if session is not None:
- # Out of _sessions now, so teardown can't recover the live id by scanning — stamp it.
- session["_sid"] = sid
+ session["_sid"] = sid # out of _sessions now, so teardown can't recover the live id by scanning
return session
@@ -376,18 +347,15 @@ def _teardown_popped_session(session: dict | None, *, end_reason: str = "tui_clo
def _close_session_by_id(
sid: str, *, end_reason: str = "tui_close", predicate: Callable[[dict], bool] | None = None
) -> bool:
- """Idempotent teardown funnel for callers with no resume race (resume-sensitive callers
- pop under ``_session_resume_lock`` and call ``_teardown_popped_session`` after releasing
- it). Automatic reapers pass ``predicate`` to revalidate under ``_sessions_lock`` right
- before the claim, so a stale scan can't close a session that reattached."""
- if predicate is None:
+ """Idempotent teardown funnel for callers with no resume race (resume-sensitive callers pop under
+ ``_session_resume_lock`` and call ``_teardown_popped_session`` after releasing it). Automatic reapers pass
+ ``predicate`` to revalidate under ``_sessions_lock`` right before the claim, so a stale scan can't close a
+ session that reattached."""
+ with _sessions_lock: # RLock: predicate + claim in one critical section
+ current = _sessions.get(sid)
+ if predicate is not None and (current is None or not predicate(current)):
+ return False
session = _pop_session_by_id(sid)
- else:
- with _sessions_lock:
- current = _sessions.get(sid)
- if current is None or not predicate(current):
- return False
- session = _pop_session_by_id(sid)
return _teardown_popped_session(session, end_reason=end_reason)
@@ -397,34 +365,31 @@ def _ws_session_is_detached(session: dict | None) -> bool:
def _ws_session_is_orphaned(session: dict | None) -> bool:
- """True if a WS session sits on ``_detached_ws_transport`` (where ``handle_ws`` parks
- disconnected clients) with no in-flight turn."""
+ """True if a WS session sits on ``_detached_ws_transport`` (where ``handle_ws`` parks disconnected clients)
+ with no in-flight turn."""
return bool(_ws_session_is_detached(session) and not session.get("running"))
def _interrupt_session_turn(sid: str, session: dict, *, request_id: str | None = None) -> bool:
- """Apply the shared ``session.interrupt`` contract to one claimed session; returns
- whether the compute-host control channel was used. The WS orphan reaper reuses this so
- a dead client gets the same partial-history and queued-prompt semantics."""
+ """Apply the shared ``session.interrupt`` contract to one claimed session; returns whether the compute-host
+ control channel was used. The WS orphan reaper reuses this so a dead client gets the same partial-history
+ and queued-prompt semantics."""
use_compute_host = _session_uses_compute_host(session)
should_interrupt = bool(session.get("running"))
run_thread_alive = False
if use_compute_host:
- # The host owns the live turn (parent `running` can lag a blocked tool), so let it
- # decide. Gate on `_compute_host_active`: HostSupervisor.interrupt() calls start(),
- # so forwarding blindly for a lazy session would spawn a child just to interrupt.
+ # The host owns the live turn (parent `running` can lag a blocked tool), so let it decide. Gate on
+ # `_compute_host_active`: HostSupervisor.interrupt() calls start(), so forwarding blindly for a lazy
+ # session would spawn a child just to interrupt.
if should_interrupt or session.get("_compute_host_active"):
_get_compute_host_supervisor().interrupt(sid, request_id=request_id)
else:
- run_thread = session.get("_run_thread")
- run_thread_alive = run_thread is not None and run_thread.is_alive()
-
+ run_thread_alive = (rt := session.get("_run_thread")) is not None and rt.is_alive()
with session["history_lock"]:
session["_turn_cancel_requested"] = True
session["queued_prompt"] = None
session.pop("queued_prompts", None)
session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
-
if not use_compute_host:
if should_interrupt:
from agent.interrupt_compat import request_hard_interrupt
@@ -434,7 +399,6 @@ def _interrupt_session_turn(sid: str, session: dict, *, request_id: str | None =
if session.get("running"):
session["running"] = False
_clear_inflight_turn(session)
-
_clear_pending(sid)
with contextlib.suppress(Exception):
from tools.approval import resolve_gateway_approval
@@ -442,31 +406,25 @@ def _interrupt_session_turn(sid: str, session: dict, *, request_id: str | None =
return use_compute_host
-def _session_owns_durable_lifecycle(session_id: str | None) -> bool:
- """Whether this TUI/desktop session may end its durable DB row by key
- (never for gateway-originated sessions — the TUI is only a viewer there)."""
- if not session_id:
- return True
- try:
- db = _get_db()
- return db is None or not _is_gateway_owned_source((db.get_session(session_id) or {}).get("source", ""))
- except Exception:
- return True
-
-
def _session_has_active_delegations(sid: str, session: dict | None = None) -> bool:
- """True when UI session ``sid`` still owns live background work — by live UI sid AND,
- when the TUI owns the durable lifecycle (never for gateway-viewer tabs), by durable
- session_key so a delegation from an earlier tab of the same session keeps it alive."""
+ """True when UI session ``sid`` still owns live background work — by live UI sid AND, when the TUI owns the
+ durable lifecycle (never for gateway-viewer tabs), by durable session_key so a delegation from an earlier
+ tab of the same session keeps it alive."""
if session is None:
with _sessions_lock:
session = _sessions.get(sid)
if not session:
return False
own_sid = _lifecycle_own_sid(session, sid)
- session_key = str(session.get("session_key") or "")
+ owned_session_key = session_key = str(session.get("session_key") or "")
session_id = getattr(session.get("agent"), "session_id", None) or session_key
- owned_session_key = session_key if _session_owns_durable_lifecycle(session_id) else ""
+ if session_id:
+ # Only when this TUI/desktop session may end its durable row by key — never for gateway-originated
+ # sessions (the TUI is only a viewer there). Unknown DB state -> assume ownership.
+ with contextlib.suppress(Exception):
+ db = _get_db()
+ if db is not None and _is_gateway_owned_source((db.get_session(session_id) or {}).get("source", "")):
+ owned_session_key = ""
if not own_sid and not owned_session_key:
return False
try:
@@ -474,20 +432,19 @@ def _session_has_active_delegations(sid: str, session: dict | None = None) -> bo
return has_live_for_session(session_key=owned_session_key, origin_ui_session_id=own_sid)
except Exception:
logger.debug("Failed to query active delegations for UI session %s", sid, exc_info=True)
- # A transient registry/import failure must not become destructive cleanup.
- return True
+ return True # a transient registry/import failure must not become destructive cleanup
-# One pending WS-orphan reap Timer per live sid; guarded by _sessions_lock. Cancelled by
-# _cancel_ws_orphan_reap from every resume/reuse/transport-rebind path — otherwise a reap
-# could fire on a reattached session and trigger a reap->broadcast->resume storm.
+# One pending WS-orphan reap Timer per live sid; guarded by _sessions_lock. Cancelled by _cancel_ws_orphan_reap
+# from every resume/reuse/transport-rebind path — otherwise a reap could fire on a reattached session and
+# trigger a reap->broadcast->resume storm.
_pending_ws_reaps: dict[str, threading.Timer] = {}
def _cancel_ws_orphan_reap(sid: str) -> None:
- """Cancel a pending WS-orphan reap for ``sid`` (client came back). Called from every
- path that re-binds a live transport; closes the fired-but-not-run Timer race and stops
- dead Timers accumulating on flappy clients."""
+ """Cancel a pending WS-orphan reap for ``sid`` (client came back). Called from every path that re-binds a
+ live transport; closes the fired-but-not-run Timer race and stops dead Timers accumulating on flappy
+ clients."""
with _sessions_lock:
timer = _pending_ws_reaps.pop(sid, None)
if timer is not None:
@@ -496,11 +453,10 @@ def _cancel_ws_orphan_reap(sid: str) -> None:
def _ws_orphan_turn_activity_is_fresh(session: dict) -> bool:
- """Whether a detached RUNNING turn's activity clock (``_touch_activity``, the watchdog's
- clock) is still fresh — the reaper must NOT interrupt healthy detached work (closed
- laptop, backgrounded app). Conservative fallbacks keep the wedged-turn safety net:
- disabled threshold, missing/opaque agent, unreadable summary or never-stamped clock all
- report NOT fresh, i.e. eligible for interrupt-at-grace."""
+ """Whether a detached RUNNING turn's activity clock (``_touch_activity``, the watchdog's clock) is still
+ fresh — the reaper must NOT interrupt healthy detached work (closed laptop, backgrounded app).
+ Conservative fallbacks keep the wedged-turn safety net: disabled threshold, missing/opaque agent,
+ unreadable summary or never-stamped clock all report NOT fresh, i.e. eligible for interrupt-at-grace."""
if _WS_ORPHAN_ACTIVITY_STALE_S <= 0:
return False
summary_fn = getattr(session.get("agent"), "get_activity_summary", None)
@@ -514,20 +470,19 @@ def _ws_orphan_turn_activity_is_fresh(session: dict) -> bool:
def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:
- """After a grace window, reap session ``sid`` iff it's still orphaned. Called from the
- WS-disconnect path; a reconnect or ``session.resume`` cancels the reap by re-binding a
- live transport. Disabled when the grace is 0."""
+ """After a grace window, reap session ``sid`` iff it's still orphaned. Called from the WS-disconnect path; a
+ reconnect or ``session.resume`` cancels the reap by re-binding a live transport. Disabled when grace is 0."""
if _WS_ORPHAN_REAP_GRACE_S <= 0:
return
def _reap() -> None:
- # Serialize the re-check against session.resume (rebinds under _session_resume_lock).
- # Claim teardown by popping under both locks, then release the resume lock before
- # slow finalization. Ordering is always resume_lock -> sessions_lock (RLock).
+ # Serialize the re-check against session.resume (rebinds under _session_resume_lock). Claim teardown
+ # by popping under both locks, then release the resume lock before slow finalization. Ordering is
+ # always resume_lock -> sessions_lock (RLock).
reschedule_delay = interrupt_session = session = None
with _session_resume_lock:
- # Drop this Timer's registration so a concurrent _cancel_ws_orphan_reap can't
- # cancel a dead Timer while a rescheduled one (registered below) is the owner.
+ # Drop this Timer's registration so a concurrent _cancel_ws_orphan_reap can't cancel a dead Timer
+ # while a rescheduled one (registered below) is the owner.
with _sessions_lock:
_pending_ws_reaps.pop(sid, None)
current = _sessions.get(sid)
@@ -538,15 +493,15 @@ def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:
elif not current.get("running"):
session = _pop_session_by_id(sid)
elif not current.get("_client_gone_interrupt_requested") and _ws_orphan_turn_activity_is_fresh(current):
- # Client-absent but producing: keep running detached (the sentinel
- # buffers emits) and re-check each grace interval.
+ # Client-absent but producing: keep running detached (the sentinel buffers emits) and re-check
+ # each grace interval.
logger.debug(
"client_gone sid=%s action=defer (turn activity fresh; stale threshold %.0fs)",
sid, _WS_ORPHAN_ACTIVITY_STALE_S)
reschedule_delay = _WS_ORPHAN_REAP_GRACE_S
else:
- # Mid-turn detached sessions must never drop the single Timer: interrupt
- # once after grace, then poll until turn-finalization settles.
+ # Mid-turn detached sessions must never drop the single Timer: interrupt once after grace, then
+ # poll until turn-finalization settles.
polls = int(current.get("_client_gone_interrupt_polls") or 0) + 1
current["_client_gone_interrupt_polls"] = polls
if polls > _WS_ORPHAN_INTERRUPT_REAP_MAX_POLLS:
@@ -561,7 +516,6 @@ def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:
current["_client_gone_interrupt_requested"] = True
interrupt_session = current
reschedule_delay = _WS_ORPHAN_INTERRUPT_REAP_POLL_S
-
if interrupt_session is not None:
try:
isolated = _interrupt_session_turn(sid, interrupt_session, request_id=f"client-gone-{sid}")
@@ -590,18 +544,17 @@ def _schedule_ws_orphan_reap(sid: str, *, delay_s: float | None = None) -> None:
def _close_sessions_for_transport(transport, *, end_reason: str = "ws_disconnect") -> tuple[int, int]:
- """Single WS-disconnect teardown entry point: reap close_on_disconnect sessions
- (sidecar/dashboard) immediately and re-point the rest at the detached transport so
- later emits don't hit a dead socket; those go to the grace-windowed WS-orphan reaper.
- Returns ``(reaped, detached)`` counts."""
+ """Single WS-disconnect teardown entry point: reap close_on_disconnect sessions (sidecar/dashboard)
+ immediately and re-point the rest at the detached transport so later emits don't hit a dead socket;
+ those go to the grace-windowed WS-orphan reaper. Returns ``(reaped, detached)`` counts."""
with _sessions_lock:
owned = [(sid, s) for sid, s in _sessions.items() if s.get("transport") is transport]
reaped = detached = 0
for sid, session in owned:
claimed_for_teardown = None
should_schedule_reap = False
- # session.resume fast-path rebinds under _session_resume_lock: take it before
- # re-checking so a reconnect can't move the transport between check and claim.
+ # session.resume fast-path rebinds under _session_resume_lock: take it before re-checking so a
+ # reconnect can't move the transport between check and claim.
with _session_resume_lock, _sessions_lock:
current = _sessions.get(sid)
if current is not session:
@@ -613,15 +566,13 @@ def _close_sessions_for_transport(transport, *, end_reason: str = "ws_disconnect
if current.get("close_on_disconnect"):
claimed_for_teardown = _pop_session_by_id(sid)
else:
- # Point at the drop sentinel (NOT real stdio) so _ws_session_is_orphaned
- # recognizes it; standalone `hermes --tui` keeps real _stdio. UNLESS
- # another window (multi-window pop-out viewer) still shows the session:
- # re-bind to the most recent surviving viewer instead of stranding it.
+ # Point at the drop sentinel (NOT real stdio) so _ws_session_is_orphaned recognizes it;
+ # standalone `hermes --tui` keeps real _stdio. UNLESS another window (multi-window pop-out
+ # viewer) still shows the session: re-bind to the most recent surviving viewer instead.
viewers = current.get("viewers") or {}
viewers.pop(transport, None)
- live = [
- vt for vt, ts in sorted(viewers.items(), key=lambda kv: kv[1])
- if vt is not transport and not _transport_is_dead(vt)]
+ live = [vt for vt, ts in sorted(viewers.items(), key=lambda kv: kv[1])
+ if vt is not transport and not _transport_is_dead(vt)]
if live:
current["transport"] = live[-1]
else:
@@ -629,8 +580,7 @@ def _close_sessions_for_transport(transport, *, end_reason: str = "ws_disconnect
current.pop("_client_gone_interrupt_requested", None)
should_schedule_reap = True
if claimed_for_teardown is not None:
- if _teardown_popped_session(claimed_for_teardown, end_reason=end_reason):
- reaped += 1
+ reaped += _teardown_popped_session(claimed_for_teardown, end_reason=end_reason)
elif should_schedule_reap:
detached += 1
with contextlib.suppress(Exception):
@@ -639,5 +589,5 @@ def _close_sessions_for_transport(transport, *, end_reason: str = "ws_disconnect
def register(server) -> None:
- """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ """Publish this module's helpers onto ``server``, rebound to its globals."""
bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/session_reaper.py b/tui_gateway/session_reaper.py
index 9dc4744da78..ba91af9159c 100644
--- a/tui_gateway/session_reaper.py
+++ b/tui_gateway/session_reaper.py
@@ -1,31 +1,28 @@
-"""Session flush / reaping / orphan sweep / cross-backend heartbeat: exit-flush signal handlers,
-idle + LRU eviction, orphaned session-row sweep, backend heartbeat refresher.
-
-Bodies are rebound onto server.py's globals at install time (method_ctx.bind_module), so they
-reference server.py globals bare — including the knobs _SESSION_TTL_S, _REAPER_SCAN_S,
-_EXIT_FLUSH_BUDGET_S and _INCREMENTAL_FLUSH_INTERVAL_S.
+"""Session flush / reaping / orphan sweep / cross-backend heartbeat: exit-flush signal handlers, idle + LRU
+eviction, orphaned session-row sweep, backend heartbeat refresher. Bodies are rebound onto server.py's
+globals at install time (method_ctx.bind_module), so they reference server.py globals bare — including the
+knobs _SESSION_TTL_S, _REAPER_SCAN_S, _EXIT_FLUSH_BUDGET_S and _INCREMENTAL_FLUSH_INTERVAL_S.
"""
from __future__ import annotations
import contextlib
+import secrets
import threading
from tui_gateway._env import env_float
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
# ── Flush-on-kill + periodic incremental flush ───────────────────────────
-# (a) SIGTERM/SIGINT run a bounded flush to state.db BEFORE normal shutdown, chained to the prior
-# handler; (b) the idle-reaper scan piggybacks an incremental flush so a SIGKILL loses at most one interval.
+# (a) SIGTERM/SIGINT run a bounded flush to state.db BEFORE normal shutdown, chained to the prior handler;
+# (b) the idle-reaper scan piggybacks an incremental flush so a SIGKILL loses at most one interval.
def _flush_session_messages(session: dict | None) -> bool:
- """Best-effort durable flush of one session's transcript via ``agent._persist_session`` (same
- marker-deduped contract as ``_finalize_session``: repeated calls never duplicate rows)."""
+ """Best-effort durable flush of one session's transcript via ``agent._persist_session`` (same marker-deduped
+ contract as ``_finalize_session``: repeated calls never duplicate rows)."""
agent = session.get("agent") if session else None
snapshot = getattr(agent, "_session_messages", None) if hasattr(agent, "_persist_session") else None
if not snapshot:
@@ -44,10 +41,10 @@ def _reaper_session_snapshot() -> list:
def _flush_dirty_sessions(now: float | None = None) -> int:
- """Periodic incremental flush, driven by the idle-reaper scan. Skips ``running`` sessions: the
- turn thread owns mid-turn persistence and mutates the live message list, so racing it from the
- reaper thread is never safe. Idle sessions flush at most once per ``_INCREMENTAL_FLUSH_INTERVAL_S``;
- ``now`` (monotonic) is injectable for tests."""
+ """Periodic incremental flush, driven by the idle-reaper scan. Skips ``running`` sessions: the turn thread
+ owns mid-turn persistence and mutates the live message list, so racing it from the reaper thread is never
+ safe. Idle sessions flush at most once per ``_INCREMENTAL_FLUSH_INTERVAL_S``; ``now`` (monotonic) is
+ injectable for tests."""
if _INCREMENTAL_FLUSH_INTERVAL_S <= 0:
return 0
now = time.monotonic() if now is None else now
@@ -64,9 +61,9 @@ def _flush_dirty_sessions(now: float | None = None) -> int:
def _flush_sessions_before_exit(budget_s: float | None = None) -> int:
- """Bounded flush of ALL in-memory sessions on the way out, on a daemon worker joined with the
- budget so a hung SQLite write can't block exit past ``HERMES_TUI_EXIT_FLUSH_BUDGET_S`` (default
- 5s). Running sessions are included — the process is dying, a partial transcript beats loss."""
+ """Bounded flush of ALL in-memory sessions on the way out, on a daemon worker joined with the budget so a
+ hung SQLite write can't block exit past ``HERMES_TUI_EXIT_FLUSH_BUDGET_S`` (default 5s). Running sessions
+ are included — the process is dying, a partial transcript beats loss."""
budget = _EXIT_FLUSH_BUDGET_S if budget_s is None else max(0.0, budget_s)
if budget <= 0:
return 0
@@ -90,8 +87,8 @@ _exit_flush_handlers_installed = False
def _handle_exit_flush_signal(signum, frame) -> None:
- """Flush in-memory sessions, then hand off to the prior handler (uvicorn's graceful shutdown, a
- supervisor's handler, or the default disposition) — this only *prepends* a bounded flush."""
+ """Flush in-memory sessions, then hand off to the prior handler (uvicorn's graceful shutdown, a supervisor's
+ handler, or the default disposition) — this only *prepends* a bounded flush."""
with contextlib.suppress(Exception):
_flush_sessions_before_exit()
import signal as _signal
@@ -99,8 +96,8 @@ def _handle_exit_flush_signal(signum, frame) -> None:
if callable(prev):
prev(signum, frame)
elif prev is not _signal.SIG_IGN:
- # Default disposition: restore it and re-raise so the process dies with the correct
- # signal (exit status visible to supervisors).
+ # Default disposition: restore it and re-raise so the process dies with the correct signal (exit status
+ # visible to supervisors).
try:
_signal.signal(signum, _signal.SIG_DFL)
os.kill(os.getpid(), signum)
@@ -109,10 +106,10 @@ def _handle_exit_flush_signal(signum, frame) -> None:
def install_exit_flush_signal_handlers() -> bool:
- """Install chaining SIGTERM/SIGINT flush handlers (main thread only). Called before uvicorn takes
- over signals: its ``capture_signals()`` saves these as the "original" handlers and re-raises into
- them after graceful shutdown, so the flush also covers terminations outside uvicorn's serve
- window. Idempotent; False off-main-thread/on failure."""
+ """Install chaining SIGTERM/SIGINT flush handlers (main thread only). Called before uvicorn takes over
+ signals: its ``capture_signals()`` saves these as the "original" handlers and re-raises into them after
+ graceful shutdown, so the flush also covers terminations outside uvicorn's serve window. Idempotent; False
+ off-main-thread/on failure."""
global _exit_flush_handlers_installed
if _exit_flush_handlers_installed:
return True
@@ -131,15 +128,16 @@ def install_exit_flush_signal_handlers() -> bool:
def _transport_is_dead(transport) -> bool:
- # _detached_ws_transport is the post-disconnect drop sentinel. _stdio_transport is the
- # REAL transport for standalone `hermes --tui` and must NOT count as dead.
+ # _detached_ws_transport is the post-disconnect drop sentinel. _stdio_transport is the REAL transport for
+ # standalone `hermes --tui` and must NOT count as dead.
return transport is _detached_ws_transport or getattr(transport, "_closed", None) is True
-def _reaper_session_is_detached_idle(sid: str, session: dict) -> bool:
- """Shared hard exemptions for both reapers: never evict a session mid-turn, awaiting input, still
- building, owning live delegated work, or on a live transport. Lazy watch sessions never start a
- build, so their unset agent_ready must not make them immortal."""
+def _session_is_lru_evictable(sid: str, session: dict) -> bool:
+ """Shared hard exemptions for both reapers (the LRU cap applies them WITHOUT the age gate: eligible the moment
+ it loses its client): never evict a session mid-turn, awaiting input, still building, owning live delegated
+ work, or on a live transport. Lazy watch sessions never start a build, so their unset agent_ready must not
+ make them immortal."""
if session.get("running") or _session_pending_kind(sid) or _session_has_active_delegations(sid, session):
return False
ready = session.get("agent_ready")
@@ -149,7 +147,8 @@ def _reaper_session_is_detached_idle(sid: str, session: dict) -> bool:
def _session_is_evictable(sid: str, session: dict, now: float) -> bool:
- if not _reaper_session_is_detached_idle(sid, session):
+ """TTL eviction: the LRU exemptions plus idle-for-TTL AND older-than-TTL."""
+ if not _session_is_lru_evictable(sid, session):
return False
last_active = float(session.get("last_active") or 0.0)
created_at = float(session.get("created_at") or 0.0)
@@ -170,8 +169,8 @@ def _reap_idle_sessions() -> None:
predicate=lambda session, vs=sid: _session_is_evictable(vs, session, time.time()))
_enforce_session_cap()
_reclaim_orphaned_leases()
- # Long-lived processes: gen2 GC rarely runs at steady state and glibc retains freed
- # pages as RSS, so trim every scan to prevent unbounded RSS growth over days/weeks.
+ # Long-lived processes: gen2 GC rarely runs at steady state and glibc retains freed pages as RSS, so trim
+ # every scan to prevent unbounded RSS growth over days/weeks.
try:
from hermes_cli.mem_trim import trim_memory
trim_memory(reason="idle reaper periodic trim")
@@ -184,19 +183,17 @@ def _reclaim_orphaned_leases() -> None:
try:
from hermes_cli.active_sessions import release_orphaned_leases
with _sessions_lock:
- live = {
- lease.lease_id for session in _sessions.values()
- if (lease := session.get("active_session_lease")) is not None}
+ live = {lease.lease_id for session in _sessions.values()
+ if (lease := session.get("active_session_lease")) is not None}
if dropped := release_orphaned_leases(live):
logger.info("Reclaimed %d orphaned active-session lease(s)", dropped)
except Exception:
logger.debug("orphaned lease reclaim failed", exc_info=True)
-# Soft LRU cap on in-memory sessions: the TTL reaper only frees sessions idle for hours, so a heavy
-# reconnecting user accumulates resident detached agents. The cap evicts the least-recently-active
-# DETACHED sessions sooner — never a running / pending / mid-build / live-transport one (reopening
-# re-resumes from the DB). 0/null disables.
+# Soft LRU cap on in-memory sessions: the TTL reaper only frees sessions idle for hours, so a heavy reconnecting
+# user accumulates resident detached agents. The cap evicts the least-recently-active DETACHED sessions sooner —
+# never a running / pending / mid-build / live-transport one (reopening re-resumes from the DB). 0/null disables.
def _max_live_sessions() -> int:
try:
from hermes_cli.active_sessions import coerce_max_concurrent_sessions
@@ -210,11 +207,6 @@ def _max_live_sessions() -> int:
return 0
-def _session_is_lru_evictable(sid: str, session: dict) -> bool:
- # TTL-reaper exemptions WITHOUT the age gate: eligible the moment it loses its client.
- return _reaper_session_is_detached_idle(sid, session)
-
-
def _enforce_session_cap() -> None:
cap = _max_live_sessions()
if cap <= 0:
@@ -235,7 +227,6 @@ def _enforce_session_cap() -> None:
def _reaper_daemon_timer(delay: float, fn, fail_log: str, level: str = "debug") -> None:
"""Run ``fn`` once on a daemon Timer after ``delay``; log (never raise) on failure."""
-
def _run() -> None:
try:
fn()
@@ -253,18 +244,18 @@ def _schedule_session_cap_enforcement() -> None:
# ── Startup sweep for orphaned session rows ──────────────────────────────
-# The WS-orphan reaper is an in-process Timer: a gateway restart kills it before it fires, leaving
-# the row `ended_at IS NULL` forever. Scheduled once per process from both gateway entry points
-# (stdio `entry.main`, WS sidecar `handle_ws`). state.db is shared by sibling processes on the same
-# profile, so eligibility is conservative. Disable via `dashboard.startup_orphan_sweep: false`.
+# The WS-orphan reaper is an in-process Timer: a gateway restart kills it before it fires, leaving the row
+# `ended_at IS NULL` forever. Scheduled once per process from both gateway entry points (stdio `entry.main`, WS
+# sidecar `handle_ws`). state.db is shared by sibling processes on the same profile, so eligibility is
+# conservative. Disable via `dashboard.startup_orphan_sweep: false`.
_ORPHAN_SWEEP_SOURCES = ("tui", "desktop", "subagent")
_startup_orphan_sweep_ran = False
_startup_orphan_sweep_lock = threading.Lock()
def _session_orphan_reaper_enabled() -> bool:
- """``dashboard.startup_orphan_sweep`` (default on). Fail-open on errors and on a missing key
- (raw yaml, no DEFAULT_CONFIG merge on this loader)."""
+ """``dashboard.startup_orphan_sweep`` (default on). Fail-open on errors and on a missing key (raw yaml, no
+ DEFAULT_CONFIG merge on this loader)."""
try:
dashboard_cfg = (_load_cfg() or {}).get("dashboard") or {}
if isinstance(dashboard_cfg, dict) and "startup_orphan_sweep" in dashboard_cfg:
@@ -274,31 +265,24 @@ def _session_orphan_reaper_enabled() -> bool:
return True
-def _live_session_ids() -> list[str]:
- """Session ids this process currently holds in memory."""
- ids: set[str] = set()
+def _sweep_orphaned_session_rows() -> list[str]:
+ """End orphaned tui/desktop/subagent rows left by a dead process. "Provably orphaned" is inferred
+ conservatively: the row must have been created AND last messaged at least the session TTL ago (a fresh row
+ that copied an old transcript is protected by its own ``started_at``). Rows held in memory (e.g. a
+ ``session.resume`` in the startup grace window) are excluded. Cross-backend: the sweep refuses to close a
+ row any live backend (heartbeat within ``2 * TTL``) could own — see ``SessionDB.sweep_orphaned_sessions``."""
+ db = _get_db()
+ if db is None or _SESSION_TTL_S <= 0:
+ return []
+ live_ids: set[str] = set() # every id this process holds in memory: live sid, agent session_id, session_key
with _sessions_lock:
for sid, session in _sessions.items():
candidates = [sid]
if isinstance(session, dict):
candidates += [getattr(session.get("agent"), "session_id", None), session.get("session_key")]
- ids.update(str(c) for c in candidates if c)
- return sorted(ids)
-
-
-def _sweep_orphaned_session_rows() -> list[str]:
- """End orphaned tui/desktop/subagent rows left by a dead process.
-
- "Provably orphaned" is inferred conservatively: the row must have been created AND last messaged
- at least the session TTL ago (a fresh row that copied an old transcript is protected by its own
- ``started_at``). Rows held in memory (e.g. a ``session.resume`` in the startup grace window) are
- excluded. Cross-backend: the sweep refuses to close a row any live backend (heartbeat within
- ``2 * TTL``) could own — see ``SessionDB.sweep_orphaned_sessions``."""
- db = _get_db()
- if db is None or _SESSION_TTL_S <= 0:
- return []
+ live_ids.update(str(c) for c in candidates if c)
swept = db.sweep_orphaned_sessions(
- max_idle_seconds=_SESSION_TTL_S, sources=_ORPHAN_SWEEP_SOURCES, exclude_ids=tuple(_live_session_ids()))
+ max_idle_seconds=_SESSION_TTL_S, sources=_ORPHAN_SWEEP_SOURCES, exclude_ids=tuple(sorted(live_ids)))
if swept:
logger.info(
"Closed %d orphaned session row(s) from a previous gateway process (startup_orphan_reap): %s",
@@ -307,37 +291,32 @@ def _sweep_orphaned_session_rows() -> list[str]:
# ── Cross-backend heartbeat ──────────────────────────────────────────────
-# Each serve / gateway process registers a heartbeat row in ``gateway_heartbeats`` so the startup
-# sweep can tell "owned by a live but idle backend" from "truly orphaned" (else the first process to
-# restart reaped every inactive row of the other N−1). Refresh 60s default — far shorter than the
-# 6h TTL so a refresh always lands inside the staleness window. Removed at exit; a crashed row ages out.
-
+# Each serve / gateway process registers a heartbeat row in ``gateway_heartbeats`` so the startup sweep can tell
+# "owned by a live but idle backend" from "truly orphaned" (else the first process to restart reaped every
+# inactive row of the other N−1). Refresh 60s default — far shorter than the 6h TTL so a refresh always lands
+# inside the staleness window. Removed at exit; a crashed row ages out.
_HEARTBEAT_REFRESH_S = max(0.0, env_float("HERMES_GATEWAY_HEARTBEAT_REFRESH_S", 60.0))
-
_heartbeat_refresher_started = False
_heartbeat_refresher_lock = threading.Lock()
+_BACKEND_NONCE = secrets.token_hex(4)
def _reaper_hostname() -> str:
return os.uname().nodename if hasattr(os, "uname") else "host"
-def _reaper_memo(fn, attr: str, compute):
- """Compute-once value memoised as an attribute on ``fn`` itself."""
- value = getattr(fn, attr, None)
- if value is None:
- value = compute()
- with contextlib.suppress(AttributeError): # pragma: no cover - defensive
- setattr(fn, attr, value)
- return value
+def _backend_id_for_this_process() -> str:
+ """Stable identity for this process's heartbeat row: pid (readability) AND a startup nonce so a PID-reuse
+ respawn cannot inherit the dead predecessor's heartbeat."""
+ return f"{_current_profile_name()}@{_reaper_hostname()}:{os.getpid()}:{_BACKEND_NONCE}"
-def _backend_id_for_this_process() -> str:
- """Stable identity for this process's heartbeat row: pid (readability) AND a startup nonce so a
- PID-reuse respawn cannot inherit the dead predecessor's heartbeat."""
- import secrets as _secrets
- nonce = _reaper_memo(_backend_id_for_this_process, "_nonce", lambda: _secrets.token_hex(4))
- return f"{_current_profile_name()}@{_reaper_hostname()}:{os.getpid()}:{nonce}"
+def _gateway_started_at() -> float:
+ """Wall-clock time this process started (first-call time is a good-enough proxy: the heartbeat refresher
+ runs after the gateway is fully wired up)."""
+ if getattr(_gateway_started_at, "_t", None) is None:
+ _gateway_started_at._t = time.time()
+ return _gateway_started_at._t
def _refresh_backend_heartbeat() -> None:
@@ -353,26 +332,10 @@ def _refresh_backend_heartbeat() -> None:
logger.debug("backend heartbeat refresh failed", exc_info=True)
-def _gateway_started_at() -> float:
- """Wall-clock time this process started (first-call time is a good-enough proxy: the heartbeat
- refresher runs after the gateway is fully wired up)."""
- return _reaper_memo(_gateway_started_at, "_t", time.time)
-
-
-def _heartbeat_refresher_loop(stop_event: threading.Event) -> None:
- """Background loop that refreshes the heartbeat on a fixed cadence."""
- while not stop_event.is_set():
- try:
- _refresh_backend_heartbeat()
- except Exception:
- logger.debug("heartbeat refresh loop iteration failed", exc_info=True)
- stop_event.wait(_HEARTBEAT_REFRESH_S)
-
-
def _start_backend_heartbeat_refresher() -> None:
- """Register this backend and start the refresher thread (once per process). The first refresh
- writes the row synchronously so this process's own sweep sees itself in the heartbeat table.
- ``_HEARTBEAT_REFRESH_S <= 0`` means "register once, never refresh"."""
+ """Register this backend and start the refresher thread (once per process). The first refresh writes the row
+ synchronously so this process's own sweep sees itself in the heartbeat table. ``_HEARTBEAT_REFRESH_S <= 0``
+ means "register once, never refresh"."""
global _heartbeat_refresher_started
with _heartbeat_refresher_lock:
if _heartbeat_refresher_started:
@@ -386,6 +349,14 @@ def _start_backend_heartbeat_refresher() -> None:
return
stop_event = threading.Event()
+ def _loop() -> None:
+ while not stop_event.is_set():
+ try:
+ _refresh_backend_heartbeat()
+ except Exception:
+ logger.debug("heartbeat refresh loop iteration failed", exc_info=True)
+ stop_event.wait(_HEARTBEAT_REFRESH_S)
+
def _atexit_clear():
stop_event.set()
with contextlib.suppress(Exception):
@@ -393,15 +364,13 @@ def _start_backend_heartbeat_refresher() -> None:
db.clear_backend_heartbeat(_backend_id_for_this_process())
atexit.register(_atexit_clear)
- threading.Thread(
- target=_heartbeat_refresher_loop, args=(stop_event,), name="hermes-gateway-heartbeat", daemon=True
- ).start()
+ threading.Thread(target=_loop, name="hermes-gateway-heartbeat", daemon=True).start()
def _schedule_startup_orphan_sweep() -> None:
- """Schedule the once-per-process startup orphan sweep, delayed by the WS-orphan grace window so
- a client reconnecting right after a restart can ``session.resume`` its row first. Grace 0 (park
- forever), TTL 0 and ``dashboard.startup_orphan_sweep: false`` all suppress the sweep."""
+ """Schedule the once-per-process startup orphan sweep, delayed by the WS-orphan grace window so a client
+ reconnecting right after a restart can ``session.resume`` its row first. Grace 0 (park forever), TTL 0 and
+ ``dashboard.startup_orphan_sweep: false`` all suppress the sweep."""
global _startup_orphan_sweep_ran
if _WS_ORPHAN_REAP_GRACE_S <= 0 or _SESSION_TTL_S <= 0 or not _session_orphan_reaper_enabled():
return
@@ -414,5 +383,5 @@ def _schedule_startup_orphan_sweep() -> None:
def register(server) -> None:
- """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ """Publish this module's helpers onto ``server``, rebound to its globals."""
bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 77272846f87..f29b64caa95 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -1,8 +1,6 @@
-"""Session working-directory + durable session row: cwd resolution/healing, session.db row
-ensure, branch seed, history rewind, git meta persistence.
-
-Bodies are rebound onto server.py's globals at install time (method_ctx.bind_module),
-so they reference server.py globals bare.
+"""Session working-directory + durable session row: cwd resolution/healing, session.db row ensure,
+branch seed, history rewind, git meta persistence. Bodies are rebound onto server.py's globals at
+install time (method_ctx.bind_module), so they reference server.py globals bare.
"""
from __future__ import annotations
@@ -10,9 +8,7 @@ from __future__ import annotations
import contextlib
from tui_gateway import git_probe
-from .method_ctx import HandlerRegistry, bind_module
-
-_registry = HandlerRegistry()
+from .method_ctx import bind_module
def _normalize_completion_path(path_part: str) -> str:
@@ -29,11 +25,10 @@ def _completion_cwd(params: dict | None = None) -> str:
raw = (
params.get("cwd")
or _sessions.get(params.get("session_id") or "", {}).get("cwd")
- # A session bound to another profile resolves its workspace from THAT
- # profile's config before falling back to the launch profile's env var.
+ # A session bound to another profile resolves its workspace from THAT profile's config before the
+ # launch profile's env var; the dashboard's in-memory gateway does NOT inherit the PTY child's bridged
+ # TERMINAL_CWD, so a configured terminal.cwd is read directly.
or _profile_configured_cwd(_profile_home(params.get("profile")))
- # The dashboard's in-memory gateway does NOT inherit the PTY child's
- # bridged TERMINAL_CWD, so a configured terminal.cwd is read directly.
or _launch_configured_cwd()
or os.environ.get("TERMINAL_CWD")
or os.getcwd())
@@ -54,16 +49,15 @@ def _workdir_terminal_cfg(key: str) -> str:
def _terminal_task_cwd(session: dict | None) -> str:
- """The cwd terminal_tool should use for this TUI session (NOT host-validated, unlike
- ``_completion_cwd``: a non-local backend's cwd lives inside the target environment)."""
+ """The cwd terminal_tool should use for this TUI session (NOT host-validated, unlike ``_completion_cwd``:
+ a non-local backend's cwd lives inside the target environment)."""
return _terminal_task_cwd_with_source(session)[0]
def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:
- """``(cwd, source)``: ``"session"`` for THIS session's workspace (``explicit_cwd``/tracked
- dir), ``"process"`` for the process-global ``TERMINAL_CWD`` / ``terminal.cwd`` fallback —
- under per-session docker isolation that is a launch artifact of a PREVIOUS session, so
- terminal_tool refuses it as a bind-mount source."""
+ """``(cwd, source)``: ``"session"`` for THIS session's workspace (``explicit_cwd``/tracked dir), ``"process"``
+ for the process-global ``TERMINAL_CWD`` / ``terminal.cwd`` fallback — under per-session docker isolation
+ that is a launch artifact of a PREVIOUS session, so terminal_tool refuses it as a bind-mount source."""
backend = _effective_terminal_backend()
if backend != "local":
# THIS session's explicit workspace beats the LAST session's env var.
@@ -80,7 +74,6 @@ def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:
# Git probing lives in git_probe; these keep the in-server names call sites use.
-_git = git_probe.run_git
_git_branch_for_cwd = git_probe.branch
_git_repo_root_for_cwd = git_probe.repo_root
_git_common_repo_root_for_cwd = git_probe.common_repo_root
@@ -91,8 +84,8 @@ def _session_cwd(session: dict | None) -> str:
return str(session["cwd"]) if session and session.get("cwd") else _completion_cwd()
-# Sources whose launch directory is an artifact of how the app was started, not
-# a workspace the user picked (everything else is a directory the user cd'd into).
+# Sources whose launch directory is an artifact of how the app was started, not a workspace the user picked
+# (everything else is a directory the user cd'd into).
_LAUNCH_CWD_NOT_A_WORKSPACE = {"desktop"}
@@ -102,21 +95,20 @@ def _context_cwd_is_launch_artifact(session: dict | None) -> bool:
def _persisted_session_cwd(session: dict) -> str | None:
- """The cwd to stamp on the session's DB row, or None to leave it unset (see
- :func:`_ensure_session_db_row` for the desktop vs terminal launch-dir rule)."""
+ """The cwd to stamp on the session's DB row, or None to leave it unset (see :func:`_ensure_session_db_row`
+ for the desktop vs terminal launch-dir rule)."""
if session.get("explicit_cwd"):
return _session_cwd(session)
if _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE:
return None
- # Only the session's OWN directory, never `_session_cwd`'s gateway-wide fallback.
- return str(session.get("cwd") or "") or None
+ return str(session.get("cwd") or "") or None # the session's OWN dir, never _session_cwd's gateway-wide fallback
def _heal_dead_cwd(cwd: str) -> str:
- """Resolve a session cwd inside a now-deleted directory (e.g. a removed linked worktree,
- which probes to no branch while the sidebar folds it to the main lane): walk up to the first
- existing ancestor and take its common git root. Local backends only — a remote/SSH cwd may
- legitimately not exist on the host, so callers skip healing there."""
+ """Resolve a session cwd inside a now-deleted directory (e.g. a removed linked worktree, which probes to no
+ branch while the sidebar folds it to the main lane): walk up to the first existing ancestor and take its
+ common git root. Local backends only — a remote/SSH cwd may legitimately not exist on the host, so callers
+ skip healing there."""
raw = (cwd or "").strip()
if not raw or os.path.isdir(raw):
return raw
@@ -141,9 +133,9 @@ def _is_local_terminal_backend() -> bool:
def _effective_terminal_backend() -> str:
- """Active terminal backend name (``local``, ``docker``, ``ssh``, ...): ``TERMINAL_ENV`` when
- set (launchers bridge ``terminal.backend`` into env), else the ``terminal.backend`` config
- key (desktop/TUI in-process gateways skip that bridge)."""
+ """Active terminal backend name (``local``, ``docker``, ``ssh``, ...): ``TERMINAL_ENV`` when set (launchers
+ bridge ``terminal.backend`` into env), else the ``terminal.backend`` config key (desktop/TUI in-process
+ gateways skip that bridge)."""
backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
if not backend or backend == "local":
cfg_backend = _workdir_terminal_cfg("backend").lower()
@@ -153,8 +145,8 @@ def _effective_terminal_backend() -> str:
def _display_session_cwd(session: dict | None) -> str:
- """Session cwd for display/probe surfaces, healed past deleted worktrees;
- the healed value is persisted back (best-effort, local only)."""
+ """Session cwd for display/probe surfaces, healed past deleted worktrees; the healed value is persisted
+ back (best-effort, local only)."""
cwd = _session_cwd(session)
if not _is_local_terminal_backend():
return cwd
@@ -166,17 +158,16 @@ def _display_session_cwd(session: dict | None) -> str:
def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:
- """Re-anchor a session that SETTLED in another worktree of the SAME repo. Returns moved.
-
- An agent told to work in a fresh worktree `git worktree add`s and `cd`s in while the session
- stays pinned (labelled with the primary checkout's branch). A plain `cd` is deliberately NOT
- a workspace move (see ``_apply_project_workspace``): a non-git workspace stepping into a repo
- or a visit to an unrelated repo is browsing, and an explicitly chosen workspace is never
- overridden. Local backends only (a remote cwd cannot be stat'ed or git-probed here)."""
+ """Re-anchor a session that SETTLED in another worktree of the SAME repo. Returns moved. An agent told to
+ work in a fresh worktree `git worktree add`s and `cd`s in while the session stays pinned (labelled with the
+ primary checkout's branch). A plain `cd` is deliberately NOT a workspace move (see
+ ``_apply_project_workspace``): a non-git workspace stepping into a repo or a visit to an unrelated repo is
+ browsing, and an explicitly chosen workspace is never overridden. Local backends only (a remote cwd cannot
+ be stat'ed or git-probed here)."""
if not session or not _is_local_terminal_backend():
return False
- # An explicit choice only moves by another explicit action; a cwd adopted
- # HERE is marked `cwd_from_settle` so successive settles keep following.
+ # An explicit choice only moves by another explicit action; a cwd adopted HERE is marked `cwd_from_settle`
+ # so successive settles keep following.
if session.get("explicit_cwd") and not session.get("cwd_from_settle"):
return False
try:
@@ -190,8 +181,8 @@ def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:
current = os.path.abspath(os.path.expanduser(_session_cwd(session)))
if resolved == current or not os.path.isdir(resolved):
return False
- # Worktree ROOTS (folding to the common root would hide the move), both in a git
- # tree, different from each other, sharing the SAME common .git dir.
+ # Worktree ROOTS (folding to the common root would hide the move), both in a git tree, different from each
+ # other, sharing the SAME common .git dir.
landed = _git_repo_root_for_cwd(resolved)
current_root = _git_repo_root_for_cwd(current)
if not landed or not current_root or landed == current_root:
@@ -199,19 +190,17 @@ def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:
landed_common = _git_common_repo_root_for_cwd(resolved)
if not landed_common or landed_common != _git_common_repo_root_for_cwd(current):
return False
- session["cwd"] = resolved
- # This is the session's workspace now (a desktop launch-artifact cwd earns
- # a real row); the settle marker keeps it overridable by the NEXT settle.
- session["explicit_cwd"] = True
- session["cwd_from_settle"] = True
+ # This is the session's workspace now (a desktop launch-artifact cwd earns a real row); the settle marker
+ # keeps it overridable by the NEXT settle.
+ session.update(cwd=resolved, explicit_cwd=True, cwd_from_settle=True)
_register_session_cwd(session)
_persist_session_cwd_and_schedule_git_meta(session, resolved)
return True
def _emit_settled_session_info(sid: str, session: dict, agent) -> None:
- """Emit end-of-turn ``session.info``, reconciling a settled cwd first: the agent has stopped
- moving, and riding the reconcile on the turn-end event needs no new event type/round trip."""
+ """Emit end-of-turn ``session.info``, reconciling a settled cwd first: the agent has stopped moving, and
+ riding the reconcile on the turn-end event needs no new event type/round trip."""
try:
_reconcile_session_cwd_from_terminal(session)
except Exception:
@@ -234,19 +223,18 @@ def _register_session_cwd(session: dict | None) -> None:
def _workdir_row_model_config(session: dict) -> tuple[str, dict]:
- """``(model, model_config)`` for a fresh session row.
-
- The session's own model/effort/fast pick (composer override or restored /model switch) must
- own the row: the agent isn't built yet at first prompt.submit, and writing the global default
- here wins the INSERT-OR-IGNORE race, so a reconnect silently reverts to the profile default.
- model_config carries provider/reasoning/service_tier so resume restores effort + fast too."""
+ """``(model, model_config)`` for a fresh session row. The session's own model/effort/fast pick (composer
+ override or restored /model switch) must own the row: the agent isn't built yet at first prompt.submit,
+ and writing the global default here wins the INSERT-OR-IGNORE race, so a reconnect silently reverts to
+ the profile default. model_config carries provider/reasoning/service_tier so resume restores effort +
+ fast too."""
override = session.get("model_override")
override = override if isinstance(override, dict) else {}
row_model = str(override.get("model") or "").strip() or _resolve_model()
model_config: dict = {k: str(v) for k in ("model", "provider", "base_url", "api_mode") if (v := override.get(k))}
- # A RESOLVED provider "custom" (named ``providers:``/``custom_providers:`` entry) persisted
- # bare here is the origin of "No LLM provider configured" rows (resume routes to OpenRouter
- # with no key). Recover the durable ``custom:<name>`` identity (matches _runtime_model_config).
+ # A RESOLVED provider "custom" (named ``providers:``/``custom_providers:`` entry) persisted bare here is the
+ # origin of "No LLM provider configured" rows (resume routes to OpenRouter with no key). Recover the
+ # durable ``custom:<name>`` identity (matches _runtime_model_config).
if str(model_config.get("provider") or "").strip().lower() == "custom":
try:
from hermes_cli.runtime_provider import canonical_custom_identity
@@ -259,15 +247,15 @@ def _workdir_row_model_config(session: dict) -> tuple[str, dict]:
if (reasoning := session.get("create_reasoning_override")) is not None:
model_config["reasoning_config"] = reasoning
if (service_tier := session.get("create_service_tier_override")) is not None:
- # "" is the in-memory sentinel for an explicit normal tier (bypasses _make_agent's profile
- # fallback); persist a durable marker so resume can tell it from an inherited tier.
+ # "" is the in-memory sentinel for an explicit normal tier (bypasses _make_agent's profile fallback);
+ # persist a durable marker so resume can tell it from an inherited tier.
model_config["service_tier"] = service_tier or "normal"
# Same ``_branched_from`` marker the TUI /branch uses (list_sessions_rich + sidebar nesting).
if parent_session_id := session.get("parent_session_id"):
model_config["_branched_from"] = parent_session_id
- # Bot-Mode canonical chats / room plumbing are plugin-owned scratch conversations whose runtime
- # must ALWAYS follow the member profile's CURRENT config, never the provider pinned at first
- # write; persist that contract for resume (see _stored_session_runtime_overrides).
+ # Bot-Mode canonical chats / room plumbing are plugin-owned scratch conversations whose runtime must ALWAYS
+ # follow the member profile's CURRENT config, never the provider pinned at first write; persist that
+ # contract for resume (see _stored_session_runtime_overrides).
for flag in ("room_plumbing", "follow_profile_config"):
if session.get(flag):
model_config[flag] = True
@@ -275,50 +263,46 @@ def _workdir_row_model_config(session: dict) -> tuple[str, dict]:
def _ensure_session_db_row(session: dict) -> bool:
- """Idempotently persist the session's DB row on first real activity (prompt.submit), so
- abandoned drafts never leave an empty "Untitled" session. INSERT OR IGNORE: re-calls and the
- AIAgent's lazy create are no-ops. Returns False only when the store is unavailable (no
- openable state.db) — prompt.submit fails the send loudly instead of streaming into a store
- that will never save it; no key / best-effort / success are all True.
-
- A cwd the user *chose* is always persisted. Otherwise the launch directory stands in only for
- terminal sessions (the user deliberately ``cd``'d there; dropping it left the sidebar with no
- cwd AND no git_repo_root); desktop launch dirs (``/``, home) stay null -> "No workspace"."""
+ """Idempotently persist the session's DB row on first real activity (prompt.submit), so abandoned drafts
+ never leave an empty "Untitled" session. INSERT OR IGNORE: re-calls and the AIAgent's lazy create are
+ no-ops. Returns False only when the store is unavailable (no openable state.db) — prompt.submit fails the
+ send loudly instead of streaming into a store that will never save it; no key / best-effort / success are
+ all True.
+
+ A cwd the user *chose* is always persisted. Otherwise the launch directory stands in only for terminal
+ sessions (the user deliberately ``cd``'d there; dropping it left the sidebar with no cwd AND no
+ git_repo_root); desktop launch dirs (``/``, home) stay null -> "No workspace"."""
key = session.get("session_key")
if not key:
return
- # Persist into the session's own profile db (global remote mode), not the launch profile's —
- # otherwise the unified list mis-tags the row and resume 404s ("session not found").
+ # Persist into the session's own profile db (global remote mode), not the launch profile's — otherwise the
+ # unified list mis-tags the row and resume 404s ("session not found").
profile_home = session.get("profile_home")
with _workdir_owner_db(session, "failed to open profile db for session row") as db:
if db is _WORKDIR_DB_OPEN_FAILED:
return False
if db is None:
- # Fail loud ONLY when the store failed to open (_db_error records the SessionDB open
- # exception); None with no recorded error means "no store in this context" -> True.
+ # Fail loud ONLY when the store failed to open (_db_error records the SessionDB open exception);
+ # None with no recorded error means "no store in this context" -> True.
return _db_error is None
row_model, model_config = _workdir_row_model_config(session)
try:
db.create_session(
- key,
- source=_session_source(session),
- model=row_model,
- model_config=model_config or None,
- parent_session_id=session.get("parent_session_id") or None,
- cwd=_persisted_session_cwd(session),
- # Self-describing rows: aggregators merging several profile DBs can't rely on
- # which file a row came from; a NULL is only repaired by the one-shot backfill.
+ key, source=_session_source(session), model=row_model, model_config=model_config or None,
+ parent_session_id=session.get("parent_session_id") or None, cwd=_persisted_session_cwd(session),
+ # Self-describing rows: aggregators merging several profile DBs can't rely on which file a row
+ # came from; a NULL is only repaired by the one-shot backfill.
profile_name=Path(profile_home).name if profile_home else _current_profile_name())
- # Born hidden (session.create hidden=true, or set_hidden before the
- # row existed): apply the deferred intent now, like pending_title.
+ # Born hidden (session.create hidden=true, or set_hidden before the row existed): apply the
+ # deferred intent now, like pending_title.
if session.get("pending_hidden"):
try:
db.set_session_hidden(key, True)
except Exception:
logger.debug("failed to apply pending hidden flag", exc_info=True)
except Exception as exc:
- # Disk-full is not a soft failure: swallowed here, prompt.submit
- # returns {"status":"streaming"} and the message vanishes silently.
+ # Disk-full is not a soft failure: swallowed here, prompt.submit returns {"status":"streaming"} and
+ # the message vanishes silently.
_workdir_reraise_disk_full(exc, "failed to persist desktop session row")
return True
@@ -331,25 +315,21 @@ def _workdir_reraise_disk_full(exc: BaseException, log_msg: str) -> None:
logger.debug(log_msg, exc_info=True)
-# Seed row fields copied from the parent transcript. display_kind/metadata: timeline markers
-# ride as role=user, dropping the tag re-plants them as bare user turns after a restart and
-# corrupts the truncate ordinal address space. timestamp: parent's original, not "now".
+# Seed row fields copied from the parent transcript. display_kind/metadata: timeline markers ride as role=user,
+# dropping the tag re-plants them as bare user turns after a restart and corrupts the truncate ordinal address
+# space. timestamp: parent's original, not "now".
_WORKDIR_SEED_FIELDS = (
"content", "reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items",
- "codex_message_items", "display_kind", "display_metadata", "timestamp",
-)
+ "codex_message_items", "display_kind", "display_metadata", "timestamp")
def _persist_branch_seed(session: dict) -> None:
- """First-turn persist of a branch's copied transcript. A branch is a draft until its first
- submit: the parent's messages live only in ``session["history"]`` (ridden into the agent as
- ``conversation_history``, which ``_flush_messages_to_session_db`` skips by identity), so the
- row would otherwise resume missing its pre-branch context. Runs once, after
- ``_ensure_session_db_row`` wrote the row + parent link."""
- if not session.get("parent_session_id") or session.get("_branch_seed_persisted"):
- return
+ """First-turn persist of a branch's copied transcript. A branch is a draft until its first submit: the
+ parent's messages live only in ``session["history"]`` (ridden into the agent as ``conversation_history``,
+ which ``_flush_messages_to_session_db`` skips by identity), so the row would otherwise resume missing its
+ pre-branch context. Runs once, after ``_ensure_session_db_row`` wrote the row + parent link."""
key = session.get("session_key")
- if not key:
+ if not key or not session.get("parent_session_id") or session.get("_branch_seed_persisted"):
return
with session["history_lock"]:
seed = [dict(msg) for msg in (session.get("history") or [])]
@@ -359,8 +339,8 @@ def _persist_branch_seed(session: dict) -> None:
if db is None:
return
try:
- # Chunked so each BEGIN IMMEDIATE stays short (a seed can be hundreds of rows); a
- # mid-copy failure leaves a partial seed with _branch_seed_persisted unset.
+ # Chunked so each BEGIN IMMEDIATE stays short (a seed can be hundreds of rows); a mid-copy failure
+ # leaves a partial seed with _branch_seed_persisted unset.
db.append_messages_batch(
key,
[{"role": msg.get("role", "user"), **{f: msg.get(f) for f in _WORKDIR_SEED_FIELDS}} for msg in seed],
@@ -370,15 +350,15 @@ def _persist_branch_seed(session: dict) -> None:
_workdir_reraise_disk_full(exc, "branch seed persist failed")
-# Yielded by _workdir_owner_db when the profile db failed to OPEN (as opposed
-# to "no store in this context"); _ensure_session_db_row fails loud on it.
+# Yielded by _workdir_owner_db when the profile db failed to OPEN (as opposed to "no store in this context");
+# _ensure_session_db_row fails loud on it.
_WORKDIR_DB_OPEN_FAILED = object()
@contextlib.contextmanager
def _workdir_owner_db(session: dict, fail_log: str):
- """Body of :func:`_session_db`; also used directly by ``_ensure_session_db_row``
- so a test-patched ``_session_db`` does not change row creation."""
+ """Body of :func:`_session_db`; also used directly by ``_ensure_session_db_row`` so a test-patched
+ ``_session_db`` does not change row creation."""
db, close_db = None, False
profile_home = session.get("profile_home")
if profile_home:
@@ -401,9 +381,9 @@ def _workdir_owner_db(session: dict, fail_log: str):
@contextlib.contextmanager
def _session_db(session: dict):
- """Yield the SessionDB that owns this session's row (profile-aware): a remote/profile session
- persists into its own profile's ``state.db`` (fresh handle, closed on exit); everything else
- borrows the shared ``_get_db()`` handle (left open). Yields None when unavailable."""
+ """Yield the SessionDB that owns this session's row (profile-aware): a remote/profile session persists into
+ its own profile's ``state.db`` (fresh handle, closed on exit); everything else borrows the shared
+ ``_get_db()`` handle (left open). Yields None when unavailable."""
with _workdir_owner_db(session, "failed to open profile db for session") as db:
yield None if db is _WORKDIR_DB_OPEN_FAILED else db
@@ -411,19 +391,16 @@ def _session_db(session: dict):
def _rewind_active_session_history(
session: dict, user_ordinal: int, *, require_retryable: bool = False
) -> tuple[list[dict], dict, int]:
- """Rewind one canonical user turn while retaining carrier scaffolding.
-
- Caller holds ``history_lock``. Persistent sessions archive the target and tail, inserting a
- composite carrier's hidden handoff in the same transaction; memory is installed only after
- the durable commit, from the already-validated prefix plus the returned scaffold row id
- (no fallible post-commit reload)."""
+ """Rewind one canonical user turn while retaining carrier scaffolding. Caller holds ``history_lock``.
+ Persistent sessions archive the target and tail, inserting a composite carrier's hidden handoff in the
+ same transaction; memory is installed only after the durable commit, from the already-validated prefix
+ plus the returned scaffold row id (no fallible post-commit reload)."""
from agent.context_compressor import (
- history_before_user_originated_turn,
- retryable_user_text,
- split_user_originated_turn,
+ history_before_user_originated_turn, retryable_user_text, split_user_originated_turn,
user_originated_turn_view)
from agent.memory_manager import sanitize_context
from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
+
def _comparison_content(message: dict) -> Any:
content = message.get("content")
if _is_multimodal_tool_result(content):
@@ -472,24 +449,22 @@ def _rewind_active_session_history(
retryable_user_text(durable_live_view.get("content"))
scaffold, _ = split_user_originated_turn(durable_target)
result = db.rewind_to_message(
- session_key, target_row_id,
- preserve_compaction_handoff=scaffold is not None,
- expected_active_ids=expected_active_ids,
- expected_target_content=durable_live_view.get("content"))
+ session_key, target_row_id, preserve_compaction_handoff=scaffold is not None,
+ expected_active_ids=expected_active_ids, expected_target_content=durable_live_view.get("content"))
if scaffold is not None:
replacement_id = result.get("replacement_message_id")
if not isinstance(replacement_id, int):
raise RuntimeError("rewind commit did not return the replacement scaffold id")
- durable_prefix[-1]["_row_id"] = replacement_id
- durable_prefix[-1]["_db_persisted"] = True
+ durable_prefix[-1].update(_row_id=replacement_id, _db_persisted=True)
installed[-1] = durable_prefix[-1]
- # Clients address follow-ups by durable row id: keep the richer warm
- # content but copy row identities when the shapes align.
+ # Clients address follow-ups by durable row id: keep the richer warm content but copy row
+ # identities when the shapes align.
if len(installed) == len(durable_prefix) and all(
warm.get("role") == durable_message.get("role")
and bool(warm.get("display_kind")) == bool(durable_message.get("display_kind"))
and _comparison_content(warm) == _comparison_content(durable_message)
- for warm, durable_message in zip(installed, durable_prefix)):
+ for warm, durable_message in zip(installed, durable_prefix)
+ ):
for warm, durable_message in zip(installed, durable_prefix):
if isinstance(row_id := durable_message.get("_row_id"), int):
warm["_row_id"] = row_id
@@ -524,10 +499,10 @@ def _workdir_valid_generation(generation) -> bool:
def _persist_session_git_meta(session: dict, cwd: str, generation: int) -> None:
- """Resolve + persist a session's git branch / repo root on a daemon thread: inline ``git``
- probes on the session-init / cwd-set path would stall startup on a slow or unreachable
- ``cwd``. Persists via the same profile-aware db the caller wrote ``cwd`` to. Best-effort: a
- probe failure leaves the enrichment columns unset (project tree uses its live resolver)."""
+ """Resolve + persist a session's git branch / repo root on a daemon thread: inline ``git`` probes on the
+ session-init / cwd-set path would stall startup on a slow or unreachable ``cwd``. Persists via the same
+ profile-aware db the caller wrote ``cwd`` to. Best-effort: a probe failure leaves the enrichment columns
+ unset (project tree uses its live resolver)."""
session_key = session.get("session_key", "")
if not session_key or not cwd or not _workdir_valid_generation(generation):
return
@@ -571,14 +546,11 @@ def _set_session_cwd(session: dict, cwd: str) -> str:
resolved = os.path.abspath(os.path.expanduser(cwd))
if not os.path.isdir(resolved):
raise ValueError(f"working directory does not exist: {cwd}")
- session["cwd"] = resolved
- # An explicit user choice: persisted as the workspace (not the launch-dir
- # fallback) and superseding any settle-adopted cwd.
- session["explicit_cwd"] = True
- session["cwd_from_settle"] = False
+ # An explicit user choice: persisted as the workspace (not the launch-dir fallback) and superseding any
+ # settle-adopted cwd.
+ session.update(cwd=resolved, explicit_cwd=True, cwd_from_settle=False)
_register_session_cwd(session)
- # The synchronous DB write claims ordering authority; git probes may
- # publish only for that exact generation.
+ # The synchronous DB write claims ordering authority; git probes may publish only for that exact generation.
_persist_session_cwd_and_schedule_git_meta(session, resolved)
with contextlib.suppress(Exception):
from tools.terminal_tool import cleanup_vm
@@ -587,5 +559,5 @@ def _set_session_cwd(session: dict, cwd: str) -> str:
def register(server) -> None:
- """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ """Publish this module's helpers onto ``server``, rebound to its globals."""
bind_module(globals(), server, skip=("_",))