Skip to content

The agent that grows with you

refactor(tui): split compute-host bridge, session workdir/db-row, and session lifecycle out of server.py

Tekniumc6011955df95
diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.py
new file mode 100644
index 00000000000..40cbd513c74
--- /dev/null
+++ b/tui_gateway/compute_host_bridge.py
@@ -0,0 +1,373 @@
+"""Compute-host (turn isolation) bridge: relay prompts/controls to the per-session child process and mirror its metadata/clarify/compress acks back into the session.
+
+Bodies are rebound onto server.py's globals at install time (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+from __future__ import annotations
+
+import threading
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+
+_compute_host_supervisor = None
+_compute_host_supervisor_lock = threading.Lock()
+# Hard cap on how long session.compress blocks its RPC waiting for the compute
+# host (#97948). Must stay below the desktop's SESSION_COMPRESS_TIMEOUT_MS
+# (660s) so the client receives the `pending` answer instead of its own
+# timeout error; the late-ack path covers anything slower.
+_COMPUTE_HOST_COMPRESS_WAIT_CAP_SECS = 630.0
+
+
+def _inside_compute_host_child() -> bool:
+ return os.environ.get("HERMES_COMPUTE_HOST_CHILD") == "1"
+
+
+def _turn_isolation_enabled(cfg: dict | None = None) -> bool:
+ if _inside_compute_host_child():
+ return False
+ isolation_cfg = cfg or _load_dashboard_process_isolation_config()
+ return bool(isolation_cfg.get("turn_isolation"))
+
+
+def _session_uses_compute_host(session: dict, cfg: dict | None = None) -> bool:
+ if not _turn_isolation_enabled(cfg):
+ return False
+ # Phase 1 routes lazy/dashboard sessions whose live AIAgent has not been
+ # built inside the serving process. Already-built in-process sessions keep
+ # the historical path unless a prior isolated turn marked host ownership.
+ return bool(session.get("_compute_host_active")) or (
+ session.get("agent") is None and session.get("agent_ready") is not None
+ )
+
+
+def _get_compute_host_supervisor(cfg: dict | None = None):
+ global _compute_host_supervisor
+ isolation_cfg = cfg or _load_dashboard_process_isolation_config()
+ with _compute_host_supervisor_lock:
+ if _compute_host_supervisor is None:
+ from tui_gateway.host_supervisor import HostSupervisor
+
+ _compute_host_supervisor = HostSupervisor(
+ rpc_sink=_relay_compute_host_rpc,
+ heartbeat_secs=int(isolation_cfg.get("compute_host_heartbeat_secs") or 15),
+ respawn_max=int(isolation_cfg.get("compute_host_respawn_max") or 3),
+ )
+ return _compute_host_supervisor
+
+
+def _compute_host_turn_frame(
+ rid: str,
+ sid: str,
+ session: dict,
+ text: Any,
+ image_paths: list[str] | None = None,
+ queued_prompt_generation: int | None = None,
+ display_kind: str | None = None,
+) -> dict:
+ with session["history_lock"]:
+ history = list(session.get("history", []))
+ history_version = int(session.get("history_version", 0))
+ attached_images = (
+ list(image_paths)
+ if image_paths is not None
+ else list(session.get("attached_images", []))
+ )
+ return {
+ "type": "turn.start",
+ "sid": sid,
+ "request_id": rid,
+ "session_key": session.get("session_key") or sid,
+ "text": text,
+ **({"display_kind": display_kind} if display_kind else {}),
+ "history": history,
+ "history_version": history_version,
+ "cols": int(session.get("cols", 80) or 80),
+ "cwd": _session_cwd(session),
+ "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(session),
+ "profile_home": session.get("profile_home") or "",
+ "model_override": session.get("model_override"),
+ "reasoning_config_override": session.get("create_reasoning_override"),
+ "service_tier_override": session.get("create_service_tier_override"),
+ "source": _session_source(session),
+ "attached_images": attached_images,
+ "queued_prompt_generation": queued_prompt_generation,
+ }
+
+
+def _metadata_mirror(session: dict | None) -> dict:
+ mirror = (session or {}).get("_metadata_mirror")
+ return mirror if isinstance(mirror, dict) else {}
+
+
+def _relay_compute_host_rpc(message: dict) -> bool:
+ """Relay host events while retaining the clarify snapshot needed on resume."""
+ params = message.get("params") if isinstance(message, dict) else None
+ if isinstance(params, dict) and params.get("type") == "clarify.request":
+ sid = str(params.get("session_id") or "")
+ payload = params.get("payload")
+ session = _sessions.get(sid)
+ if session is not None and isinstance(payload, dict) and payload.get("request_id"):
+ with session.get("history_lock", threading.Lock()):
+ session["_compute_host_pending_clarify"] = dict(payload)
+ elif isinstance(params, dict) and params.get("type") == "clarify.expire":
+ sid = str(params.get("session_id") or "")
+ payload = params.get("payload")
+ session = _sessions.get(sid)
+ request_id = payload.get("request_id") if isinstance(payload, dict) else None
+ if session is not None and request_id:
+ with session.get("history_lock", threading.Lock()):
+ pending = session.get("_compute_host_pending_clarify")
+ if isinstance(pending, dict) and pending.get("request_id") == request_id:
+ session.pop("_compute_host_pending_clarify", None)
+ return write_json(message)
+
+
+def _compute_host_clarify_session(request_id: str) -> tuple[str, dict] | None:
+ """Find the parent mirror for one host-owned clarify request."""
+ if not request_id:
+ return None
+ for sid, session in list(_sessions.items()):
+ with session.get("history_lock", threading.Lock()):
+ pending = session.get("_compute_host_pending_clarify")
+ if isinstance(pending, dict) and pending.get("request_id") == request_id:
+ return sid, session
+ return None
+
+
+def _update_compute_host_clarify_snapshot(sid: str, session: dict, params: dict, result: dict) -> None:
+ """Keep reconnect snapshots accurate while a batch clarify is answered."""
+ request_id = str(params.get("request_id") or "")
+ with session.get("history_lock", threading.Lock()):
+ pending = session.get("_compute_host_pending_clarify")
+ if not isinstance(pending, dict) or pending.get("request_id") != request_id:
+ return
+ if result.get("status") == "expired" or not result.get("remaining") and not params.get("question_id"):
+ session.pop("_compute_host_pending_clarify", None)
+ return
+ question_id = str(params.get("question_id") or "")
+ if question_id and isinstance(result.get("remaining"), list):
+ answers = dict(pending.get("answers") or {})
+ answers[question_id] = str(params.get("answer") or "")
+ pending["answers"] = answers
+ if not result["remaining"]:
+ session.pop("_compute_host_pending_clarify", None)
+
+
+def _respond_compute_host_clarify(rid: str, params: dict) -> dict | None:
+ """Proxy a clarify answer into the process that owns its pending Event."""
+ located = _compute_host_clarify_session(str(params.get("request_id") or ""))
+ if located is None:
+ return None
+ sid, session = located
+ if not _session_uses_compute_host(session):
+ return None
+ try:
+ ack = _get_compute_host_supervisor().respond(sid, params)
+ except Exception as exc:
+ return _err(rid, 5019, f"compute-host clarify response failed: {exc}")
+ if ack.get("type") == "respond.error":
+ return _err(rid, 5019, str(ack.get("message") or "compute-host clarify response failed"))
+ response = ack.get("response")
+ if not isinstance(response, dict):
+ return _err(rid, 5019, "compute-host clarify response returned an invalid response")
+ if "error" in response:
+ error = response["error"] if isinstance(response["error"], dict) else {}
+ return _err(rid, int(error.get("code") or 5000), str(error.get("message") or "clarify response failed"))
+ result = response.get("result")
+ if not isinstance(result, dict):
+ return _err(rid, 5019, "compute-host clarify response returned an invalid result")
+ _update_compute_host_clarify_snapshot(sid, session, params, result)
+ return _ok(rid, result)
+
+
+def _apply_compute_host_metadata_mirror(session: dict, frame: dict | None) -> None:
+ """Mirror host-owned session metadata in the serving process.
+
+ The compute host is the only writer of live agent/history state while turn
+ isolation is active. The serving process keeps read metadata from the last
+ host frame so UI reads do not construct a second in-process agent.
+ """
+ if not isinstance(frame, dict):
+ return
+ with session.get("history_lock", threading.Lock()):
+ if frame.get("session_key"):
+ session["session_key"] = str(frame.get("session_key"))
+ if frame.get("history_version") is not None:
+ try:
+ session["history_version"] = max(
+ int(session.get("history_version", 0)),
+ int(frame.get("history_version") or 0),
+ )
+ except Exception:
+ pass
+ if frame.get("message_count") is not None:
+ try:
+ session["_metadata_message_count"] = int(frame.get("message_count") or 0)
+ except Exception:
+ pass
+ info = frame.get("session_info")
+ if isinstance(info, dict):
+ mirror = dict(_metadata_mirror(session))
+ mirror.update(info)
+ session["_metadata_mirror"] = mirror
+ session["_metadata_mirror_updated_at"] = time.time()
+
+
+def _on_compute_host_turn_done(rid: str, sid: str, session: dict, frame: dict) -> None:
+ is_error = frame.get("type") == "turn.error"
+ with session["history_lock"]:
+ if frame.get("session_key"):
+ session["session_key"] = str(frame.get("session_key"))
+ if frame.get("history_version") is not None:
+ try:
+ session["history_version"] = max(
+ int(session.get("history_version", 0)),
+ int(frame.get("history_version") or 0),
+ )
+ except Exception:
+ pass
+ session["running"] = False
+ session["last_active"] = time.time()
+ _clear_inflight_turn(session)
+ session.pop("_compute_host_pending_clarify", None)
+ if is_error:
+ message = str(frame.get("message") or "compute host turn failed")
+ _emit("message.complete", sid, {"text": f"Error: {message}", "status": "error"})
+ _apply_compute_host_metadata_mirror(session, frame)
+ try:
+ info = _session_info(session.get("agent"), session)
+ except TypeError:
+ info = _session_info(session.get("agent"))
+ if not frame.get("session_info_emitted"):
+ _emit("session.info", sid, info)
+ _drain_queued_prompt(rid, sid, session)
+
+
+def _submit_prompt_to_compute_host(
+ rid: str,
+ sid: str,
+ session: dict,
+ text: Any,
+ image_paths: list[str] | None = None,
+ queued_prompt_generation: int | None = None,
+ display_kind: str | None = None,
+) -> dict:
+ cfg = _load_dashboard_process_isolation_config()
+ frame = _compute_host_turn_frame(
+ rid,
+ sid,
+ session,
+ text,
+ image_paths=image_paths,
+ queued_prompt_generation=queued_prompt_generation,
+ display_kind=display_kind,
+ )
+
+ def _complete(done: dict) -> None:
+ # submit_turn reports a synchronous pipe failure through the callback
+ # before re-raising. Leave the parent session untouched so prompt.submit
+ # can fail open to the historical in-process path without emitting a
+ # duplicate terminal error.
+ if done.get("reason") == "send_failed":
+ return
+ _on_compute_host_turn_done(rid, sid, session, done)
+
+ try:
+ _get_compute_host_supervisor(cfg).submit_turn(frame, on_complete=_complete)
+ except Exception as exc:
+ return _err(rid, 5019, f"compute-host dispatch failed: {exc}")
+ with session["history_lock"]:
+ session["_compute_host_active"] = True
+ if image_paths is None:
+ session["attached_images"] = []
+ return _ok(rid, {"status": "streaming", "turn_isolation": True})
+
+
+def _send_compute_host_control(
+ sid: str,
+ *,
+ route_name: str,
+ command: str = "",
+ payload: dict | None = None,
+ wait: bool = True,
+ timeout: float = 30.0,
+ on_late_ack=None,
+) -> dict:
+ frame = dict(payload or {})
+ frame.setdefault("type", "control")
+ frame.setdefault("command", command)
+ return _get_compute_host_supervisor().control(
+ sid,
+ route_name=route_name,
+ payload=frame,
+ wait=wait,
+ timeout=timeout,
+ on_late_ack=on_late_ack,
+ )
+
+
+def _compute_host_compress_wait_seconds(cfg: dict | None = None) -> float:
+ """RPC wait budget for a compute-host compress control (#97948).
+
+ Manual compression legitimately runs up to the configured
+ ``compression.context_total_ceiling_seconds`` (default 600s), so a fixed
+ 120s waiter reported a false timeout while the host kept working. Follow
+ the ceiling with a little slack, but cap the blocking wait so it stays
+ below the desktop's own RPC timeout; anything longer is adopted through
+ the late-ack path instead of failing.
+ """
+ from agent.conversation_compression import resolve_context_compression_timeouts
+
+ try:
+ compression_cfg = (cfg if cfg is not None else _load_cfg()).get("compression", {})
+ except Exception:
+ compression_cfg = {}
+ _idle, ceiling = resolve_context_compression_timeouts(
+ compression_cfg if isinstance(compression_cfg, dict) else {}
+ )
+ return float(min(max(ceiling + 30.0, 120.0), _COMPUTE_HOST_COMPRESS_WAIT_CAP_SECS))
+
+
+def _announce_compute_host_compress_done(sid: str, session: dict, ack: dict) -> None:
+ """Mirror a compute-host compress ack and push the client-visible edges.
+
+ Emits the same ``session.info`` the in-process /compress path does plus
+ the ``compacted`` status edge, so a client whose own RPC wait already
+ expired still learns the transcript changed.
+ """
+ _apply_compute_host_metadata_mirror(session, ack)
+ try:
+ info = _session_info(session.get("agent"), session)
+ except TypeError:
+ info = _session_info(session.get("agent"))
+ _emit("session.info", sid, info)
+ _status_update(sid, "compacted", "✓ Context compression complete")
+
+
+def _adopt_late_compute_host_compress_ack(sid: str, session: dict, ack: dict, *, route_name: str) -> None:
+ """Adopt a compute-host compress ack that arrived after its RPC waiter gave up.
+
+ The RPC already answered ``status: pending``; this is the only place the
+ rotated session_key / history_version / session_info mirror can land, and
+ the only signal the client gets that the transcript changed. A late
+ ``control.error`` surfaces through the existing ``error`` event path.
+ """
+ with _sessions_lock:
+ live = _sessions.get(sid)
+ if live is not session:
+ return
+ if not isinstance(ack, dict) or ack.get("type") in {"control.error", "error"}:
+ message = str((ack or {}).get("message") or f"compute-host {route_name} failed")
+ _emit("error", sid, {"message": f"compression failed: {message}"})
+ _status_update(sid, "ready")
+ return
+ _announce_compute_host_compress_done(sid, session, ack)
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 9e531628889..ebe7b96598e 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -643,1021 +643,6 @@ def _load_interim_assistant_messages() -> bool:
return is_truthy_value(display.get("interim_assistant_messages", True))
-def _notify_session_boundary(
- event_type: str, session_id: str | None, platform: str | None = None
-) -> None:
- """Fire session lifecycle hooks with CLI parity."""
- try:
- from hermes_cli.lifecycle import finalize_session, invoke_hook
-
- if event_type == "on_session_finalize":
- finalize_session(
- session_id=session_id,
- platform=_resolve_agent_platform(platform),
- )
- else:
- invoke_hook(
- event_type,
- session_id=session_id,
- platform=_resolve_agent_platform(platform),
- )
- except Exception:
- pass
-
-
-_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",
-})
-
-
-def _claim_active_session_slot(
- session_key: str,
- *,
- live_session_id: str,
- surface: str = "tui",
- profile_home: str | Path | None = None,
-) -> tuple[Any, str | None]:
- track_liveness = str(surface or "").strip().lower() == "desktop"
- 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,
- track_liveness=track_liveness,
- )
- except Exception as exc:
- logger.warning("Failed to claim active session slot: %s", exc)
- # Fail CLOSED regardless of surface: per-session exclusivity is a
- # correctness guarantee (see PER_SESSION_EXCLUSIVE_SUBMIT), and a
- # claim that errors out has NOT proven the session is unowned.
- # Proceeding without a lease here is the silent double-writer hole
- # flagged in the #94595 review (blocker 2).
- 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 / session.resume deliberately do NOT claim one. Every
- desktop tile paint, background reconnect-resume and abandoned draft opens a
- session just to paint a composer, and a slot held by one of those is
- invisible everywhere: an unprompted draft has no DB row, and the sidebar
- filters it out with min_messages=1. Idle desktop tabs therefore silently
- starved the messaging gateway, which shares this cap — five parked tabs on
- a websocket-flappy host locked a Discord bot out of a 5-slot cap while
- running no agents at all. Claiming on the first turn mirrors the lazy
- contract _ensure_session_db_row already uses for the row itself, and keeps
- the invariant that anything holding a slot is something the user can see.
- """
- if session.get("active_session_lease") is not None:
- return None
- lease, limit_message = _claim_active_session_slot(
- str(session.get("session_key") or ""),
- live_session_id=sid,
- surface=_session_source(session),
- profile_home=session.get("profile_home"),
- )
- if limit_message is not None:
- return limit_message
- session["active_session_lease"] = lease
- return None
-
-
-def _release_active_session_lease(lease) -> bool:
- 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))
- released = getattr(lease, "released", True)
- enabled = getattr(lease, "enabled", True)
- return bool(released or not enabled)
-
-
-def _release_active_session_slot(session: dict | None) -> bool:
- if not session:
- return True
- lease = session.get("active_session_lease")
- if _release_active_session_lease(lease):
- if session.get("active_session_lease") is lease:
- session.pop("active_session_lease", None)
- return True
- return False
-
-
-def _other_runtime_lease_guard(session_id: str, session: dict):
- """Release this runtime and lock sibling ownership through the DB write."""
- lease = session.get("active_session_lease")
- try:
- from hermes_cli.active_sessions import (
- active_session_liveness_guard,
- release_active_session_liveness_guard,
- )
- except Exception as exc:
- 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:
- logger.warning(
- "Failed to inspect active session leases; preserving session %s: %s",
- session_id,
- last_error,
- )
- yield True
- return
- try:
- yield active
- finally:
- stack.close()
- if (
- lease is not None
- and getattr(lease, "released", False)
- and session.get("active_session_lease") is lease
- ):
- session.pop("active_session_lease", None)
-
-
-def _transfer_active_session_slot(
- sid: str,
- session: dict,
- *,
- new_session_id: str,
-) -> bool:
- if not new_session_id:
- return False
- lease = session.get("active_session_lease")
- if lease is None:
- return True
- try:
- from hermes_cli.active_sessions import transfer_active_session
-
- if transfer_active_session(
- lease,
- session_id=new_session_id,
- metadata={"live_session_id": sid},
- ):
- return True
- except Exception:
- logger.debug("Failed to transfer active session slot", exc_info=True)
-
- if getattr(lease, "track_liveness", False):
- return False
-
- # Fallback: the in-place transfer could not move the lease (entry pruned /
- # pid-check transiently failed). Reserve the new slot BEFORE releasing the
- # old one, so a concurrent gateway at the session cap cannot grab the freed
- # slot in a release-then-reacquire window and leave this session with no
- # lease at all (#49041 review). If the reserve fails, 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 not None:
- 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)
- session["active_session_lease"] = new_lease
- return True
- # Reserve failed — retain the existing lease rather than dropping it.
- if limit_message:
- logger.warning(
- "Compression session lease re-anchor failed (kept old lease): "
- "sid=%s new_session_id=%s reason=%s",
- sid,
- new_session_id,
- limit_message,
- )
- return False
-
-
-# Session sources the TUI/desktop backend must never end in state.db: the
-# messaging gateway owns those sessions' lifecycle — the TUI is only a viewer
-# (a resume of a Telegram/Discord/... session). Ending one creates the
-# #60609 Groundhog Day routing loop (see _finalize_session). Sources the
-# TUI backend itself creates ("tui", plus whatever a client passes as its
-# own ``source``) and the CLI's own sessions 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`` names a messaging-gateway platform whose session
- lifecycle belongs to the gateway, not to this TUI backend.
-
- Structural rather than a hardcoded platform list: any source that
- resolves to a known gateway ``Platform`` (built-in enum member OR a
- registered platform plugin, via ``Platform._missing_``) counts, so new
- platforms are covered automatically. Local/self-owned sources are
- excluded explicitly — ``local``/``webhook``/``api_server`` are Platform
- members but their sessions are not owned by a remote chat surface that
- routes by session_key, so reaping them is safe and keeps /resume clean.
- """
- src = (source or "").strip().lower()
- if src in _NON_GATEWAY_SOURCES:
- return False
- try:
- from gateway.config import Platform
-
- Platform(src) # raises ValueError for arbitrary non-platform strings
- return True
- except Exception:
- return False
-
-
-def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> None:
- """Best-effort finalize hook + memory commit for a session.
-
- Fires ``on_session_end`` plugin hook and attempts to persist any
- unflushed messages before closing the session. This mirrors the
- CLI's exit-path behaviour and prevents data loss when the TUI is
- force-quit (double Ctrl‑C, terminal‑close, SIGHUP) while the agent
- is mid‑turn.
- """
- if not session or session.get("_finalized"):
- return
- session["_finalized"] = True
- history_ready = session.get("resume_history_ready")
- if history_ready is not None and not history_ready.is_set():
- session["resume_history_error"] = "session resume cancelled"
- history_ready.set()
- _desktop_automatic_cleanup = bool(
- end_reason in _AUTOMATIC_SESSION_END_REASONS
- and _session_source(session).strip().lower() == "desktop"
- )
- # Automatic Desktop cleanup removes 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)
- stop_event = session.get("_notif_stop")
- if stop_event is not None:
- stop_event.set()
-
- agent = session.get("agent")
- lock = session.get("history_lock")
- if lock is not None:
- with lock:
- history = list(session.get("history", []))
- else:
- history = list(session.get("history", []))
-
- # ── Persist unflushed messages to SQLite ──────────────────────────
- # Flush ``agent._session_messages`` via ``_persist_session``'s marker-based
- # dedup (same contract as the gateway-shutdown flush, #13121). Do NOT pass
- # ``conversation_history``: ``session["history"]`` and ``_session_messages``
- # alias the SAME list once a turn completes, so passing it made
- # ``_flush_messages_to_session_db`` treat every message as already-durable
- # and skip it — a data-loss bug when finalize is the sole persist path after
- # a WS disconnect/restart (e.g. the in-turn flush hit a transient SQLite
- # failure). Markers persist the genuinely-unflushed tail without duplicating
- # durable rows (including a resumed-but-not-run session's already-in-DB
- # transcript, which stays in ``session["history"]`` only).
- if agent is not None and hasattr(agent, "_persist_session"):
- snapshot = getattr(agent, "_session_messages", None)
- if snapshot:
- try:
- agent._persist_session(snapshot)
- except Exception:
- pass
-
- # ── Plugin hook: on_session_end ────────────────────────────────────
- # Signals every plugin that the session is closing, with
- # interrupted=True so crash‑recovery plugins can flush buffers,
- # persist state, or close connections before the gateway exits.
- # Mirrors cli.py's atexit handler that fires the same hook when
- # the user Ctrl‑C's mid‑turn.
- if agent is not None:
- try:
- from hermes_cli.lifecycle import invoke_hook
-
- invoke_hook(
- "on_session_end",
- 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",
- )
- except Exception:
- pass
-
- if agent is not None and history and hasattr(agent, "commit_memory_session"):
- try:
- agent.commit_memory_session(history)
- except Exception:
- pass
-
- 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))
-
- # Mark session ended in DB so it doesn't linger as a ghost row in /resume.
- # Use session_id (from agent.session_id) not session_key — after compression,
- # session_key may be stale (the ended parent) while session_id is the live
- # continuation. Fix for #20001.
- 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)
- )
- with _lifecycle_guard as _other_runtime_owns_lifecycle:
- _tui_owns_lifecycle = not _other_runtime_owns_lifecycle
- if _other_runtime_owns_lifecycle:
- logger.info(
- "Preserving session %s during %s: another backend owns an active lease",
- session_id,
- end_reason,
- )
- if session_id:
- try:
- # End the row in the *session's* profile state.db (app-global
- # remote mode), not the launch profile's shared handle.
- with _session_db(session) as db:
- if db is not None:
- # Don't end gateway-originated sessions — the gateway owns
- # their lifecycle. The TUI is a viewer, not the owner.
- # Ending a gateway session in state.db triggers a Groundhog
- # Day routing loop: the gateway's #54878 self-heal detects
- # the stale entry, recovers to the parent session, context
- # compression splits back to the reaped child, and the cycle
- # repeats on every inbound message. (#60609)
- row = db.get_session(session_id)
- source = (row or {}).get("source", "")
- if _is_gateway_owned_source(source):
- _tui_owns_lifecycle = False
- elif _tui_owns_lifecycle:
- db.end_session(session_id, end_reason)
- except Exception:
- pass
-
- # A session's in-flight async delegations end WITH the session (#55578):
- # once nobody owns the return address, a still-running background subagent
- # can only burn tokens and park an orphaned completion on the shared
- # queue. Always interrupt delegations commissioned by THIS live UI session
- # (its sid); additionally interrupt by durable session_key, but only when
- # the TUI owns the lifecycle — closing a viewer tab on a live gateway
- # session must not kill the gateway's own background work.
- try:
- from tools.async_delegation import interrupt_for_session
-
- _own_sid = str(session.get("_sid") or "")
- if not _own_sid:
- try:
- with _sessions_lock:
- for _cand_sid, _cand in _sessions.items():
- if _cand is session:
- _own_sid = _cand_sid
- break
- except Exception:
- _own_sid = ""
- interrupt_for_session(
- session_key=str(session_key or "") if _tui_owns_lifecycle else "",
- origin_ui_session_id=_own_sid,
- reason=end_reason,
- )
- except Exception:
- pass
-
- # Close the slash-worker subprocess as part of finalize itself, not just
- # in the callers. Defense-in-depth: every session-end path goes through
- # _finalize_session (it's the single ``_finalized``-guarded chokepoint), so
- # folding worker cleanup in here means a future code path that calls
- # _finalize_session directly — without the surrounding _teardown_session /
- # _shutdown_sessions worker.close() — can't reintroduce the #38095 leak.
- # Idempotent: _SlashWorker.close() is poll()-guarded, so the explicit
- # close() still in those callers is harmless.
- try:
- worker = session.get("slash_worker")
- if worker:
- worker.close()
- except Exception:
- pass
-
-
-# End reasons where the BACKEND reclaimed a session the client never asked to
-# close: the idle-TTL reaper, the LRU cap, and the WS-orphan reap. A client
-# holding that live session id gets no signal today — its next prompt fails
-# against an id the backend has already forgotten, which reads as the session
-# silently vanishing rather than being reclaimed. ``tui_close`` and friends are
-# deliberately absent: the client initiated those and already knows.
-_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 rather than session-targeted: the reap paths run on background
- timer threads with no contextvar binding, and the WS-orphan case has by
- definition lost its own transport — ``_emit`` would bottom out on stdio and
- the peer that owns the session would never see it. Best-effort; a failed
- notify must never break teardown.
- """
- if end_reason not in _RECLAIM_END_REASONS:
- return
- try:
- _broadcast_global_event(
- "session.reclaimed",
- {
- "session_id": str(session.get("_sid") or ""),
- "stored_session_id": str(session.get("session_key") or ""),
- "reason": end_reason,
- },
- )
- except Exception:
- logger.debug("session.reclaimed broadcast failed", exc_info=True)
-
-
-def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") -> None:
- """Fully tear down a session: finalize, unregister, close agent + worker.
-
- Shared by ``session.close`` and the orphaned-WS-session reaper. The
- slash-worker subprocess is closed inside ``_finalize_session`` (the single
- finalize chokepoint); this still unregisters the approval notifier and
- closes the in-process agent. Idempotent: the ``_finalized`` guard in
- ``_finalize_session`` and the ``poll()`` guard in ``_SlashWorker.close``
- make repeat calls harmless.
- """
- if not session:
- return
- _finalize_session(session, end_reason=end_reason)
- _announce_session_reclaimed(session, end_reason)
- try:
- from tools.approval import unregister_gateway_notify
-
- if key := session.get("session_key"):
- unregister_gateway_notify(key)
- except Exception:
- pass
- try:
- agent = session.get("agent")
- if agent is not None and hasattr(agent, "close"):
- agent.close()
- except Exception:
- pass
- # NOTE: the slash-worker is closed inside _finalize_session (the single
- # _finalized-guarded chokepoint that main folded it into), exactly once.
- # We deliberately do NOT re-close it here — _teardown_session's job beyond
- # finalize is unregistering the notifier and closing the in-process agent.
-
-
-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. Closes the create/close race at every slash-worker spawn site."""
- with _sessions_lock:
- if _sessions.get(sid) is session:
- session["slash_worker"] = worker
- return
- worker.close()
-
-
-def _pop_session_by_id(sid: str) -> dict | None:
- """Atomically detach one live session from the registry.
-
- Detaching is the ownership claim for teardown: once the record is no
- longer in ``_sessions``, a concurrent close/reaper becomes a no-op. Keep
- this operation separate from ``_teardown_session`` because finalization can
- flush SQLite state, invoke plugins, commit memory, interrupt delegations,
- and close agents/workers. None of that slow external work belongs under
- the global ``_session_resume_lock``.
- """
- with _sessions_lock:
- session = _sessions.get(sid)
- if session is not None:
- session["_closing"] = True
- _sessions.pop(sid, None)
- if session is None:
- return None
- # The session is already out of _sessions here, so downstream teardown
- # (e.g. _finalize_session's per-session async-delegation interrupt) can't
- # recover its live id by scanning the dict — stamp it on the record.
- session["_sid"] = sid
- return session
-
-
-def _teardown_popped_session(
- session: dict | None, *, end_reason: str = "tui_close"
-) -> bool:
- """Finish a close after the caller has atomically detached the session."""
- if session is None:
- return False
- run_thread = session.get("_run_thread")
- if (
- end_reason != "tui_shutdown"
- and run_thread is not None
- and run_thread is not threading.current_thread()
- ):
- try:
- if run_thread.is_alive():
- run_thread.join(timeout=_TURN_SETTLE_BEFORE_CLOSE_SECONDS)
- if run_thread.is_alive():
- logger.warning(
- "session turn thread still alive after %.1fs teardown grace",
- _TURN_SETTLE_BEFORE_CLOSE_SECONDS,
- )
- except Exception:
- logger.debug("failed waiting for session turn thread", exc_info=True)
- _teardown_session(session, end_reason=end_reason)
- return True
-
-
-def _close_session_by_id(
- sid: str,
- *,
- end_reason: str = "tui_close",
- predicate: Callable[[dict], bool] | None = None,
-) -> bool:
- """Single idempotent teardown funnel for callers needing no resume race.
-
- Resume-sensitive callers first pop under ``_session_resume_lock`` and then
- call ``_teardown_popped_session`` after releasing it. Other reapers can use
- this convenience wrapper directly. The pop remains the single atomic
- ownership claim, so concurrent/repeat close attempts stay harmless.
-
- Automatic reapers can pass ``predicate`` to revalidate under
- ``_sessions_lock`` immediately before the ownership claim. This prevents a
- stale scan result from closing a session that reattached or gained active
- delegated work before teardown.
- """
- if predicate is None:
- 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)
-
-
-def _ws_session_is_detached(session: dict | None) -> bool:
- """True if a live session is still bound to the disconnected-WS sentinel."""
- return bool(
- session
- and not session.get("_finalized")
- and session.get("transport") is _detached_ws_transport
- )
-
-
-def _ws_session_is_orphaned(session: dict | None) -> bool:
- """True if a WS session has no live transport and no in-flight turn.
-
- After ``handle_ws`` detaches a disconnected client it points the session at
- ``_detached_ws_transport``. A session left on that transport (and not
- mid-turn) is genuinely orphaned and safe to reap.
- """
- return bool(
- _ws_session_is_detached(session)
- and session is not None
- 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 interrupt used the compute-host control channel. The WS
- orphan reaper calls this same helper after its reconnect grace expires, so a
- dead client gets the same partial-history and queued-prompt semantics as an
- explicit user interrupt.
- """
- 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` is only a mirror and
- # can lag behind a blocked interactive tool (a clarify parked on its
- # Event keeps the host turn alive after the parent flag went stale),
- # so let the host decide whether there is work to interrupt.
- # Gate on `_compute_host_active` too: `_session_uses_compute_host`
- # is also true for lazy sessions that never ran a hosted turn, and
- # `HostSupervisor.interrupt()` calls `start()` — forwarding
- # unconditionally would spawn a compute-host child just to deliver
- # an interrupt no session ever submitted work to.
- 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()
-
- 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
-
- request_hard_interrupt(session.get("agent"))
- if not run_thread_alive:
- with session["history_lock"]:
- if session.get("running"):
- session["running"] = False
- _clear_inflight_turn(session)
-
- _clear_pending(sid)
- try:
- from tools.approval import resolve_gateway_approval
-
- resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)
- except Exception:
- pass
- 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."""
- if not session_id:
- return True
- try:
- db = _get_db()
- if db is None:
- return True
- # Don't end gateway-originated sessions — the gateway owns their
- # lifecycle. The TUI is only a viewer there (#60609).
- row = db.get_session(session_id)
- source = (row or {}).get("source", "")
- return not _is_gateway_owned_source(source)
- except Exception:
- return True
-
-
-def _session_async_delegation_selectors(
- session: dict | None, *, sid_hint: str = ""
-) -> tuple[str, str]:
- """Ownership selectors for async background work tied to one UI session."""
- if not session:
- return "", ""
- own_sid = str(sid_hint or session.get("_sid") or "")
- if not own_sid:
- try:
- with _sessions_lock:
- for _cand_sid, _cand in _sessions.items():
- if _cand is session:
- own_sid = _cand_sid
- break
- except Exception:
- own_sid = ""
- agent = session.get("agent")
- session_key = str(session.get("session_key") or "")
- session_id = getattr(agent, "session_id", None) or session_key
- owned_session_key = session_key if _session_owns_durable_lifecycle(session_id) else ""
- return own_sid, owned_session_key
-
-
-def _session_has_active_delegations(sid: str, session: dict | None = None) -> bool:
- """True when UI session ``sid`` still owns live background work.
-
- Matches by the live UI sid AND — when the TUI owns the durable lifecycle
- (never for gateway-viewer tabs, #60609) — by the durable session_key, so a
- delegation dispatched from an earlier tab of the same resumed session still
- keeps it alive.
- """
- if session is None:
- with _sessions_lock:
- session = _sessions.get(sid)
- own_sid, owned_session_key = _session_async_delegation_selectors(
- session, sid_hint=sid
- )
- if not own_sid and not owned_session_key:
- return False
- try:
- from tools.async_delegation import has_live_for_session
-
- 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 turn into destructive
- # cleanup. Conservatively keep the detached session and let the next
- # orphan timer retry the lookup.
- return True
-
-
-# One pending WS-orphan reap Timer per live sid. Registered by
-# _schedule_ws_orphan_reap, popped when its _reap fires, and cancelled by
-# _cancel_ws_orphan_reap from every resume/reuse/transport-rebind path. Without
-# this cancellation the reap could fire against an already-reattached session,
-# broadcast session.reclaimed, and trigger the client's auto-re-resume — a
-# reap->broadcast->resume feedback storm. Guarded by _sessions_lock.
-_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 onto the session:
- the session.resume fast-path reuse, _claim_or_reuse_live winners, and the
- _live_session_payload transport rebind. Cancelling here (rather than
- relying on the reap's own orphan re-check) removes the window where a
- fired-but-not-yet-run Timer races the resume, and stops dead Timers from
- accumulating for sessions that reconnect frequently.
- """
- with _sessions_lock:
- timer = _pending_ws_reaps.pop(sid, None)
- if timer is not None:
- try:
- timer.cancel()
- except Exception:
- pass
-
-
-def _ws_orphan_turn_activity_is_fresh(session: dict) -> bool:
- """Whether a detached RUNNING turn's activity clock is still fresh.
-
- Reuses the agent's existing activity summary (``_touch_activity`` is
- stamped by API waits, stream tokens, and tool heartbeats — the same
- clock the turn-liveness watchdog samples; see agent/turn_liveness.py).
- Fresh means the WS-orphan reaper must NOT interrupt the turn yet
- (#98028/#100325): deliberate client absence (closed laptop, backgrounded
- mobile app, desktop update/relaunch) keeps healthy work running detached.
-
- Conservative fallbacks preserve the wedged-turn safety net: a disabled
- threshold (<= 0), a missing/opaque agent, an unreadable summary, or a
- never-stamped clock all report NOT fresh, i.e. eligible for the
- interrupt-at-grace path exactly as before.
- """
- if _WS_ORPHAN_ACTIVITY_STALE_S <= 0:
- return False
- agent = session.get("agent")
- summary_fn = getattr(agent, "get_activity_summary", None)
- if not callable(summary_fn):
- return False
- try:
- elapsed = summary_fn().get("seconds_since_activity")
- return elapsed is not None and float(elapsed) < _WS_ORPHAN_ACTIVITY_STALE_S
- except Exception:
- return False
-
-
-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. The grace window lets a transient
- reconnect (or a ``session.resume`` that reattaches the transport) cancel
- the reap by re-binding a live transport. Disabled when the grace is 0.
- """
- if _WS_ORPHAN_REAP_GRACE_S <= 0:
- return
-
- def _reap() -> None:
- # Serialize the orphan re-check against session.resume (which re-binds a
- # live transport under _session_resume_lock and would make this session
- # non-orphaned). Claim teardown by popping under both lifecycle locks,
- # then release the global resume lock before the slow finalization work.
- # The dict mutation still happens under _sessions_lock — consistent
- # with every other _sessions mutator
- # (#39591: _reap previously popped under _session_resume_lock, giving no
- # mutual exclusion against _init_session / _close_session_by_id, which
- # guard with _sessions_lock). _sessions_lock is an RLock and the global
- # ordering is always resume_lock -> sessions_lock, so nesting is safe.
- reschedule_delay = None
- interrupt_session = None
- session = None
- with _session_resume_lock:
- # This Timer is running: drop its registration so a concurrent
- # _cancel_ws_orphan_reap doesn't cancel a dead Timer object while
- # a rescheduled one (registered below) is the live owner.
- with _sessions_lock:
- _pending_ws_reaps.pop(sid, None)
- current = _sessions.get(sid)
- if current is None or not _ws_session_is_detached(current):
- return
- if _session_has_active_delegations(sid, current):
- reschedule_delay = _WS_ORPHAN_REAP_GRACE_S
- elif current.get("running"):
- if not current.get(
- "_client_gone_interrupt_requested"
- ) and _ws_orphan_turn_activity_is_fresh(current):
- # Client-absent but actively producing (#98028/#100325):
- # the turn keeps running detached (the sentinel transport
- # already buffers emits) and the reaper re-checks each
- # grace interval. Only a turn whose activity clock has
- # gone stale — genuinely wedged, the case the interrupt
- # was added for — falls through to the interrupt below.
- 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 (#85578): after the reconnect grace the turn is
- # interrupted once, then the reap keeps polling until the
- # normal turn-finalization path 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:
- # The interrupted turn never settled inside the budget
- # — force-reap rather than parking the session + a
- # timer chain forever. Loud by design: this only fires
- # when a turn is genuinely stuck past interrupt.
- logger.error(
- "client_gone sid=%s: turn did not settle after %d "
- "interrupt polls (%.0fs) — force-reaping detached "
- "session",
- sid, polls - 1,
- (polls - 1) * _WS_ORPHAN_INTERRUPT_REAP_POLL_S,
- )
- session = _pop_session_by_id(sid)
- else:
- if not current.get("_client_gone_interrupt_requested"):
- current["_client_gone_interrupt_requested"] = True
- interrupt_session = current
- reschedule_delay = _WS_ORPHAN_INTERRUPT_REAP_POLL_S
- else:
- session = _pop_session_by_id(sid)
-
- if interrupt_session is not None:
- try:
- isolated = _interrupt_session_turn(
- sid,
- interrupt_session,
- request_id=f"client-gone-{sid}",
- )
- logger.info(
- "client_gone sid=%s action=interrupt turn_isolation=%s",
- sid,
- isolated,
- )
- except Exception:
- logger.exception("client_gone interrupt failed sid=%s", sid)
- with _sessions_lock:
- if _sessions.get(sid) is interrupt_session:
- interrupt_session.pop(
- "_client_gone_interrupt_requested", None
- )
-
- if reschedule_delay is not None:
- _schedule_ws_orphan_reap(sid, delay_s=reschedule_delay)
- return
- if session is not None and session.get(
- "_client_gone_interrupt_requested"
- ):
- logger.info("client_gone sid=%s action=reap", sid)
- _teardown_popped_session(session, end_reason="ws_orphan_reap")
-
- timer = threading.Timer(
- _WS_ORPHAN_REAP_GRACE_S if delay_s is None else max(0.0, delay_s),
- _reap,
- )
- timer.daemon = True
- with _sessions_lock:
- prior = _pending_ws_reaps.pop(sid, None)
- _pending_ws_reaps[sid] = timer
- if prior is not None:
- try:
- prior.cancel()
- except Exception:
- pass
- timer.start()
-
-
-def _close_sessions_for_transport(
- transport, *, end_reason: str = "ws_disconnect"
-) -> tuple[int, int]:
- """On transport disconnect, reap the sessions that opted into
- close_on_disconnect (sidecar/dashboard) immediately and re-point the rest
- at the detached transport so later emits don't hit a dead socket.
-
- Non-flagged detached sessions are handed to the grace-windowed WS-orphan
- reaper (``_schedule_ws_orphan_reap``): a quick reconnect / session.resume
- that re-binds a live transport cancels the reap, otherwise the orphan is
- torn down through the same idempotent ``_teardown_session`` path. This is
- the single WS-disconnect teardown entry point — there is no second
- independent reap loop in ``handle_ws``.
-
- Returns ``(reaped, detached)`` counts for disconnect-path observability."""
- with _sessions_lock:
- owned = [(sid, s) for sid, s in _sessions.items() if s.get("transport") is transport]
- reaped = 0
- detached = 0
- for sid, session in owned:
- claimed_for_teardown = None
- should_schedule_reap = False
- # A session.resume fast-path rebinds its live session while holding
- # _session_resume_lock. Take that lock before re-checking the snapshot
- # so a reconnect cannot move the transport between this check and the
- # close/detach ownership claim. Keep the slow teardown below both locks.
- with _session_resume_lock:
- with _sessions_lock:
- current = _sessions.get(sid)
- if current is not session:
- continue
- if current.get("transport") is not transport:
- # The reconnect owns this session now. Drop only the old
- # viewer registration; it must not affect the new owner.
- viewers = current.get("viewers")
- if viewers:
- viewers.pop(transport, None)
- continue
- if current.get("close_on_disconnect"):
- claimed_for_teardown = _pop_session_by_id(sid)
- else:
- # Point detached sessions at the drop sentinel (NOT real
- # stdio) so _ws_session_is_orphaned recognizes them and
- # the grace-reap can actually fire; a standalone
- # `hermes --tui` keeps real _stdio. UNLESS another window
- # still shows the session: multi-window pop-outs all
- # register as viewers, so on disconnect re-bind the
- # session to the most recent surviving viewer instead of
- # stranding the original window on the sentinel (#83716).
- viewers = current.get("viewers")
- if viewers:
- viewers.pop(transport, None)
- remaining = [
- (ts, viewer_transport)
- for viewer_transport, ts in (viewers or {}).items()
- if (
- viewer_transport is not transport
- and not _transport_is_dead(viewer_transport)
- )
- ]
- if remaining:
- remaining.sort(key=lambda item: item[0])
- current["transport"] = remaining[-1][1]
- else:
- current["transport"] = _detached_ws_transport
- 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
- elif should_schedule_reap:
- detached += 1
- try:
- _schedule_ws_orphan_reap(sid)
- except Exception:
- pass
- return reaped, detached
-
def _shutdown_sessions() -> None:
# Durable-first (#94724 item 2): persist every session's un-flushed
@@ -2651,373 +1636,18 @@ def _broadcast_global_event(event: str, payload: dict | None = None) -> None:
with _live_transports_lock:
targets = list(_live_transports)
- if not targets:
- _emit(event, "", payload)
- return
-
- frame = _event_frame(event, "", payload)
- for transport in targets:
- try:
- transport.write(frame)
- except Exception:
- # One wedged peer must not stall the rest; disconnect teardown
- # unregisters it.
- logger.debug("global-event broadcast write failed type=%s", event, exc_info=True)
-
-
-_compute_host_supervisor = None
-_compute_host_supervisor_lock = threading.Lock()
-# Hard cap on how long session.compress blocks its RPC waiting for the compute
-# host (#97948). Must stay below the desktop's SESSION_COMPRESS_TIMEOUT_MS
-# (660s) so the client receives the `pending` answer instead of its own
-# timeout error; the late-ack path covers anything slower.
-_COMPUTE_HOST_COMPRESS_WAIT_CAP_SECS = 630.0
-
-
-def _inside_compute_host_child() -> bool:
- return os.environ.get("HERMES_COMPUTE_HOST_CHILD") == "1"
-
-
-def _turn_isolation_enabled(cfg: dict | None = None) -> bool:
- if _inside_compute_host_child():
- return False
- isolation_cfg = cfg or _load_dashboard_process_isolation_config()
- return bool(isolation_cfg.get("turn_isolation"))
-
-
-def _session_uses_compute_host(session: dict, cfg: dict | None = None) -> bool:
- if not _turn_isolation_enabled(cfg):
- return False
- # Phase 1 routes lazy/dashboard sessions whose live AIAgent has not been
- # built inside the serving process. Already-built in-process sessions keep
- # the historical path unless a prior isolated turn marked host ownership.
- return bool(session.get("_compute_host_active")) or (
- session.get("agent") is None and session.get("agent_ready") is not None
- )
-
-
-def _get_compute_host_supervisor(cfg: dict | None = None):
- global _compute_host_supervisor
- isolation_cfg = cfg or _load_dashboard_process_isolation_config()
- with _compute_host_supervisor_lock:
- if _compute_host_supervisor is None:
- from tui_gateway.host_supervisor import HostSupervisor
-
- _compute_host_supervisor = HostSupervisor(
- rpc_sink=_relay_compute_host_rpc,
- heartbeat_secs=int(isolation_cfg.get("compute_host_heartbeat_secs") or 15),
- respawn_max=int(isolation_cfg.get("compute_host_respawn_max") or 3),
- )
- return _compute_host_supervisor
-
-
-def _compute_host_turn_frame(
- rid: str,
- sid: str,
- session: dict,
- text: Any,
- image_paths: list[str] | None = None,
- queued_prompt_generation: int | None = None,
- display_kind: str | None = None,
-) -> dict:
- with session["history_lock"]:
- history = list(session.get("history", []))
- history_version = int(session.get("history_version", 0))
- attached_images = (
- list(image_paths)
- if image_paths is not None
- else list(session.get("attached_images", []))
- )
- return {
- "type": "turn.start",
- "sid": sid,
- "request_id": rid,
- "session_key": session.get("session_key") or sid,
- "text": text,
- **({"display_kind": display_kind} if display_kind else {}),
- "history": history,
- "history_version": history_version,
- "cols": int(session.get("cols", 80) or 80),
- "cwd": _session_cwd(session),
- "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(session),
- "profile_home": session.get("profile_home") or "",
- "model_override": session.get("model_override"),
- "reasoning_config_override": session.get("create_reasoning_override"),
- "service_tier_override": session.get("create_service_tier_override"),
- "source": _session_source(session),
- "attached_images": attached_images,
- "queued_prompt_generation": queued_prompt_generation,
- }
-
-
-def _metadata_mirror(session: dict | None) -> dict:
- mirror = (session or {}).get("_metadata_mirror")
- return mirror if isinstance(mirror, dict) else {}
-
-
-def _relay_compute_host_rpc(message: dict) -> bool:
- """Relay host events while retaining the clarify snapshot needed on resume."""
- params = message.get("params") if isinstance(message, dict) else None
- if isinstance(params, dict) and params.get("type") == "clarify.request":
- sid = str(params.get("session_id") or "")
- payload = params.get("payload")
- session = _sessions.get(sid)
- if session is not None and isinstance(payload, dict) and payload.get("request_id"):
- with session.get("history_lock", threading.Lock()):
- session["_compute_host_pending_clarify"] = dict(payload)
- elif isinstance(params, dict) and params.get("type") == "clarify.expire":
- sid = str(params.get("session_id") or "")
- payload = params.get("payload")
- session = _sessions.get(sid)
- request_id = payload.get("request_id") if isinstance(payload, dict) else None
- if session is not None and request_id:
- with session.get("history_lock", threading.Lock()):
- pending = session.get("_compute_host_pending_clarify")
- if isinstance(pending, dict) and pending.get("request_id") == request_id:
- session.pop("_compute_host_pending_clarify", None)
- return write_json(message)
-
-
-def _compute_host_clarify_session(request_id: str) -> tuple[str, dict] | None:
- """Find the parent mirror for one host-owned clarify request."""
- if not request_id:
- return None
- for sid, session in list(_sessions.items()):
- with session.get("history_lock", threading.Lock()):
- pending = session.get("_compute_host_pending_clarify")
- if isinstance(pending, dict) and pending.get("request_id") == request_id:
- return sid, session
- return None
-
-
-def _update_compute_host_clarify_snapshot(sid: str, session: dict, params: dict, result: dict) -> None:
- """Keep reconnect snapshots accurate while a batch clarify is answered."""
- request_id = str(params.get("request_id") or "")
- with session.get("history_lock", threading.Lock()):
- pending = session.get("_compute_host_pending_clarify")
- if not isinstance(pending, dict) or pending.get("request_id") != request_id:
- return
- if result.get("status") == "expired" or not result.get("remaining") and not params.get("question_id"):
- session.pop("_compute_host_pending_clarify", None)
- return
- question_id = str(params.get("question_id") or "")
- if question_id and isinstance(result.get("remaining"), list):
- answers = dict(pending.get("answers") or {})
- answers[question_id] = str(params.get("answer") or "")
- pending["answers"] = answers
- if not result["remaining"]:
- session.pop("_compute_host_pending_clarify", None)
-
-
-def _respond_compute_host_clarify(rid: str, params: dict) -> dict | None:
- """Proxy a clarify answer into the process that owns its pending Event."""
- located = _compute_host_clarify_session(str(params.get("request_id") or ""))
- if located is None:
- return None
- sid, session = located
- if not _session_uses_compute_host(session):
- return None
- try:
- ack = _get_compute_host_supervisor().respond(sid, params)
- except Exception as exc:
- return _err(rid, 5019, f"compute-host clarify response failed: {exc}")
- if ack.get("type") == "respond.error":
- return _err(rid, 5019, str(ack.get("message") or "compute-host clarify response failed"))
- response = ack.get("response")
- if not isinstance(response, dict):
- return _err(rid, 5019, "compute-host clarify response returned an invalid response")
- if "error" in response:
- error = response["error"] if isinstance(response["error"], dict) else {}
- return _err(rid, int(error.get("code") or 5000), str(error.get("message") or "clarify response failed"))
- result = response.get("result")
- if not isinstance(result, dict):
- return _err(rid, 5019, "compute-host clarify response returned an invalid result")
- _update_compute_host_clarify_snapshot(sid, session, params, result)
- return _ok(rid, result)
-
-
-def _apply_compute_host_metadata_mirror(session: dict, frame: dict | None) -> None:
- """Mirror host-owned session metadata in the serving process.
-
- The compute host is the only writer of live agent/history state while turn
- isolation is active. The serving process keeps read metadata from the last
- host frame so UI reads do not construct a second in-process agent.
- """
- if not isinstance(frame, dict):
- return
- with session.get("history_lock", threading.Lock()):
- if frame.get("session_key"):
- session["session_key"] = str(frame.get("session_key"))
- if frame.get("history_version") is not None:
- try:
- session["history_version"] = max(
- int(session.get("history_version", 0)),
- int(frame.get("history_version") or 0),
- )
- except Exception:
- pass
- if frame.get("message_count") is not None:
- try:
- session["_metadata_message_count"] = int(frame.get("message_count") or 0)
- except Exception:
- pass
- info = frame.get("session_info")
- if isinstance(info, dict):
- mirror = dict(_metadata_mirror(session))
- mirror.update(info)
- session["_metadata_mirror"] = mirror
- session["_metadata_mirror_updated_at"] = time.time()
-
-
-def _on_compute_host_turn_done(rid: str, sid: str, session: dict, frame: dict) -> None:
- is_error = frame.get("type") == "turn.error"
- with session["history_lock"]:
- if frame.get("session_key"):
- session["session_key"] = str(frame.get("session_key"))
- if frame.get("history_version") is not None:
- try:
- session["history_version"] = max(
- int(session.get("history_version", 0)),
- int(frame.get("history_version") or 0),
- )
- except Exception:
- pass
- session["running"] = False
- session["last_active"] = time.time()
- _clear_inflight_turn(session)
- session.pop("_compute_host_pending_clarify", None)
- if is_error:
- message = str(frame.get("message") or "compute host turn failed")
- _emit("message.complete", sid, {"text": f"Error: {message}", "status": "error"})
- _apply_compute_host_metadata_mirror(session, frame)
- try:
- info = _session_info(session.get("agent"), session)
- except TypeError:
- info = _session_info(session.get("agent"))
- if not frame.get("session_info_emitted"):
- _emit("session.info", sid, info)
- _drain_queued_prompt(rid, sid, session)
-
-
-def _submit_prompt_to_compute_host(
- rid: str,
- sid: str,
- session: dict,
- text: Any,
- image_paths: list[str] | None = None,
- queued_prompt_generation: int | None = None,
- display_kind: str | None = None,
-) -> dict:
- cfg = _load_dashboard_process_isolation_config()
- frame = _compute_host_turn_frame(
- rid,
- sid,
- session,
- text,
- image_paths=image_paths,
- queued_prompt_generation=queued_prompt_generation,
- display_kind=display_kind,
- )
-
- def _complete(done: dict) -> None:
- # submit_turn reports a synchronous pipe failure through the callback
- # before re-raising. Leave the parent session untouched so prompt.submit
- # can fail open to the historical in-process path without emitting a
- # duplicate terminal error.
- if done.get("reason") == "send_failed":
- return
- _on_compute_host_turn_done(rid, sid, session, done)
-
- try:
- _get_compute_host_supervisor(cfg).submit_turn(frame, on_complete=_complete)
- except Exception as exc:
- return _err(rid, 5019, f"compute-host dispatch failed: {exc}")
- with session["history_lock"]:
- session["_compute_host_active"] = True
- if image_paths is None:
- session["attached_images"] = []
- return _ok(rid, {"status": "streaming", "turn_isolation": True})
-
-
-def _send_compute_host_control(
- sid: str,
- *,
- route_name: str,
- command: str = "",
- payload: dict | None = None,
- wait: bool = True,
- timeout: float = 30.0,
- on_late_ack=None,
-) -> dict:
- frame = dict(payload or {})
- frame.setdefault("type", "control")
- frame.setdefault("command", command)
- return _get_compute_host_supervisor().control(
- sid,
- route_name=route_name,
- payload=frame,
- wait=wait,
- timeout=timeout,
- on_late_ack=on_late_ack,
- )
-
-
-def _compute_host_compress_wait_seconds(cfg: dict | None = None) -> float:
- """RPC wait budget for a compute-host compress control (#97948).
-
- Manual compression legitimately runs up to the configured
- ``compression.context_total_ceiling_seconds`` (default 600s), so a fixed
- 120s waiter reported a false timeout while the host kept working. Follow
- the ceiling with a little slack, but cap the blocking wait so it stays
- below the desktop's own RPC timeout; anything longer is adopted through
- the late-ack path instead of failing.
- """
- from agent.conversation_compression import resolve_context_compression_timeouts
-
- try:
- compression_cfg = (cfg if cfg is not None else _load_cfg()).get("compression", {})
- except Exception:
- compression_cfg = {}
- _idle, ceiling = resolve_context_compression_timeouts(
- compression_cfg if isinstance(compression_cfg, dict) else {}
- )
- return float(min(max(ceiling + 30.0, 120.0), _COMPUTE_HOST_COMPRESS_WAIT_CAP_SECS))
-
-
-def _announce_compute_host_compress_done(sid: str, session: dict, ack: dict) -> None:
- """Mirror a compute-host compress ack and push the client-visible edges.
-
- Emits the same ``session.info`` the in-process /compress path does plus
- the ``compacted`` status edge, so a client whose own RPC wait already
- expired still learns the transcript changed.
- """
- _apply_compute_host_metadata_mirror(session, ack)
- try:
- info = _session_info(session.get("agent"), session)
- except TypeError:
- info = _session_info(session.get("agent"))
- _emit("session.info", sid, info)
- _status_update(sid, "compacted", "✓ Context compression complete")
-
-
-def _adopt_late_compute_host_compress_ack(sid: str, session: dict, ack: dict, *, route_name: str) -> None:
- """Adopt a compute-host compress ack that arrived after its RPC waiter gave up.
-
- The RPC already answered ``status: pending``; this is the only place the
- rotated session_key / history_version / session_info mirror can land, and
- the only signal the client gets that the transcript changed. A late
- ``control.error`` surfaces through the existing ``error`` event path.
- """
- with _sessions_lock:
- live = _sessions.get(sid)
- if live is not session:
- return
- if not isinstance(ack, dict) or ack.get("type") in {"control.error", "error"}:
- message = str((ack or {}).get("message") or f"compute-host {route_name} failed")
- _emit("error", sid, {"message": f"compression failed: {message}"})
- _status_update(sid, "ready")
+ if not targets:
+ _emit(event, "", payload)
return
- _announce_compute_host_compress_done(sid, session, ack)
+
+ frame = _event_frame(event, "", payload)
+ for transport in targets:
+ try:
+ transport.write(frame)
+ except Exception:
+ # One wedged peer must not stall the rest; disconnect teardown
+ # unregisters it.
+ logger.debug("global-event broadcast write failed type=%s", event, exc_info=True)
def _approval_request_payload(data: dict | None) -> dict:
@@ -3722,891 +2352,6 @@ def _sess_building(params, rid):
return (s, None)
-def _normalize_completion_path(path_part: str) -> str:
- expanded = os.path.expanduser(path_part)
- if os.name != "nt":
- normalized = expanded.replace("\\", "/")
- if (
- len(normalized) >= 3
- and normalized[1] == ":"
- and normalized[2] == "/"
- and normalized[0].isalpha()
- ):
- return f"/mnt/{normalized[0].lower()}/{normalized[3:]}"
- return expanded
-
-
-def _completion_cwd(params: dict | None = None) -> str:
- params = params or {}
- 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.
- or _profile_configured_cwd(_profile_home(params.get("profile")))
- # The launch profile's dashboard /chat attaches to the dashboard's
- # in-memory gateway, which does NOT inherit the PTY child's bridged
- # TERMINAL_CWD. Read the launch profile's config.yaml directly so a
- # configured terminal.cwd wins over a stale process env / launch dir.
- or _launch_configured_cwd()
- or os.environ.get("TERMINAL_CWD")
- or os.getcwd()
- )
- try:
- resolved = os.path.abspath(os.path.expanduser(str(raw)))
- if os.path.isdir(resolved):
- return resolved
- except Exception:
- pass
- return os.getcwd()
-
-
-def _terminal_task_cwd(session: dict | None) -> str:
- """Return the cwd that terminal_tool should use for this TUI session.
-
- ``_completion_cwd`` validates paths on the host so file completion does not
- point at nonsense. Non-local terminal backends are different: their cwd is
- inside the target environment, so an SSH path like /home/user/workspace may
- not exist on the local macOS host but is still the correct execution cwd.
-
- When ``TERMINAL_ENV`` is unset (dashboard/TUI process) the config's
- ``terminal.backend`` is consulted as a fallback so the non-local cwd
- resolution path is taken even when the dashboard entrypoint did not call
- ``apply_terminal_config_to_env`` on its own ``os.environ``.
- """
- return _terminal_task_cwd_with_source(session)[0]
-
-
-def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:
- """Like :func:`_terminal_task_cwd` but also names the value's ORIGIN.
-
- Returns ``(cwd, source)`` where source is:
-
- * ``"session"`` — the workspace the user attached to THIS session
- (``explicit_cwd``), or this session's own tracked directory.
- * ``"process"`` — the process-global ``TERMINAL_CWD`` env var / config
- ``terminal.cwd`` fallback. On a shared-container backend this is the
- normal seed; under per-session docker isolation it is a launch
- artifact from a PREVIOUS session (the workspace picker persists it
- process-wide) and must never become a fresh session's bind mount —
- terminal_tool refuses ``cwd_source: "process"`` as a mount source.
- """
- backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
- if not backend or backend == "local":
- # Fall back to config when TERMINAL_ENV is unset (dashboard/TUI process
- # never calls apply_terminal_config_to_env on os.environ).
- try:
- terminal_cfg = _load_cfg().get("terminal", {})
- if isinstance(terminal_cfg, dict):
- cfg_backend = str(terminal_cfg.get("backend") or "").strip().lower()
- if cfg_backend and cfg_backend != "local":
- backend = cfg_backend
- except Exception:
- pass
-
- if backend and backend != "local":
- # A workspace the user explicitly attached to THIS session wins over
- # the process-global env var — the env var is whatever the LAST
- # session's picker wrote, not this session's choice.
- if session and session.get("explicit_cwd") and session.get("cwd"):
- return str(session["cwd"]), "session"
- raw = os.environ.get("TERMINAL_CWD", "").strip()
- if not raw:
- try:
- terminal_cfg = _load_cfg().get("terminal", {})
- if isinstance(terminal_cfg, dict):
- raw = str(terminal_cfg.get("cwd") or "").strip()
- except Exception:
- raw = ""
- if raw and raw not in {".", "auto", "cwd"}:
- return raw, "process"
- if backend == "ssh":
- return "~", "process"
-
- if session and session.get("cwd"):
- return str(session["cwd"]), "session"
- return _completion_cwd(), "process"
-
-
-# Git working-tree probing (run git, resolve roots, fold worktrees) lives in a
-# focused, single-flight-cached module; these stay as the in-server names every
-# call site already uses.
-_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
-_resolve_cwd_git = git_probe.resolve
-
-
-def _session_cwd(session: dict | None) -> str:
- if session and session.get("cwd"):
- return str(session["cwd"])
- return _completion_cwd()
-
-
-# Sources whose launch directory is an artifact of how the app was started, not
-# a workspace the user picked. Everything else is terminal-started: the process
-# runs in a directory the user deliberately cd'd into.
-_LAUNCH_CWD_NOT_A_WORKSPACE = {"desktop"}
-
-
-def _context_cwd_is_launch_artifact(session: dict | None) -> bool:
- """Whether the session cwd came from app launch rather than user intent."""
- return bool(
- session
- and not session.get("explicit_cwd")
- and _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE
- )
-
-
-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 why the launch directory counts as a
- workspace for terminal sessions but not for the desktop.
- """
- 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. `_session_cwd` falls back to the
- # gateway-wide completion cwd, which belongs to no session in particular —
- # stamping that would invent a workspace for a session that never had one.
- return str(session.get("cwd") or "") or None
-
-
-def _heal_dead_cwd(cwd: str) -> str:
- """Resolve a session cwd that points at a now-deleted directory.
-
- A session anchored to a linked worktree (``<repo>/.worktrees/<name>``) keeps
- that path after the worktree is removed (branch merged, `git worktree
- remove`, etc). The literal dir is gone, so a probe of it returns nothing and
- the composer shows no branch — while the sidebar still folds the path up to
- the repo's main lane. Heal the mismatch: walk up to the first existing
- ancestor, then resolve its common git root, so a dead-worktree cwd collapses
- to the live repo root (and its real current branch).
-
- Only meaningful for local backends; a remote/SSH cwd may legitimately not
- exist on the host, so callers must skip healing there.
- """
- raw = (cwd or "").strip()
- if not raw or os.path.isdir(raw):
- return raw
-
- probe = raw
- # Climb to the first ancestor that still exists on disk.
- for _ in range(64):
- parent = os.path.dirname(probe)
- if not parent or parent == probe:
- break
- probe = parent
- if os.path.isdir(probe):
- break
-
- if not os.path.isdir(probe):
- return raw
-
- try:
- root = _git_common_repo_root_for_cwd(probe) or _git_repo_root_for_cwd(probe)
- except Exception:
- root = ""
-
- return root or probe
-
-
-def _is_local_terminal_backend() -> bool:
- backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
- return not backend or backend == "local"
-
-
-def _effective_terminal_backend() -> str:
- """Active terminal backend name (``local``, ``docker``, ``ssh``, ...).
-
- ``TERMINAL_ENV`` is authoritative when set (launchers bridge
- ``terminal.backend`` into env at startup). Desktop/TUI in-process gateways
- skip that bridge, so fall back to the ``terminal.backend`` config key —
- the same rule ``_terminal_task_cwd`` uses.
- """
- backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
- if not backend or backend == "local":
- try:
- terminal_cfg = _load_cfg().get("terminal", {})
- if isinstance(terminal_cfg, dict):
- cfg_backend = str(terminal_cfg.get("backend") or "").strip().lower()
- if cfg_backend and cfg_backend != "local":
- backend = cfg_backend
- except Exception:
- pass
- return backend or "local"
-
-
-def _display_session_cwd(session: dict | None) -> str:
- """Session cwd for display/probe surfaces, healed past deleted worktrees.
-
- Persists the healed value back to the session row (best-effort, local only)
- so the next load is already coherent and the sidebar lane stops showing a
- session pinned to a vanished path.
- """
- cwd = _session_cwd(session)
- if not _is_local_terminal_backend():
- return cwd
-
- healed = _heal_dead_cwd(cwd)
- if healed and healed != cwd and session is not None:
- session["cwd"] = healed
- _persist_session_cwd_and_schedule_git_meta(session, healed)
-
- return healed
-
-
-def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:
- """Re-anchor a session that SETTLED in another git checkout. Returns moved.
-
- An agent told to work in a fresh worktree does exactly that — `git worktree
- add`, `cd` into it, and every later command runs there — but the session
- stayed pinned to wherever it started, so the desktop kept labelling the chat
- with the primary checkout's branch while all the work landed elsewhere.
-
- A plain `cd` is deliberately NOT a workspace move (see
- ``_apply_project_workspace``): browsing to /tmp to read a log must not
- re-home the chat. What we adopt here is narrower — the session's recorded
- cwd is in a DIFFERENT working tree of the SAME repository (the shape
- ``git worktree add`` produces). Everything else — a non-git workspace
- stepping into a repo, or a git workspace visiting an unrelated repo — is
- a browsing visit, and a user's explicitly chosen workspace is never
- overridden at all.
-
- Local backends only: a remote/SSH cwd names a path on the host, which this
- gateway can neither stat nor probe with git.
- """
- if not session or not _is_local_terminal_backend():
- return False
-
- # A workspace the user (or GUI) explicitly chose is never overridden by
- # where the agent's terminal happened to settle — only another explicit
- # action (`_set_session_cwd`, a project switch) moves it. A cwd this very
- # function adopted is marked `cwd_from_settle` so a session can keep
- # following the agent through successive worktrees.
- if session.get("explicit_cwd") and not session.get("cwd_from_settle"):
- return False
-
- try:
- from tools.terminal_tool import get_session_cwd
-
- recorded = get_session_cwd(session.get("session_key") or "")
- except Exception:
- return False
-
- if not recorded:
- return False
-
- resolved = os.path.abspath(os.path.expanduser(str(recorded)))
- current = os.path.abspath(os.path.expanduser(_session_cwd(session)))
- if resolved == current or not os.path.isdir(resolved):
- return False
-
- # The worktree ROOT, not the common repo root: folding worktrees together
- # here is exactly what hides the move we're looking for.
- landed = _git_repo_root_for_cwd(resolved)
- current_root = _git_repo_root_for_cwd(current)
- # A relocation is a move between two DIFFERENT git working trees. When the
- # session's own workspace is not in a git repo, the agent stepping into one
- # to read a file or run a command is a browsing visit, not a re-home:
- # adopting it would hijack a non-git workspace onto whatever repo a tool
- # call touched first (e.g. a home-directory session pinned to the checkout
- # it read a file from).
- if not landed or not current_root or landed == current_root:
- return False
-
- # And only between checkouts of the SAME repository — the shape a real
- # `git worktree add` produces (linked worktrees share the common .git
- # dir). Settling in an UNRELATED repo (`cd ~/other-project && git log`)
- # is likewise a visit: adopting it would re-home the chat onto whatever
- # foreign repo the terminal last touched.
- landed_common = _git_common_repo_root_for_cwd(resolved)
- current_common = _git_common_repo_root_for_cwd(current)
- if not landed_common or landed_common != current_common:
- return False
-
- session["cwd"] = resolved
- # The session works here now, so this is its workspace — a desktop chat
- # whose cwd was an unpersisted launch artifact earns a real row. The
- # settle marker keeps this adoption overridable by the NEXT settle while
- # still yielding to a user's explicit choice (see the guard above).
- session["explicit_cwd"] = True
- session["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 turn is over, so the agent has stopped moving: this is the one moment
- where its recorded cwd is a stable answer to "where does this session
- work". Reconciling before building the payload means the same event that
- already tells the desktop the turn ended also carries the new cwd/branch —
- the client follows it with no new event type and no extra round trip.
- """
- try:
- _reconcile_session_cwd_from_terminal(session)
- except Exception:
- logger.debug("failed to reconcile settled session cwd", exc_info=True)
- _emit("session.info", sid, _session_info(agent, session))
-
-
-def _session_source(session: dict | None) -> str:
- if session:
- source = str(session.get("source") or "").strip()
- if source:
- return source
- return _resolve_session_platform()
-
-
-def _register_session_cwd(session: dict | None) -> None:
- if not session:
- return
- try:
- from tools.terminal_tool import register_task_env_overrides
-
- cwd, cwd_source = _terminal_task_cwd_with_source(session)
- register_task_env_overrides(
- session["session_key"], {"cwd": cwd, "cwd_source": cwd_source}
- )
- except Exception:
- pass
-
-
-def _ensure_session_db_row(session: dict) -> bool:
- """Idempotently persist the session's DB row on first real activity.
-
- Called from prompt.submit so a row only exists once the user actually sends
- a message — abandoned drafts never leave an empty "Untitled" session behind.
- Uses INSERT OR IGNORE under the hood, so re-calls (and the AIAgent's own
- lazy create) are no-ops.
- Returns False only when the store is unavailable (no openable state.db);
- prompt.submit turns that into an RPC error so a send fails loudly with a
- toast instead of streaming into a store that will never save it (#98924).
- Every other outcome — no key, best-effort attempt, success — is True.
-
- A cwd the user *chose* is always persisted. When they made no explicit
- choice the launch directory stands in, and whether that is meaningful
- depends on how the session was started:
-
- * The desktop launches from wherever the app bundle was opened (often ``/``
- or the user's home), so stamping that would file every unpicked chat under
- a folder the user never chose. Those stay null and group under "No
- workspace", which is the desired default.
- * A terminal session (``hermes`` / ``hermes --tui`` / CLI) is started from a
- directory the user deliberately ``cd``'d into — that IS the workspace, and
- it is also where the agent's terminal actually runs. Dropping it stranded
- the session with no cwd AND no git_repo_root, so the sidebar could never
- place it under its project.
- """
- 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 row lands in the wrong state.db, the
- # unified list mis-tags it, and resume 404s ("session not found").
- profile_home = session.get("profile_home")
- if profile_home:
- from hermes_state import SessionDB
-
- try:
- from hermes_state import get_shared_session_db
- db = get_shared_session_db(Path(profile_home) / "state.db")
- except Exception:
- logger.debug("failed to open profile db for session row", exc_info=True)
- return False
- close_db = True
- else:
- db = _get_db()
- close_db = False
- if db is None:
- # Fail loud ONLY when the store actually failed to open (#98924):
- # _db_error records the SessionDB open exception. A None db with no
- # recorded error means "no store in this context" (degraded harness,
- # store deliberately absent) — that keeps the pinned best-effort
- # contract and stays True.
- return _db_error is None
- # The session's own model/effort/fast pick — the composer override shipped on
- # session.create, or a restored /model switch — must own the row's model +
- # model_config. The agent isn't built yet at first prompt.submit, so derive
- # the row from the live override dict; fall back to the global resolved model
- # only when this chat made no explicit pick. Writing the global default here
- # used to win the INSERT-OR-IGNORE race against the agent's own correct
- # lazy-create, so a reconnect/resume rebuilt from the global model and
- # silently reverted the chat (e.g. picked gpt-5.5, reconnect snapped back to
- # the profile default). model_config carries provider/reasoning/service_tier
- # so resume restores effort + fast too, not just the model name.
- 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 = {}
- for src_key, cfg_key in (
- ("model", "model"),
- ("provider", "provider"),
- ("base_url", "base_url"),
- ("api_mode", "api_mode"),
- ):
- if val := override.get(src_key):
- model_config[cfg_key] = str(val)
- # The composer override may carry the RESOLVED provider "custom" for a named
- # ``providers:`` / ``custom_providers:`` entry. Persisting bare "custom" here
- # (the very first DB write for a fresh desktop session, before the agent is
- # built) is the origin of the recurring "No LLM provider configured" rows:
- # on the next resume bare "custom" routes to OpenRouter with no key. Recover
- # the durable ``custom:<name>`` identity from the override's base_url, else
- # the configured provider, so a routable identity is persisted from the
- # start (matches _runtime_model_config's normalization).
- if str(model_config.get("provider") or "").strip().lower() == "custom":
- try:
- from hermes_cli.runtime_provider import canonical_custom_identity
-
- healed = canonical_custom_identity(
- base_url=model_config.get("base_url") or None,
- model=model_config.get("model") or row_model or None,
- )
- if healed:
- model_config["provider"] = healed
- except Exception:
- logger.debug(
- "custom provider identity recovery failed (db row)", exc_info=True
- )
- if (reasoning := session.get("create_reasoning_override")) is not None:
- model_config["reasoning_config"] = reasoning
- create_service_tier_override = session.get("create_service_tier_override")
- if create_service_tier_override is not None:
- # Empty string is the in-memory sentinel for an explicit normal tier:
- # it bypasses _make_agent's profile fallback without sending a bogus
- # service_tier value to the provider. Persist a durable marker so resume
- # can distinguish that choice from an omitted/inherited tier.
- model_config["service_tier"] = create_service_tier_override or "normal"
- # Branch lineage: stamp the same ``_branched_from`` marker the TUI /branch
- # uses so list_sessions_rich keeps the branch listed and the desktop sidebar
- # can nest it under its parent.
- parent_session_id = session.get("parent_session_id") or None
- if parent_session_id:
- model_config["_branched_from"] = parent_session_id
- # Bot-Mode room plumbing sessions are per-member scratch conversations
- # inside a group chat: their runtime must ALWAYS follow the member profile's
- # CURRENT config, never the provider that was pinned when the row was first
- # written. Persist that contract explicitly so resume can distinguish room
- # plumbing from a normal user chat (whose stored model/provider must be
- # restored verbatim). See _stored_session_runtime_overrides.
- if session.get("room_plumbing"):
- model_config["room_plumbing"] = True
- # Bot-Mode canonical chats (the ONE forever DM per bot) and room plumbing
- # sessions are plugin-owned scratch conversations: their runtime must ALWAYS
- # follow the member profile's CURRENT config, never the model/provider that
- # was pinned when the row was first written. Persist that contract explicitly
- # so resume can distinguish them from a normal user chat (whose stored
- # model/provider must be restored verbatim). See
- # _stored_session_runtime_overrides.
- if session.get("follow_profile_config"):
- model_config["follow_profile_config"] = True
- try:
- db.create_session(
- key,
- source=_session_source(session),
- model=row_model,
- model_config=model_config or None,
- parent_session_id=parent_session_id,
- cwd=_persisted_session_cwd(session),
- # Self-describing rows: aggregators that merge multiple profile DBs
- # into one list can't rely on which file a row came from alone.
- # Stamp the launch profile explicitly instead of leaving NULL —
- # NULL is exactly what the #94724 legacy-owner backfill exists to
- # repair, and rows minted AFTER that one-shot backfill ran stayed
- # NULL forever: profile-keyed matching then drops them from the
- # sidebar and deep links can't resolve them (#99222).
- profile_name=(
- Path(profile_home).name if profile_home else _current_profile_name()
- ),
- )
- # A session can be born hidden (session.create hidden=true, or a
- # session.set_hidden that arrived before the row existed): apply the
- # deferred intent now that the row exists, mirroring 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: if we swallow it here, prompt.submit
- # returns {"status":"streaming"} and the user's message vanishes with
- # no toast. Re-raise so the submit handler can return a real RPC error.
- from hermes_state import is_disk_full_error
-
- if is_disk_full_error(exc):
- raise
- logger.debug("failed to persist desktop session row", exc_info=True)
- finally:
- if close_db:
- try:
- from hermes_state import release_or_close
- release_or_close(db)
- except Exception:
- pass
- return True
-
-
-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"]`` (they ride into the agent as ``conversation_history``,
- which ``_flush_messages_to_session_db`` skips by identity). Without this the
- branch row would resume missing its pre-branch context. Runs once; the row +
- parent link are written by ``_ensure_session_db_row`` just before this.
- """
- if not session.get("parent_session_id") or session.get("_branch_seed_persisted"):
- return
- key = session.get("session_key")
- if not key:
- return
- with session["history_lock"]:
- seed = [dict(msg) for msg in (session.get("history") or [])]
- if not seed:
- return
- with _session_db(session) as db:
- if db is None:
- return
- try:
- # Bounded-chunk transactions (see #23254): a branch seed can be
- # hundreds of rows; chunking keeps each BEGIN IMMEDIATE short so
- # concurrent writers aren't starved. Recovery semantics match the
- # old per-row loop (mid-copy failure leaves a partial seed with
- # _branch_seed_persisted unset).
- db.append_messages_batch(
- key,
- [
- {
- "role": msg.get("role", "user"),
- "content": msg.get("content"),
- "reasoning": msg.get("reasoning"),
- "reasoning_content": msg.get("reasoning_content"),
- "reasoning_details": msg.get("reasoning_details"),
- "codex_reasoning_items": msg.get("codex_reasoning_items"),
- "codex_message_items": msg.get("codex_message_items"),
- # Timeline markers (model_switch, personality_switch,
- # auto_continue, …) ride as role=user; dropping the tag
- # here re-planted them as bare user turns after a
- # restart, corrupting the truncate ordinal address
- # space the same way #82756 did.
- "display_kind": msg.get("display_kind"),
- "display_metadata": msg.get("display_metadata"),
- # Preserve the parent's original message timestamps —
- # append_message would otherwise stamp time.time() and the
- # branch's copied history would all appear authored "now".
- "timestamp": msg.get("timestamp"),
- }
- for msg in seed
- ],
- chunk_rows=500,
- )
- session["_branch_seed_persisted"] = True
- except Exception as exc:
- from hermes_state import is_disk_full_error
-
- if is_disk_full_error(exc):
- raise
- logger.debug("branch seed persist failed", exc_info=True)
-
-
-def _session_db(session: dict):
- """Yield the SessionDB that owns this session's row (profile-aware).
-
- Mirrors :func:`_ensure_session_db_row`: a remote/profile session persists
- into its own profile's ``state.db`` (a fresh handle we close on exit);
- everything else borrows the shared ``_get_db()`` handle (left open). Yields
- None when the db is unavailable.
- """
- db, close_db = None, False
- profile_home = session.get("profile_home")
- if profile_home:
- from hermes_state import SessionDB
-
- try:
- from hermes_state import get_shared_session_db
- db, close_db = get_shared_session_db(Path(profile_home) / "state.db"), True
- except Exception:
- logger.debug("failed to open profile db for session", exc_info=True)
- else:
- db = _get_db()
- try:
- yield db
- finally:
- if close_db and db is not None:
- with contextlib.suppress(Exception):
- from hermes_state import release_or_close
- release_or_close(db)
-
-
-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.
-
- The caller holds ``history_lock``. Persistent sessions archive the target
- and tail; a composite carrier's own hidden handoff is inserted in that same
- transaction. Memory is installed only after the durable commit and is
- built from the already-validated prefix plus the returned scaffold row id,
- so there is no fallible post-commit reload.
- """
- from agent.context_compressor import (
- 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):
- content = _multimodal_text_summary(content)
- elif isinstance(content, list):
- text_parts = []
- for part in content:
- if isinstance(part, dict) and part.get("type") == "text":
- text_parts.append(str(part.get("text", "")))
- elif (
- isinstance(part, dict)
- and part.get("type") in {"image", "image_url", "input_image"}
- ):
- text_parts.append("[screenshot]")
- content = "\n".join(text_parts) if text_parts else None
- if message.get("role") in {"user", "assistant"} and isinstance(content, str):
- return sanitize_context(content).strip()
- return content
-
- history = _history_without_ephemeral_scaffolding(session.get("history", []))
- user_indices = [
- index
- for index, message in enumerate(history)
- if user_originated_turn_view(message) is not None
- ]
- if user_ordinal < 0 or user_ordinal >= len(user_indices):
- raise ValueError("target user message is no longer in session history")
- target_index = user_indices[user_ordinal]
- installed, live_view = history_before_user_originated_turn(history, target_index)
- rewound_count = len(history) - target_index
-
- session_key = str(session.get("session_key") or "").strip()
- persisted = False
- if session_key:
- with _session_db(session) as db:
- if db is None:
- raise RuntimeError("session database is unavailable")
- expected_active_ids = db.get_active_message_ids(session_key)
- durable = db.get_messages_as_conversation(
- session_key,
- include_row_ids=True,
- )
- durable_user_indices = [
- index
- for index, message in enumerate(durable)
- if user_originated_turn_view(message) is not None
- ]
- if len(durable_user_indices) != len(user_indices):
- raise RuntimeError(
- "session history changed before the rewind could be persisted"
- )
- durable_target_index = durable_user_indices[user_ordinal]
- durable_target = durable[durable_target_index]
- durable_prefix, durable_live_view = history_before_user_originated_turn(
- durable, durable_target_index
- )
- if _comparison_content(durable_live_view) != _comparison_content(live_view):
- raise RuntimeError(
- "session history changed before the rewind could be persisted"
- )
- target_row_id = durable_target.get("_row_id")
- if not isinstance(target_row_id, int):
- raise RuntimeError("rewind target has no durable row identity")
- if require_retryable:
- 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"),
- )
- 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
- installed[-1] = durable_prefix[-1]
- # Current clients address destructive follow-ups by durable row id.
- # Preserve the richer warm content (for example image parts), but
- # copy row identities when the retained warm/durable 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):
- row_id = durable_message.get("_row_id")
- if isinstance(row_id, int):
- warm["_row_id"] = row_id
- live_view = durable_live_view
- rewound_count = int(result.get("rewound_count", 0))
- persisted = True
- elif require_retryable:
- retryable_user_text(live_view.get("content"))
-
- installed = [message.copy() for message in installed]
- session["history"] = installed
- session["history_version"] = int(session.get("history_version", 0)) + 1
- agent = session.get("agent")
- if agent is not None:
- agent._session_messages = installed
- if hasattr(agent, "_last_flushed_db_idx"):
- agent._last_flushed_db_idx = len(installed) if persisted else 0
- if hasattr(agent, "_db_flush_scan_prefix"):
- agent._db_flush_scan_prefix = installed[:] if persisted else None
- return installed, live_view, rewound_count
-
-
-def _history_without_ephemeral_scaffolding(history: list[dict]) -> list[dict]:
- """Return the durable transcript shape without transient recovery rows."""
- from run_agent import _is_ephemeral_scaffolding
-
- return [
- message.copy()
- for message in history
- if not _is_ephemeral_scaffolding(message)
- ]
-
-
-def _persist_session_git_meta(session: dict, cwd: str, generation: int) -> None:
- """Resolve + persist a session's git branch / repo root WITHOUT blocking.
-
- Branch and root come from ``git`` subprocess probes; running them inline on
- the session-init / cwd-set path would stall startup whenever ``cwd`` is slow
- or on an unreachable mount. Run them on a short-lived daemon thread instead
- and persist via the same profile-aware db the caller writes ``cwd`` to.
-
- Best-effort: ``cwd`` itself is persisted synchronously by the caller, so a
- probe failure just leaves these enrichment columns unset (the project tree
- falls back to its live resolver / lazy backfill). Daemon, so a mid-flight
- probe never delays gateway shutdown.
- """
- session_key = session.get("session_key", "")
- if (
- not session_key
- or not cwd
- or isinstance(generation, bool)
- or not isinstance(generation, int)
- or generation < 1
- ):
- return
- # Snapshot the routing fields now; the live session dict may be gone by the
- # time the thread runs. `_session_db` reopens the profile-correct db inside.
- db_session = {"session_key": session_key, "profile_home": session.get("profile_home")}
-
- def _run() -> None:
- try:
- branch = _git_branch_for_cwd(cwd)
- root = _git_common_repo_root_for_cwd(cwd)
- if not (branch or root):
- return
- with _session_db(db_session) as db:
- if db is not None:
- db.publish_session_git_metadata(
- session_key,
- cwd,
- generation,
- branch,
- root,
- )
- except Exception:
- logger.debug("failed to persist session git metadata", exc_info=True)
-
- threading.Thread(target=_run, name="git-meta", daemon=True).start()
-
-
-def _persist_session_cwd_and_schedule_git_meta(
- session: dict,
- cwd: str,
- *,
- db=None,
-) -> int | None:
- """Claim a DB-backed probe generation, then start Git enrichment."""
- try:
- if db is not None:
- generation = db.update_session_cwd(
- session.get("session_key", ""), cwd
- )
- else:
- with _session_db(session) as owner_db:
- if owner_db is None:
- return None
- generation = owner_db.update_session_cwd(
- session.get("session_key", ""), cwd
- )
- except Exception:
- logger.debug("failed to persist session cwd", exc_info=True)
- return None
-
- if (
- isinstance(generation, bool)
- or not isinstance(generation, int)
- or generation < 1
- ):
- return None
- _persist_session_git_meta(session, cwd, generation)
- return generation
-
-
-def _set_session_cwd(session: dict, cwd: str) -> str:
- from hermes_constants import translate_cwd_for_wsl_backend
-
- cwd = translate_cwd_for_wsl_backend(str(cwd))
- 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 — persist it as the workspace (and let a later
- # lazy row creation persist it too, not the launch-dir fallback).
- session["explicit_cwd"] = True
- # A user's choice supersedes any earlier settle-adopted cwd: from here on
- # the terminal wandering must not move the workspace again.
- session["cwd_from_settle"] = False
- _register_session_cwd(session)
- # The synchronous DB write claims ordering authority; Git subprocesses stay
- # off the hot path and may publish only for that exact generation.
- _persist_session_cwd_and_schedule_git_meta(session, resolved)
- try:
- from tools.terminal_tool import cleanup_vm
-
- cleanup_vm(session["session_key"])
- except Exception:
- pass
- return resolved
-
-
# ── Config I/O ────────────────────────────────────────────────────────
@@ -10482,6 +8227,9 @@ from . import ( # noqa: E402
change_watcher as _change_watcher,
session_compression as _session_compression,
model_switch as _model_switch,
+ compute_host_bridge as _compute_host_bridge,
+ session_workdir as _session_workdir,
+ session_lifecycle as _session_lifecycle,
methods_browser_control as _methods_browser_control,
methods_bot_relay as _methods_bot_relay,
methods_complete as _methods_complete,
@@ -10495,6 +8243,9 @@ from . import ( # noqa: E402
)
for _m in (
+ _session_lifecycle,
+ _session_workdir,
+ _compute_host_bridge,
_model_switch,
_session_compression,
_change_watcher,
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
new file mode 100644
index 00000000000..96e69614381
--- /dev/null
+++ b/tui_gateway/session_lifecycle.py
@@ -0,0 +1,1034 @@
+"""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 (see
+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()
+
+
+def _notify_session_boundary(
+ event_type: str, session_id: str | None, platform: str | None = None
+) -> None:
+ """Fire session lifecycle hooks with CLI parity."""
+ try:
+ from hermes_cli.lifecycle import finalize_session, invoke_hook
+
+ if event_type == "on_session_finalize":
+ finalize_session(
+ session_id=session_id,
+ platform=_resolve_agent_platform(platform),
+ )
+ else:
+ invoke_hook(
+ event_type,
+ session_id=session_id,
+ platform=_resolve_agent_platform(platform),
+ )
+ except Exception:
+ pass
+
+
+_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",
+})
+
+
+def _claim_active_session_slot(
+ session_key: str,
+ *,
+ live_session_id: str,
+ surface: str = "tui",
+ profile_home: str | Path | None = None,
+) -> tuple[Any, str | None]:
+ track_liveness = str(surface or "").strip().lower() == "desktop"
+ 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,
+ track_liveness=track_liveness,
+ )
+ except Exception as exc:
+ logger.warning("Failed to claim active session slot: %s", exc)
+ # Fail CLOSED regardless of surface: per-session exclusivity is a
+ # correctness guarantee (see PER_SESSION_EXCLUSIVE_SUBMIT), and a
+ # claim that errors out has NOT proven the session is unowned.
+ # Proceeding without a lease here is the silent double-writer hole
+ # flagged in the #94595 review (blocker 2).
+ 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 / session.resume deliberately do NOT claim one. Every
+ desktop tile paint, background reconnect-resume and abandoned draft opens a
+ session just to paint a composer, and a slot held by one of those is
+ invisible everywhere: an unprompted draft has no DB row, and the sidebar
+ filters it out with min_messages=1. Idle desktop tabs therefore silently
+ starved the messaging gateway, which shares this cap — five parked tabs on
+ a websocket-flappy host locked a Discord bot out of a 5-slot cap while
+ running no agents at all. Claiming on the first turn mirrors the lazy
+ contract _ensure_session_db_row already uses for the row itself, and keeps
+ the invariant that anything holding a slot is something the user can see.
+ """
+ if session.get("active_session_lease") is not None:
+ return None
+ lease, limit_message = _claim_active_session_slot(
+ str(session.get("session_key") or ""),
+ live_session_id=sid,
+ surface=_session_source(session),
+ profile_home=session.get("profile_home"),
+ )
+ if limit_message is not None:
+ return limit_message
+ session["active_session_lease"] = lease
+ return None
+
+
+def _release_active_session_lease(lease) -> bool:
+ 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))
+ released = getattr(lease, "released", True)
+ enabled = getattr(lease, "enabled", True)
+ return bool(released or not enabled)
+
+
+def _release_active_session_slot(session: dict | None) -> bool:
+ if not session:
+ return True
+ lease = session.get("active_session_lease")
+ if _release_active_session_lease(lease):
+ if session.get("active_session_lease") is lease:
+ session.pop("active_session_lease", None)
+ return True
+ return False
+
+
+def _other_runtime_lease_guard(session_id: str, session: dict):
+ """Release this runtime and lock sibling ownership through the DB write."""
+ lease = session.get("active_session_lease")
+ try:
+ from hermes_cli.active_sessions import (
+ active_session_liveness_guard,
+ release_active_session_liveness_guard,
+ )
+ except Exception as exc:
+ 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:
+ logger.warning(
+ "Failed to inspect active session leases; preserving session %s: %s",
+ session_id,
+ last_error,
+ )
+ yield True
+ return
+ try:
+ yield active
+ finally:
+ stack.close()
+ if (
+ lease is not None
+ and getattr(lease, "released", False)
+ and session.get("active_session_lease") is lease
+ ):
+ session.pop("active_session_lease", None)
+
+
+def _transfer_active_session_slot(
+ sid: str,
+ session: dict,
+ *,
+ new_session_id: str,
+) -> bool:
+ if not new_session_id:
+ return False
+ lease = session.get("active_session_lease")
+ if lease is None:
+ return True
+ try:
+ from hermes_cli.active_sessions import transfer_active_session
+
+ if transfer_active_session(
+ lease,
+ session_id=new_session_id,
+ metadata={"live_session_id": sid},
+ ):
+ return True
+ except Exception:
+ logger.debug("Failed to transfer active session slot", exc_info=True)
+
+ if getattr(lease, "track_liveness", False):
+ return False
+
+ # Fallback: the in-place transfer could not move the lease (entry pruned /
+ # pid-check transiently failed). Reserve the new slot BEFORE releasing the
+ # old one, so a concurrent gateway at the session cap cannot grab the freed
+ # slot in a release-then-reacquire window and leave this session with no
+ # lease at all (#49041 review). If the reserve fails, 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 not None:
+ 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)
+ session["active_session_lease"] = new_lease
+ return True
+ # Reserve failed — retain the existing lease rather than dropping it.
+ if limit_message:
+ logger.warning(
+ "Compression session lease re-anchor failed (kept old lease): "
+ "sid=%s new_session_id=%s reason=%s",
+ sid,
+ new_session_id,
+ limit_message,
+ )
+ return False
+
+
+# Session sources the TUI/desktop backend must never end in state.db: the
+# messaging gateway owns those sessions' lifecycle — the TUI is only a viewer
+# (a resume of a Telegram/Discord/... session). Ending one creates the
+# #60609 Groundhog Day routing loop (see _finalize_session). Sources the
+# TUI backend itself creates ("tui", plus whatever a client passes as its
+# own ``source``) and the CLI's own sessions 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`` names a messaging-gateway platform whose session
+ lifecycle belongs to the gateway, not to this TUI backend.
+
+ Structural rather than a hardcoded platform list: any source that
+ resolves to a known gateway ``Platform`` (built-in enum member OR a
+ registered platform plugin, via ``Platform._missing_``) counts, so new
+ platforms are covered automatically. Local/self-owned sources are
+ excluded explicitly — ``local``/``webhook``/``api_server`` are Platform
+ members but their sessions are not owned by a remote chat surface that
+ routes by session_key, so reaping them is safe and keeps /resume clean.
+ """
+ src = (source or "").strip().lower()
+ if src in _NON_GATEWAY_SOURCES:
+ return False
+ try:
+ from gateway.config import Platform
+
+ Platform(src) # raises ValueError for arbitrary non-platform strings
+ return True
+ except Exception:
+ return False
+
+
+def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> None:
+ """Best-effort finalize hook + memory commit for a session.
+
+ Fires ``on_session_end`` plugin hook and attempts to persist any
+ unflushed messages before closing the session. This mirrors the
+ CLI's exit-path behaviour and prevents data loss when the TUI is
+ force-quit (double Ctrl‑C, terminal‑close, SIGHUP) while the agent
+ is mid‑turn.
+ """
+ if not session or session.get("_finalized"):
+ return
+ session["_finalized"] = True
+ history_ready = session.get("resume_history_ready")
+ if history_ready is not None and not history_ready.is_set():
+ session["resume_history_error"] = "session resume cancelled"
+ history_ready.set()
+ _desktop_automatic_cleanup = bool(
+ end_reason in _AUTOMATIC_SESSION_END_REASONS
+ and _session_source(session).strip().lower() == "desktop"
+ )
+ # Automatic Desktop cleanup removes 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)
+ stop_event = session.get("_notif_stop")
+ if stop_event is not None:
+ stop_event.set()
+
+ agent = session.get("agent")
+ lock = session.get("history_lock")
+ if lock is not None:
+ with lock:
+ history = list(session.get("history", []))
+ else:
+ history = list(session.get("history", []))
+
+ # ── Persist unflushed messages to SQLite ──────────────────────────
+ # Flush ``agent._session_messages`` via ``_persist_session``'s marker-based
+ # dedup (same contract as the gateway-shutdown flush, #13121). Do NOT pass
+ # ``conversation_history``: ``session["history"]`` and ``_session_messages``
+ # alias the SAME list once a turn completes, so passing it made
+ # ``_flush_messages_to_session_db`` treat every message as already-durable
+ # and skip it — a data-loss bug when finalize is the sole persist path after
+ # a WS disconnect/restart (e.g. the in-turn flush hit a transient SQLite
+ # failure). Markers persist the genuinely-unflushed tail without duplicating
+ # durable rows (including a resumed-but-not-run session's already-in-DB
+ # transcript, which stays in ``session["history"]`` only).
+ if agent is not None and hasattr(agent, "_persist_session"):
+ snapshot = getattr(agent, "_session_messages", None)
+ if snapshot:
+ try:
+ agent._persist_session(snapshot)
+ except Exception:
+ pass
+
+ # ── Plugin hook: on_session_end ────────────────────────────────────
+ # Signals every plugin that the session is closing, with
+ # interrupted=True so crash‑recovery plugins can flush buffers,
+ # persist state, or close connections before the gateway exits.
+ # Mirrors cli.py's atexit handler that fires the same hook when
+ # the user Ctrl‑C's mid‑turn.
+ if agent is not None:
+ try:
+ from hermes_cli.lifecycle import invoke_hook
+
+ invoke_hook(
+ "on_session_end",
+ 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",
+ )
+ except Exception:
+ pass
+
+ if agent is not None and history and hasattr(agent, "commit_memory_session"):
+ try:
+ agent.commit_memory_session(history)
+ except Exception:
+ pass
+
+ 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))
+
+ # Mark session ended in DB so it doesn't linger as a ghost row in /resume.
+ # Use session_id (from agent.session_id) not session_key — after compression,
+ # session_key may be stale (the ended parent) while session_id is the live
+ # continuation. Fix for #20001.
+ 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)
+ )
+ with _lifecycle_guard as _other_runtime_owns_lifecycle:
+ _tui_owns_lifecycle = not _other_runtime_owns_lifecycle
+ if _other_runtime_owns_lifecycle:
+ logger.info(
+ "Preserving session %s during %s: another backend owns an active lease",
+ session_id,
+ end_reason,
+ )
+ if session_id:
+ try:
+ # End the row in the *session's* profile state.db (app-global
+ # remote mode), not the launch profile's shared handle.
+ with _session_db(session) as db:
+ if db is not None:
+ # Don't end gateway-originated sessions — the gateway owns
+ # their lifecycle. The TUI is a viewer, not the owner.
+ # Ending a gateway session in state.db triggers a Groundhog
+ # Day routing loop: the gateway's #54878 self-heal detects
+ # the stale entry, recovers to the parent session, context
+ # compression splits back to the reaped child, and the cycle
+ # repeats on every inbound message. (#60609)
+ row = db.get_session(session_id)
+ source = (row or {}).get("source", "")
+ if _is_gateway_owned_source(source):
+ _tui_owns_lifecycle = False
+ elif _tui_owns_lifecycle:
+ db.end_session(session_id, end_reason)
+ except Exception:
+ pass
+
+ # A session's in-flight async delegations end WITH the session (#55578):
+ # once nobody owns the return address, a still-running background subagent
+ # can only burn tokens and park an orphaned completion on the shared
+ # queue. Always interrupt delegations commissioned by THIS live UI session
+ # (its sid); additionally interrupt by durable session_key, but only when
+ # the TUI owns the lifecycle — closing a viewer tab on a live gateway
+ # session must not kill the gateway's own background work.
+ try:
+ from tools.async_delegation import interrupt_for_session
+
+ _own_sid = str(session.get("_sid") or "")
+ if not _own_sid:
+ try:
+ with _sessions_lock:
+ for _cand_sid, _cand in _sessions.items():
+ if _cand is session:
+ _own_sid = _cand_sid
+ break
+ except Exception:
+ _own_sid = ""
+ interrupt_for_session(
+ session_key=str(session_key or "") if _tui_owns_lifecycle else "",
+ origin_ui_session_id=_own_sid,
+ reason=end_reason,
+ )
+ except Exception:
+ pass
+
+ # Close the slash-worker subprocess as part of finalize itself, not just
+ # in the callers. Defense-in-depth: every session-end path goes through
+ # _finalize_session (it's the single ``_finalized``-guarded chokepoint), so
+ # folding worker cleanup in here means a future code path that calls
+ # _finalize_session directly — without the surrounding _teardown_session /
+ # _shutdown_sessions worker.close() — can't reintroduce the #38095 leak.
+ # Idempotent: _SlashWorker.close() is poll()-guarded, so the explicit
+ # close() still in those callers is harmless.
+ try:
+ worker = session.get("slash_worker")
+ if worker:
+ worker.close()
+ except Exception:
+ pass
+
+
+# End reasons where the BACKEND reclaimed a session the client never asked to
+# close: the idle-TTL reaper, the LRU cap, and the WS-orphan reap. A client
+# holding that live session id gets no signal today — its next prompt fails
+# against an id the backend has already forgotten, which reads as the session
+# silently vanishing rather than being reclaimed. ``tui_close`` and friends are
+# deliberately absent: the client initiated those and already knows.
+_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 rather than session-targeted: the reap paths run on background
+ timer threads with no contextvar binding, and the WS-orphan case has by
+ definition lost its own transport — ``_emit`` would bottom out on stdio and
+ the peer that owns the session would never see it. Best-effort; a failed
+ notify must never break teardown.
+ """
+ if end_reason not in _RECLAIM_END_REASONS:
+ return
+ try:
+ _broadcast_global_event(
+ "session.reclaimed",
+ {
+ "session_id": str(session.get("_sid") or ""),
+ "stored_session_id": str(session.get("session_key") or ""),
+ "reason": end_reason,
+ },
+ )
+ except Exception:
+ logger.debug("session.reclaimed broadcast failed", exc_info=True)
+
+
+def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") -> None:
+ """Fully tear down a session: finalize, unregister, close agent + worker.
+
+ Shared by ``session.close`` and the orphaned-WS-session reaper. The
+ slash-worker subprocess is closed inside ``_finalize_session`` (the single
+ finalize chokepoint); this still unregisters the approval notifier and
+ closes the in-process agent. Idempotent: the ``_finalized`` guard in
+ ``_finalize_session`` and the ``poll()`` guard in ``_SlashWorker.close``
+ make repeat calls harmless.
+ """
+ if not session:
+ return
+ _finalize_session(session, end_reason=end_reason)
+ _announce_session_reclaimed(session, end_reason)
+ try:
+ from tools.approval import unregister_gateway_notify
+
+ if key := session.get("session_key"):
+ unregister_gateway_notify(key)
+ except Exception:
+ pass
+ try:
+ agent = session.get("agent")
+ if agent is not None and hasattr(agent, "close"):
+ agent.close()
+ except Exception:
+ pass
+ # NOTE: the slash-worker is closed inside _finalize_session (the single
+ # _finalized-guarded chokepoint that main folded it into), exactly once.
+ # We deliberately do NOT re-close it here — _teardown_session's job beyond
+ # finalize is unregistering the notifier and closing the in-process agent.
+
+
+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. Closes the create/close race at every slash-worker spawn site."""
+ with _sessions_lock:
+ if _sessions.get(sid) is session:
+ session["slash_worker"] = worker
+ return
+ worker.close()
+
+
+def _pop_session_by_id(sid: str) -> dict | None:
+ """Atomically detach one live session from the registry.
+
+ Detaching is the ownership claim for teardown: once the record is no
+ longer in ``_sessions``, a concurrent close/reaper becomes a no-op. Keep
+ this operation separate from ``_teardown_session`` because finalization can
+ flush SQLite state, invoke plugins, commit memory, interrupt delegations,
+ and close agents/workers. None of that slow external work belongs under
+ the global ``_session_resume_lock``.
+ """
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ if session is not None:
+ session["_closing"] = True
+ _sessions.pop(sid, None)
+ if session is None:
+ return None
+ # The session is already out of _sessions here, so downstream teardown
+ # (e.g. _finalize_session's per-session async-delegation interrupt) can't
+ # recover its live id by scanning the dict — stamp it on the record.
+ session["_sid"] = sid
+ return session
+
+
+def _teardown_popped_session(
+ session: dict | None, *, end_reason: str = "tui_close"
+) -> bool:
+ """Finish a close after the caller has atomically detached the session."""
+ if session is None:
+ return False
+ run_thread = session.get("_run_thread")
+ if (
+ end_reason != "tui_shutdown"
+ and run_thread is not None
+ and run_thread is not threading.current_thread()
+ ):
+ try:
+ if run_thread.is_alive():
+ run_thread.join(timeout=_TURN_SETTLE_BEFORE_CLOSE_SECONDS)
+ if run_thread.is_alive():
+ logger.warning(
+ "session turn thread still alive after %.1fs teardown grace",
+ _TURN_SETTLE_BEFORE_CLOSE_SECONDS,
+ )
+ except Exception:
+ logger.debug("failed waiting for session turn thread", exc_info=True)
+ _teardown_session(session, end_reason=end_reason)
+ return True
+
+
+def _close_session_by_id(
+ sid: str,
+ *,
+ end_reason: str = "tui_close",
+ predicate: Callable[[dict], bool] | None = None,
+) -> bool:
+ """Single idempotent teardown funnel for callers needing no resume race.
+
+ Resume-sensitive callers first pop under ``_session_resume_lock`` and then
+ call ``_teardown_popped_session`` after releasing it. Other reapers can use
+ this convenience wrapper directly. The pop remains the single atomic
+ ownership claim, so concurrent/repeat close attempts stay harmless.
+
+ Automatic reapers can pass ``predicate`` to revalidate under
+ ``_sessions_lock`` immediately before the ownership claim. This prevents a
+ stale scan result from closing a session that reattached or gained active
+ delegated work before teardown.
+ """
+ if predicate is None:
+ 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)
+
+
+def _ws_session_is_detached(session: dict | None) -> bool:
+ """True if a live session is still bound to the disconnected-WS sentinel."""
+ return bool(
+ session
+ and not session.get("_finalized")
+ and session.get("transport") is _detached_ws_transport
+ )
+
+
+def _ws_session_is_orphaned(session: dict | None) -> bool:
+ """True if a WS session has no live transport and no in-flight turn.
+
+ After ``handle_ws`` detaches a disconnected client it points the session at
+ ``_detached_ws_transport``. A session left on that transport (and not
+ mid-turn) is genuinely orphaned and safe to reap.
+ """
+ return bool(
+ _ws_session_is_detached(session)
+ and session is not None
+ 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 interrupt used the compute-host control channel. The WS
+ orphan reaper calls this same helper after its reconnect grace expires, so a
+ dead client gets the same partial-history and queued-prompt semantics as an
+ explicit user interrupt.
+ """
+ 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` is only a mirror and
+ # can lag behind a blocked interactive tool (a clarify parked on its
+ # Event keeps the host turn alive after the parent flag went stale),
+ # so let the host decide whether there is work to interrupt.
+ # Gate on `_compute_host_active` too: `_session_uses_compute_host`
+ # is also true for lazy sessions that never ran a hosted turn, and
+ # `HostSupervisor.interrupt()` calls `start()` — forwarding
+ # unconditionally would spawn a compute-host child just to deliver
+ # an interrupt no session ever submitted work to.
+ 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()
+
+ 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
+
+ request_hard_interrupt(session.get("agent"))
+ if not run_thread_alive:
+ with session["history_lock"]:
+ if session.get("running"):
+ session["running"] = False
+ _clear_inflight_turn(session)
+
+ _clear_pending(sid)
+ try:
+ from tools.approval import resolve_gateway_approval
+
+ resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)
+ except Exception:
+ pass
+ 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."""
+ if not session_id:
+ return True
+ try:
+ db = _get_db()
+ if db is None:
+ return True
+ # Don't end gateway-originated sessions — the gateway owns their
+ # lifecycle. The TUI is only a viewer there (#60609).
+ row = db.get_session(session_id)
+ source = (row or {}).get("source", "")
+ return not _is_gateway_owned_source(source)
+ except Exception:
+ return True
+
+
+def _session_async_delegation_selectors(
+ session: dict | None, *, sid_hint: str = ""
+) -> tuple[str, str]:
+ """Ownership selectors for async background work tied to one UI session."""
+ if not session:
+ return "", ""
+ own_sid = str(sid_hint or session.get("_sid") or "")
+ if not own_sid:
+ try:
+ with _sessions_lock:
+ for _cand_sid, _cand in _sessions.items():
+ if _cand is session:
+ own_sid = _cand_sid
+ break
+ except Exception:
+ own_sid = ""
+ agent = session.get("agent")
+ session_key = str(session.get("session_key") or "")
+ session_id = getattr(agent, "session_id", None) or session_key
+ owned_session_key = session_key if _session_owns_durable_lifecycle(session_id) else ""
+ return own_sid, owned_session_key
+
+
+def _session_has_active_delegations(sid: str, session: dict | None = None) -> bool:
+ """True when UI session ``sid`` still owns live background work.
+
+ Matches by the live UI sid AND — when the TUI owns the durable lifecycle
+ (never for gateway-viewer tabs, #60609) — by the durable session_key, so a
+ delegation dispatched from an earlier tab of the same resumed session still
+ keeps it alive.
+ """
+ if session is None:
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ own_sid, owned_session_key = _session_async_delegation_selectors(
+ session, sid_hint=sid
+ )
+ if not own_sid and not owned_session_key:
+ return False
+ try:
+ from tools.async_delegation import has_live_for_session
+
+ 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 turn into destructive
+ # cleanup. Conservatively keep the detached session and let the next
+ # orphan timer retry the lookup.
+ return True
+
+
+# One pending WS-orphan reap Timer per live sid. Registered by
+# _schedule_ws_orphan_reap, popped when its _reap fires, and cancelled by
+# _cancel_ws_orphan_reap from every resume/reuse/transport-rebind path. Without
+# this cancellation the reap could fire against an already-reattached session,
+# broadcast session.reclaimed, and trigger the client's auto-re-resume — a
+# reap->broadcast->resume feedback storm. Guarded by _sessions_lock.
+_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 onto the session:
+ the session.resume fast-path reuse, _claim_or_reuse_live winners, and the
+ _live_session_payload transport rebind. Cancelling here (rather than
+ relying on the reap's own orphan re-check) removes the window where a
+ fired-but-not-yet-run Timer races the resume, and stops dead Timers from
+ accumulating for sessions that reconnect frequently.
+ """
+ with _sessions_lock:
+ timer = _pending_ws_reaps.pop(sid, None)
+ if timer is not None:
+ try:
+ timer.cancel()
+ except Exception:
+ pass
+
+
+def _ws_orphan_turn_activity_is_fresh(session: dict) -> bool:
+ """Whether a detached RUNNING turn's activity clock is still fresh.
+
+ Reuses the agent's existing activity summary (``_touch_activity`` is
+ stamped by API waits, stream tokens, and tool heartbeats — the same
+ clock the turn-liveness watchdog samples; see agent/turn_liveness.py).
+ Fresh means the WS-orphan reaper must NOT interrupt the turn yet
+ (#98028/#100325): deliberate client absence (closed laptop, backgrounded
+ mobile app, desktop update/relaunch) keeps healthy work running detached.
+
+ Conservative fallbacks preserve the wedged-turn safety net: a disabled
+ threshold (<= 0), a missing/opaque agent, an unreadable summary, or a
+ never-stamped clock all report NOT fresh, i.e. eligible for the
+ interrupt-at-grace path exactly as before.
+ """
+ if _WS_ORPHAN_ACTIVITY_STALE_S <= 0:
+ return False
+ agent = session.get("agent")
+ summary_fn = getattr(agent, "get_activity_summary", None)
+ if not callable(summary_fn):
+ return False
+ try:
+ elapsed = summary_fn().get("seconds_since_activity")
+ return elapsed is not None and float(elapsed) < _WS_ORPHAN_ACTIVITY_STALE_S
+ except Exception:
+ return False
+
+
+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. The grace window lets a transient
+ reconnect (or a ``session.resume`` that reattaches the transport) cancel
+ the reap by re-binding a live transport. Disabled when the grace is 0.
+ """
+ if _WS_ORPHAN_REAP_GRACE_S <= 0:
+ return
+
+ def _reap() -> None:
+ # Serialize the orphan re-check against session.resume (which re-binds a
+ # live transport under _session_resume_lock and would make this session
+ # non-orphaned). Claim teardown by popping under both lifecycle locks,
+ # then release the global resume lock before the slow finalization work.
+ # The dict mutation still happens under _sessions_lock — consistent
+ # with every other _sessions mutator
+ # (#39591: _reap previously popped under _session_resume_lock, giving no
+ # mutual exclusion against _init_session / _close_session_by_id, which
+ # guard with _sessions_lock). _sessions_lock is an RLock and the global
+ # ordering is always resume_lock -> sessions_lock, so nesting is safe.
+ reschedule_delay = None
+ interrupt_session = None
+ session = None
+ with _session_resume_lock:
+ # This Timer is running: drop its registration so a concurrent
+ # _cancel_ws_orphan_reap doesn't cancel a dead Timer object while
+ # a rescheduled one (registered below) is the live owner.
+ with _sessions_lock:
+ _pending_ws_reaps.pop(sid, None)
+ current = _sessions.get(sid)
+ if current is None or not _ws_session_is_detached(current):
+ return
+ if _session_has_active_delegations(sid, current):
+ reschedule_delay = _WS_ORPHAN_REAP_GRACE_S
+ elif current.get("running"):
+ if not current.get(
+ "_client_gone_interrupt_requested"
+ ) and _ws_orphan_turn_activity_is_fresh(current):
+ # Client-absent but actively producing (#98028/#100325):
+ # the turn keeps running detached (the sentinel transport
+ # already buffers emits) and the reaper re-checks each
+ # grace interval. Only a turn whose activity clock has
+ # gone stale — genuinely wedged, the case the interrupt
+ # was added for — falls through to the interrupt below.
+ 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 (#85578): after the reconnect grace the turn is
+ # interrupted once, then the reap keeps polling until the
+ # normal turn-finalization path 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:
+ # The interrupted turn never settled inside the budget
+ # — force-reap rather than parking the session + a
+ # timer chain forever. Loud by design: this only fires
+ # when a turn is genuinely stuck past interrupt.
+ logger.error(
+ "client_gone sid=%s: turn did not settle after %d "
+ "interrupt polls (%.0fs) — force-reaping detached "
+ "session",
+ sid, polls - 1,
+ (polls - 1) * _WS_ORPHAN_INTERRUPT_REAP_POLL_S,
+ )
+ session = _pop_session_by_id(sid)
+ else:
+ if not current.get("_client_gone_interrupt_requested"):
+ current["_client_gone_interrupt_requested"] = True
+ interrupt_session = current
+ reschedule_delay = _WS_ORPHAN_INTERRUPT_REAP_POLL_S
+ else:
+ session = _pop_session_by_id(sid)
+
+ if interrupt_session is not None:
+ try:
+ isolated = _interrupt_session_turn(
+ sid,
+ interrupt_session,
+ request_id=f"client-gone-{sid}",
+ )
+ logger.info(
+ "client_gone sid=%s action=interrupt turn_isolation=%s",
+ sid,
+ isolated,
+ )
+ except Exception:
+ logger.exception("client_gone interrupt failed sid=%s", sid)
+ with _sessions_lock:
+ if _sessions.get(sid) is interrupt_session:
+ interrupt_session.pop(
+ "_client_gone_interrupt_requested", None
+ )
+
+ if reschedule_delay is not None:
+ _schedule_ws_orphan_reap(sid, delay_s=reschedule_delay)
+ return
+ if session is not None and session.get(
+ "_client_gone_interrupt_requested"
+ ):
+ logger.info("client_gone sid=%s action=reap", sid)
+ _teardown_popped_session(session, end_reason="ws_orphan_reap")
+
+ timer = threading.Timer(
+ _WS_ORPHAN_REAP_GRACE_S if delay_s is None else max(0.0, delay_s),
+ _reap,
+ )
+ timer.daemon = True
+ with _sessions_lock:
+ prior = _pending_ws_reaps.pop(sid, None)
+ _pending_ws_reaps[sid] = timer
+ if prior is not None:
+ try:
+ prior.cancel()
+ except Exception:
+ pass
+ timer.start()
+
+
+def _close_sessions_for_transport(
+ transport, *, end_reason: str = "ws_disconnect"
+) -> tuple[int, int]:
+ """On transport disconnect, reap the sessions that opted into
+ close_on_disconnect (sidecar/dashboard) immediately and re-point the rest
+ at the detached transport so later emits don't hit a dead socket.
+
+ Non-flagged detached sessions are handed to the grace-windowed WS-orphan
+ reaper (``_schedule_ws_orphan_reap``): a quick reconnect / session.resume
+ that re-binds a live transport cancels the reap, otherwise the orphan is
+ torn down through the same idempotent ``_teardown_session`` path. This is
+ the single WS-disconnect teardown entry point — there is no second
+ independent reap loop in ``handle_ws``.
+
+ Returns ``(reaped, detached)`` counts for disconnect-path observability."""
+ with _sessions_lock:
+ owned = [(sid, s) for sid, s in _sessions.items() if s.get("transport") is transport]
+ reaped = 0
+ detached = 0
+ for sid, session in owned:
+ claimed_for_teardown = None
+ should_schedule_reap = False
+ # A session.resume fast-path rebinds its live session while holding
+ # _session_resume_lock. Take that lock before re-checking the snapshot
+ # so a reconnect cannot move the transport between this check and the
+ # close/detach ownership claim. Keep the slow teardown below both locks.
+ with _session_resume_lock:
+ with _sessions_lock:
+ current = _sessions.get(sid)
+ if current is not session:
+ continue
+ if current.get("transport") is not transport:
+ # The reconnect owns this session now. Drop only the old
+ # viewer registration; it must not affect the new owner.
+ viewers = current.get("viewers")
+ if viewers:
+ viewers.pop(transport, None)
+ continue
+ if current.get("close_on_disconnect"):
+ claimed_for_teardown = _pop_session_by_id(sid)
+ else:
+ # Point detached sessions at the drop sentinel (NOT real
+ # stdio) so _ws_session_is_orphaned recognizes them and
+ # the grace-reap can actually fire; a standalone
+ # `hermes --tui` keeps real _stdio. UNLESS another window
+ # still shows the session: multi-window pop-outs all
+ # register as viewers, so on disconnect re-bind the
+ # session to the most recent surviving viewer instead of
+ # stranding the original window on the sentinel (#83716).
+ viewers = current.get("viewers")
+ if viewers:
+ viewers.pop(transport, None)
+ remaining = [
+ (ts, viewer_transport)
+ for viewer_transport, ts in (viewers or {}).items()
+ if (
+ viewer_transport is not transport
+ and not _transport_is_dead(viewer_transport)
+ )
+ ]
+ if remaining:
+ remaining.sort(key=lambda item: item[0])
+ current["transport"] = remaining[-1][1]
+ else:
+ current["transport"] = _detached_ws_transport
+ 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
+ elif should_schedule_reap:
+ detached += 1
+ try:
+ _schedule_ws_orphan_reap(sid)
+ except Exception:
+ pass
+ return reaped, detached
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers 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
new file mode 100644
index 00000000000..00431afc944
--- /dev/null
+++ b/tui_gateway/session_workdir.py
@@ -0,0 +1,904 @@
+"""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 (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from tui_gateway import git_probe
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+
+def _normalize_completion_path(path_part: str) -> str:
+ expanded = os.path.expanduser(path_part)
+ if os.name != "nt":
+ normalized = expanded.replace("\\", "/")
+ if (
+ len(normalized) >= 3
+ and normalized[1] == ":"
+ and normalized[2] == "/"
+ and normalized[0].isalpha()
+ ):
+ return f"/mnt/{normalized[0].lower()}/{normalized[3:]}"
+ return expanded
+
+
+def _completion_cwd(params: dict | None = None) -> str:
+ params = params or {}
+ 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.
+ or _profile_configured_cwd(_profile_home(params.get("profile")))
+ # The launch profile's dashboard /chat attaches to the dashboard's
+ # in-memory gateway, which does NOT inherit the PTY child's bridged
+ # TERMINAL_CWD. Read the launch profile's config.yaml directly so a
+ # configured terminal.cwd wins over a stale process env / launch dir.
+ or _launch_configured_cwd()
+ or os.environ.get("TERMINAL_CWD")
+ or os.getcwd()
+ )
+ try:
+ resolved = os.path.abspath(os.path.expanduser(str(raw)))
+ if os.path.isdir(resolved):
+ return resolved
+ except Exception:
+ pass
+ return os.getcwd()
+
+
+def _terminal_task_cwd(session: dict | None) -> str:
+ """Return the cwd that terminal_tool should use for this TUI session.
+
+ ``_completion_cwd`` validates paths on the host so file completion does not
+ point at nonsense. Non-local terminal backends are different: their cwd is
+ inside the target environment, so an SSH path like /home/user/workspace may
+ not exist on the local macOS host but is still the correct execution cwd.
+
+ When ``TERMINAL_ENV`` is unset (dashboard/TUI process) the config's
+ ``terminal.backend`` is consulted as a fallback so the non-local cwd
+ resolution path is taken even when the dashboard entrypoint did not call
+ ``apply_terminal_config_to_env`` on its own ``os.environ``.
+ """
+ return _terminal_task_cwd_with_source(session)[0]
+
+
+def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:
+ """Like :func:`_terminal_task_cwd` but also names the value's ORIGIN.
+
+ Returns ``(cwd, source)`` where source is:
+
+ * ``"session"`` — the workspace the user attached to THIS session
+ (``explicit_cwd``), or this session's own tracked directory.
+ * ``"process"`` — the process-global ``TERMINAL_CWD`` env var / config
+ ``terminal.cwd`` fallback. On a shared-container backend this is the
+ normal seed; under per-session docker isolation it is a launch
+ artifact from a PREVIOUS session (the workspace picker persists it
+ process-wide) and must never become a fresh session's bind mount —
+ terminal_tool refuses ``cwd_source: "process"`` as a mount source.
+ """
+ backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
+ if not backend or backend == "local":
+ # Fall back to config when TERMINAL_ENV is unset (dashboard/TUI process
+ # never calls apply_terminal_config_to_env on os.environ).
+ try:
+ terminal_cfg = _load_cfg().get("terminal", {})
+ if isinstance(terminal_cfg, dict):
+ cfg_backend = str(terminal_cfg.get("backend") or "").strip().lower()
+ if cfg_backend and cfg_backend != "local":
+ backend = cfg_backend
+ except Exception:
+ pass
+
+ if backend and backend != "local":
+ # A workspace the user explicitly attached to THIS session wins over
+ # the process-global env var — the env var is whatever the LAST
+ # session's picker wrote, not this session's choice.
+ if session and session.get("explicit_cwd") and session.get("cwd"):
+ return str(session["cwd"]), "session"
+ raw = os.environ.get("TERMINAL_CWD", "").strip()
+ if not raw:
+ try:
+ terminal_cfg = _load_cfg().get("terminal", {})
+ if isinstance(terminal_cfg, dict):
+ raw = str(terminal_cfg.get("cwd") or "").strip()
+ except Exception:
+ raw = ""
+ if raw and raw not in {".", "auto", "cwd"}:
+ return raw, "process"
+ if backend == "ssh":
+ return "~", "process"
+
+ if session and session.get("cwd"):
+ return str(session["cwd"]), "session"
+ return _completion_cwd(), "process"
+
+
+# Git working-tree probing (run git, resolve roots, fold worktrees) lives in a
+# focused, single-flight-cached module; these stay as the in-server names every
+# call site already uses.
+_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
+_resolve_cwd_git = git_probe.resolve
+
+
+def _session_cwd(session: dict | None) -> str:
+ if session and session.get("cwd"):
+ return str(session["cwd"])
+ return _completion_cwd()
+
+
+# Sources whose launch directory is an artifact of how the app was started, not
+# a workspace the user picked. Everything else is terminal-started: the process
+# runs in a directory the user deliberately cd'd into.
+_LAUNCH_CWD_NOT_A_WORKSPACE = {"desktop"}
+
+
+def _context_cwd_is_launch_artifact(session: dict | None) -> bool:
+ """Whether the session cwd came from app launch rather than user intent."""
+ return bool(
+ session
+ and not session.get("explicit_cwd")
+ and _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE
+ )
+
+
+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 why the launch directory counts as a
+ workspace for terminal sessions but not for the desktop.
+ """
+ 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. `_session_cwd` falls back to the
+ # gateway-wide completion cwd, which belongs to no session in particular —
+ # stamping that would invent a workspace for a session that never had one.
+ return str(session.get("cwd") or "") or None
+
+
+def _heal_dead_cwd(cwd: str) -> str:
+ """Resolve a session cwd that points at a now-deleted directory.
+
+ A session anchored to a linked worktree (``<repo>/.worktrees/<name>``) keeps
+ that path after the worktree is removed (branch merged, `git worktree
+ remove`, etc). The literal dir is gone, so a probe of it returns nothing and
+ the composer shows no branch — while the sidebar still folds the path up to
+ the repo's main lane. Heal the mismatch: walk up to the first existing
+ ancestor, then resolve its common git root, so a dead-worktree cwd collapses
+ to the live repo root (and its real current branch).
+
+ Only meaningful for local backends; a remote/SSH cwd may legitimately not
+ exist on the host, so callers must skip healing there.
+ """
+ raw = (cwd or "").strip()
+ if not raw or os.path.isdir(raw):
+ return raw
+
+ probe = raw
+ # Climb to the first ancestor that still exists on disk.
+ for _ in range(64):
+ parent = os.path.dirname(probe)
+ if not parent or parent == probe:
+ break
+ probe = parent
+ if os.path.isdir(probe):
+ break
+
+ if not os.path.isdir(probe):
+ return raw
+
+ try:
+ root = _git_common_repo_root_for_cwd(probe) or _git_repo_root_for_cwd(probe)
+ except Exception:
+ root = ""
+
+ return root or probe
+
+
+def _is_local_terminal_backend() -> bool:
+ backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
+ return not backend or backend == "local"
+
+
+def _effective_terminal_backend() -> str:
+ """Active terminal backend name (``local``, ``docker``, ``ssh``, ...).
+
+ ``TERMINAL_ENV`` is authoritative when set (launchers bridge
+ ``terminal.backend`` into env at startup). Desktop/TUI in-process gateways
+ skip that bridge, so fall back to the ``terminal.backend`` config key —
+ the same rule ``_terminal_task_cwd`` uses.
+ """
+ backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
+ if not backend or backend == "local":
+ try:
+ terminal_cfg = _load_cfg().get("terminal", {})
+ if isinstance(terminal_cfg, dict):
+ cfg_backend = str(terminal_cfg.get("backend") or "").strip().lower()
+ if cfg_backend and cfg_backend != "local":
+ backend = cfg_backend
+ except Exception:
+ pass
+ return backend or "local"
+
+
+def _display_session_cwd(session: dict | None) -> str:
+ """Session cwd for display/probe surfaces, healed past deleted worktrees.
+
+ Persists the healed value back to the session row (best-effort, local only)
+ so the next load is already coherent and the sidebar lane stops showing a
+ session pinned to a vanished path.
+ """
+ cwd = _session_cwd(session)
+ if not _is_local_terminal_backend():
+ return cwd
+
+ healed = _heal_dead_cwd(cwd)
+ if healed and healed != cwd and session is not None:
+ session["cwd"] = healed
+ _persist_session_cwd_and_schedule_git_meta(session, healed)
+
+ return healed
+
+
+def _reconcile_session_cwd_from_terminal(session: dict | None) -> bool:
+ """Re-anchor a session that SETTLED in another git checkout. Returns moved.
+
+ An agent told to work in a fresh worktree does exactly that — `git worktree
+ add`, `cd` into it, and every later command runs there — but the session
+ stayed pinned to wherever it started, so the desktop kept labelling the chat
+ with the primary checkout's branch while all the work landed elsewhere.
+
+ A plain `cd` is deliberately NOT a workspace move (see
+ ``_apply_project_workspace``): browsing to /tmp to read a log must not
+ re-home the chat. What we adopt here is narrower — the session's recorded
+ cwd is in a DIFFERENT working tree of the SAME repository (the shape
+ ``git worktree add`` produces). Everything else — a non-git workspace
+ stepping into a repo, or a git workspace visiting an unrelated repo — is
+ a browsing visit, and a user's explicitly chosen workspace is never
+ overridden at all.
+
+ Local backends only: a remote/SSH cwd names a path on the host, which this
+ gateway can neither stat nor probe with git.
+ """
+ if not session or not _is_local_terminal_backend():
+ return False
+
+ # A workspace the user (or GUI) explicitly chose is never overridden by
+ # where the agent's terminal happened to settle — only another explicit
+ # action (`_set_session_cwd`, a project switch) moves it. A cwd this very
+ # function adopted is marked `cwd_from_settle` so a session can keep
+ # following the agent through successive worktrees.
+ if session.get("explicit_cwd") and not session.get("cwd_from_settle"):
+ return False
+
+ try:
+ from tools.terminal_tool import get_session_cwd
+
+ recorded = get_session_cwd(session.get("session_key") or "")
+ except Exception:
+ return False
+
+ if not recorded:
+ return False
+
+ resolved = os.path.abspath(os.path.expanduser(str(recorded)))
+ current = os.path.abspath(os.path.expanduser(_session_cwd(session)))
+ if resolved == current or not os.path.isdir(resolved):
+ return False
+
+ # The worktree ROOT, not the common repo root: folding worktrees together
+ # here is exactly what hides the move we're looking for.
+ landed = _git_repo_root_for_cwd(resolved)
+ current_root = _git_repo_root_for_cwd(current)
+ # A relocation is a move between two DIFFERENT git working trees. When the
+ # session's own workspace is not in a git repo, the agent stepping into one
+ # to read a file or run a command is a browsing visit, not a re-home:
+ # adopting it would hijack a non-git workspace onto whatever repo a tool
+ # call touched first (e.g. a home-directory session pinned to the checkout
+ # it read a file from).
+ if not landed or not current_root or landed == current_root:
+ return False
+
+ # And only between checkouts of the SAME repository — the shape a real
+ # `git worktree add` produces (linked worktrees share the common .git
+ # dir). Settling in an UNRELATED repo (`cd ~/other-project && git log`)
+ # is likewise a visit: adopting it would re-home the chat onto whatever
+ # foreign repo the terminal last touched.
+ landed_common = _git_common_repo_root_for_cwd(resolved)
+ current_common = _git_common_repo_root_for_cwd(current)
+ if not landed_common or landed_common != current_common:
+ return False
+
+ session["cwd"] = resolved
+ # The session works here now, so this is its workspace — a desktop chat
+ # whose cwd was an unpersisted launch artifact earns a real row. The
+ # settle marker keeps this adoption overridable by the NEXT settle while
+ # still yielding to a user's explicit choice (see the guard above).
+ session["explicit_cwd"] = True
+ session["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 turn is over, so the agent has stopped moving: this is the one moment
+ where its recorded cwd is a stable answer to "where does this session
+ work". Reconciling before building the payload means the same event that
+ already tells the desktop the turn ended also carries the new cwd/branch —
+ the client follows it with no new event type and no extra round trip.
+ """
+ try:
+ _reconcile_session_cwd_from_terminal(session)
+ except Exception:
+ logger.debug("failed to reconcile settled session cwd", exc_info=True)
+ _emit("session.info", sid, _session_info(agent, session))
+
+
+def _session_source(session: dict | None) -> str:
+ if session:
+ source = str(session.get("source") or "").strip()
+ if source:
+ return source
+ return _resolve_session_platform()
+
+
+def _register_session_cwd(session: dict | None) -> None:
+ if not session:
+ return
+ try:
+ from tools.terminal_tool import register_task_env_overrides
+
+ cwd, cwd_source = _terminal_task_cwd_with_source(session)
+ register_task_env_overrides(
+ session["session_key"], {"cwd": cwd, "cwd_source": cwd_source}
+ )
+ except Exception:
+ pass
+
+
+def _ensure_session_db_row(session: dict) -> bool:
+ """Idempotently persist the session's DB row on first real activity.
+
+ Called from prompt.submit so a row only exists once the user actually sends
+ a message — abandoned drafts never leave an empty "Untitled" session behind.
+ Uses INSERT OR IGNORE under the hood, so re-calls (and the AIAgent's own
+ lazy create) are no-ops.
+ Returns False only when the store is unavailable (no openable state.db);
+ prompt.submit turns that into an RPC error so a send fails loudly with a
+ toast instead of streaming into a store that will never save it (#98924).
+ Every other outcome — no key, best-effort attempt, success — is True.
+
+ A cwd the user *chose* is always persisted. When they made no explicit
+ choice the launch directory stands in, and whether that is meaningful
+ depends on how the session was started:
+
+ * The desktop launches from wherever the app bundle was opened (often ``/``
+ or the user's home), so stamping that would file every unpicked chat under
+ a folder the user never chose. Those stay null and group under "No
+ workspace", which is the desired default.
+ * A terminal session (``hermes`` / ``hermes --tui`` / CLI) is started from a
+ directory the user deliberately ``cd``'d into — that IS the workspace, and
+ it is also where the agent's terminal actually runs. Dropping it stranded
+ the session with no cwd AND no git_repo_root, so the sidebar could never
+ place it under its project.
+ """
+ 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 row lands in the wrong state.db, the
+ # unified list mis-tags it, and resume 404s ("session not found").
+ profile_home = session.get("profile_home")
+ if profile_home:
+ from hermes_state import SessionDB
+
+ try:
+ from hermes_state import get_shared_session_db
+ db = get_shared_session_db(Path(profile_home) / "state.db")
+ except Exception:
+ logger.debug("failed to open profile db for session row", exc_info=True)
+ return False
+ close_db = True
+ else:
+ db = _get_db()
+ close_db = False
+ if db is None:
+ # Fail loud ONLY when the store actually failed to open (#98924):
+ # _db_error records the SessionDB open exception. A None db with no
+ # recorded error means "no store in this context" (degraded harness,
+ # store deliberately absent) — that keeps the pinned best-effort
+ # contract and stays True.
+ return _db_error is None
+ # The session's own model/effort/fast pick — the composer override shipped on
+ # session.create, or a restored /model switch — must own the row's model +
+ # model_config. The agent isn't built yet at first prompt.submit, so derive
+ # the row from the live override dict; fall back to the global resolved model
+ # only when this chat made no explicit pick. Writing the global default here
+ # used to win the INSERT-OR-IGNORE race against the agent's own correct
+ # lazy-create, so a reconnect/resume rebuilt from the global model and
+ # silently reverted the chat (e.g. picked gpt-5.5, reconnect snapped back to
+ # the profile default). model_config carries provider/reasoning/service_tier
+ # so resume restores effort + fast too, not just the model name.
+ 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 = {}
+ for src_key, cfg_key in (
+ ("model", "model"),
+ ("provider", "provider"),
+ ("base_url", "base_url"),
+ ("api_mode", "api_mode"),
+ ):
+ if val := override.get(src_key):
+ model_config[cfg_key] = str(val)
+ # The composer override may carry the RESOLVED provider "custom" for a named
+ # ``providers:`` / ``custom_providers:`` entry. Persisting bare "custom" here
+ # (the very first DB write for a fresh desktop session, before the agent is
+ # built) is the origin of the recurring "No LLM provider configured" rows:
+ # on the next resume bare "custom" routes to OpenRouter with no key. Recover
+ # the durable ``custom:<name>`` identity from the override's base_url, else
+ # the configured provider, so a routable identity is persisted from the
+ # start (matches _runtime_model_config's normalization).
+ if str(model_config.get("provider") or "").strip().lower() == "custom":
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+
+ healed = canonical_custom_identity(
+ base_url=model_config.get("base_url") or None,
+ model=model_config.get("model") or row_model or None,
+ )
+ if healed:
+ model_config["provider"] = healed
+ except Exception:
+ logger.debug(
+ "custom provider identity recovery failed (db row)", exc_info=True
+ )
+ if (reasoning := session.get("create_reasoning_override")) is not None:
+ model_config["reasoning_config"] = reasoning
+ create_service_tier_override = session.get("create_service_tier_override")
+ if create_service_tier_override is not None:
+ # Empty string is the in-memory sentinel for an explicit normal tier:
+ # it bypasses _make_agent's profile fallback without sending a bogus
+ # service_tier value to the provider. Persist a durable marker so resume
+ # can distinguish that choice from an omitted/inherited tier.
+ model_config["service_tier"] = create_service_tier_override or "normal"
+ # Branch lineage: stamp the same ``_branched_from`` marker the TUI /branch
+ # uses so list_sessions_rich keeps the branch listed and the desktop sidebar
+ # can nest it under its parent.
+ parent_session_id = session.get("parent_session_id") or None
+ if parent_session_id:
+ model_config["_branched_from"] = parent_session_id
+ # Bot-Mode room plumbing sessions are per-member scratch conversations
+ # inside a group chat: their runtime must ALWAYS follow the member profile's
+ # CURRENT config, never the provider that was pinned when the row was first
+ # written. Persist that contract explicitly so resume can distinguish room
+ # plumbing from a normal user chat (whose stored model/provider must be
+ # restored verbatim). See _stored_session_runtime_overrides.
+ if session.get("room_plumbing"):
+ model_config["room_plumbing"] = True
+ # Bot-Mode canonical chats (the ONE forever DM per bot) and room plumbing
+ # sessions are plugin-owned scratch conversations: their runtime must ALWAYS
+ # follow the member profile's CURRENT config, never the model/provider that
+ # was pinned when the row was first written. Persist that contract explicitly
+ # so resume can distinguish them from a normal user chat (whose stored
+ # model/provider must be restored verbatim). See
+ # _stored_session_runtime_overrides.
+ if session.get("follow_profile_config"):
+ model_config["follow_profile_config"] = True
+ try:
+ db.create_session(
+ key,
+ source=_session_source(session),
+ model=row_model,
+ model_config=model_config or None,
+ parent_session_id=parent_session_id,
+ cwd=_persisted_session_cwd(session),
+ # Self-describing rows: aggregators that merge multiple profile DBs
+ # into one list can't rely on which file a row came from alone.
+ # Stamp the launch profile explicitly instead of leaving NULL —
+ # NULL is exactly what the #94724 legacy-owner backfill exists to
+ # repair, and rows minted AFTER that one-shot backfill ran stayed
+ # NULL forever: profile-keyed matching then drops them from the
+ # sidebar and deep links can't resolve them (#99222).
+ profile_name=(
+ Path(profile_home).name if profile_home else _current_profile_name()
+ ),
+ )
+ # A session can be born hidden (session.create hidden=true, or a
+ # session.set_hidden that arrived before the row existed): apply the
+ # deferred intent now that the row exists, mirroring 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: if we swallow it here, prompt.submit
+ # returns {"status":"streaming"} and the user's message vanishes with
+ # no toast. Re-raise so the submit handler can return a real RPC error.
+ from hermes_state import is_disk_full_error
+
+ if is_disk_full_error(exc):
+ raise
+ logger.debug("failed to persist desktop session row", exc_info=True)
+ finally:
+ if close_db:
+ try:
+ from hermes_state import release_or_close
+ release_or_close(db)
+ except Exception:
+ pass
+ return True
+
+
+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"]`` (they ride into the agent as ``conversation_history``,
+ which ``_flush_messages_to_session_db`` skips by identity). Without this the
+ branch row would resume missing its pre-branch context. Runs once; the row +
+ parent link are written by ``_ensure_session_db_row`` just before this.
+ """
+ if not session.get("parent_session_id") or session.get("_branch_seed_persisted"):
+ return
+ key = session.get("session_key")
+ if not key:
+ return
+ with session["history_lock"]:
+ seed = [dict(msg) for msg in (session.get("history") or [])]
+ if not seed:
+ return
+ with _session_db(session) as db:
+ if db is None:
+ return
+ try:
+ # Bounded-chunk transactions (see #23254): a branch seed can be
+ # hundreds of rows; chunking keeps each BEGIN IMMEDIATE short so
+ # concurrent writers aren't starved. Recovery semantics match the
+ # old per-row loop (mid-copy failure leaves a partial seed with
+ # _branch_seed_persisted unset).
+ db.append_messages_batch(
+ key,
+ [
+ {
+ "role": msg.get("role", "user"),
+ "content": msg.get("content"),
+ "reasoning": msg.get("reasoning"),
+ "reasoning_content": msg.get("reasoning_content"),
+ "reasoning_details": msg.get("reasoning_details"),
+ "codex_reasoning_items": msg.get("codex_reasoning_items"),
+ "codex_message_items": msg.get("codex_message_items"),
+ # Timeline markers (model_switch, personality_switch,
+ # auto_continue, …) ride as role=user; dropping the tag
+ # here re-planted them as bare user turns after a
+ # restart, corrupting the truncate ordinal address
+ # space the same way #82756 did.
+ "display_kind": msg.get("display_kind"),
+ "display_metadata": msg.get("display_metadata"),
+ # Preserve the parent's original message timestamps —
+ # append_message would otherwise stamp time.time() and the
+ # branch's copied history would all appear authored "now".
+ "timestamp": msg.get("timestamp"),
+ }
+ for msg in seed
+ ],
+ chunk_rows=500,
+ )
+ session["_branch_seed_persisted"] = True
+ except Exception as exc:
+ from hermes_state import is_disk_full_error
+
+ if is_disk_full_error(exc):
+ raise
+ logger.debug("branch seed persist failed", exc_info=True)
+
+
+def _session_db(session: dict):
+ """Yield the SessionDB that owns this session's row (profile-aware).
+
+ Mirrors :func:`_ensure_session_db_row`: a remote/profile session persists
+ into its own profile's ``state.db`` (a fresh handle we close on exit);
+ everything else borrows the shared ``_get_db()`` handle (left open). Yields
+ None when the db is unavailable.
+ """
+ db, close_db = None, False
+ profile_home = session.get("profile_home")
+ if profile_home:
+ from hermes_state import SessionDB
+
+ try:
+ from hermes_state import get_shared_session_db
+ db, close_db = get_shared_session_db(Path(profile_home) / "state.db"), True
+ except Exception:
+ logger.debug("failed to open profile db for session", exc_info=True)
+ else:
+ db = _get_db()
+ try:
+ yield db
+ finally:
+ if close_db and db is not None:
+ with contextlib.suppress(Exception):
+ from hermes_state import release_or_close
+ release_or_close(db)
+
+
+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.
+
+ The caller holds ``history_lock``. Persistent sessions archive the target
+ and tail; a composite carrier's own hidden handoff is inserted in that same
+ transaction. Memory is installed only after the durable commit and is
+ built from the already-validated prefix plus the returned scaffold row id,
+ so there is no fallible post-commit reload.
+ """
+ from agent.context_compressor import (
+ 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):
+ content = _multimodal_text_summary(content)
+ elif isinstance(content, list):
+ text_parts = []
+ for part in content:
+ if isinstance(part, dict) and part.get("type") == "text":
+ text_parts.append(str(part.get("text", "")))
+ elif (
+ isinstance(part, dict)
+ and part.get("type") in {"image", "image_url", "input_image"}
+ ):
+ text_parts.append("[screenshot]")
+ content = "\n".join(text_parts) if text_parts else None
+ if message.get("role") in {"user", "assistant"} and isinstance(content, str):
+ return sanitize_context(content).strip()
+ return content
+
+ history = _history_without_ephemeral_scaffolding(session.get("history", []))
+ user_indices = [
+ index
+ for index, message in enumerate(history)
+ if user_originated_turn_view(message) is not None
+ ]
+ if user_ordinal < 0 or user_ordinal >= len(user_indices):
+ raise ValueError("target user message is no longer in session history")
+ target_index = user_indices[user_ordinal]
+ installed, live_view = history_before_user_originated_turn(history, target_index)
+ rewound_count = len(history) - target_index
+
+ session_key = str(session.get("session_key") or "").strip()
+ persisted = False
+ if session_key:
+ with _session_db(session) as db:
+ if db is None:
+ raise RuntimeError("session database is unavailable")
+ expected_active_ids = db.get_active_message_ids(session_key)
+ durable = db.get_messages_as_conversation(
+ session_key,
+ include_row_ids=True,
+ )
+ durable_user_indices = [
+ index
+ for index, message in enumerate(durable)
+ if user_originated_turn_view(message) is not None
+ ]
+ if len(durable_user_indices) != len(user_indices):
+ raise RuntimeError(
+ "session history changed before the rewind could be persisted"
+ )
+ durable_target_index = durable_user_indices[user_ordinal]
+ durable_target = durable[durable_target_index]
+ durable_prefix, durable_live_view = history_before_user_originated_turn(
+ durable, durable_target_index
+ )
+ if _comparison_content(durable_live_view) != _comparison_content(live_view):
+ raise RuntimeError(
+ "session history changed before the rewind could be persisted"
+ )
+ target_row_id = durable_target.get("_row_id")
+ if not isinstance(target_row_id, int):
+ raise RuntimeError("rewind target has no durable row identity")
+ if require_retryable:
+ 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"),
+ )
+ 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
+ installed[-1] = durable_prefix[-1]
+ # Current clients address destructive follow-ups by durable row id.
+ # Preserve the richer warm content (for example image parts), but
+ # copy row identities when the retained warm/durable 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):
+ row_id = durable_message.get("_row_id")
+ if isinstance(row_id, int):
+ warm["_row_id"] = row_id
+ live_view = durable_live_view
+ rewound_count = int(result.get("rewound_count", 0))
+ persisted = True
+ elif require_retryable:
+ retryable_user_text(live_view.get("content"))
+
+ installed = [message.copy() for message in installed]
+ session["history"] = installed
+ session["history_version"] = int(session.get("history_version", 0)) + 1
+ agent = session.get("agent")
+ if agent is not None:
+ agent._session_messages = installed
+ if hasattr(agent, "_last_flushed_db_idx"):
+ agent._last_flushed_db_idx = len(installed) if persisted else 0
+ if hasattr(agent, "_db_flush_scan_prefix"):
+ agent._db_flush_scan_prefix = installed[:] if persisted else None
+ return installed, live_view, rewound_count
+
+
+def _history_without_ephemeral_scaffolding(history: list[dict]) -> list[dict]:
+ """Return the durable transcript shape without transient recovery rows."""
+ from run_agent import _is_ephemeral_scaffolding
+
+ return [
+ message.copy()
+ for message in history
+ if not _is_ephemeral_scaffolding(message)
+ ]
+
+
+def _persist_session_git_meta(session: dict, cwd: str, generation: int) -> None:
+ """Resolve + persist a session's git branch / repo root WITHOUT blocking.
+
+ Branch and root come from ``git`` subprocess probes; running them inline on
+ the session-init / cwd-set path would stall startup whenever ``cwd`` is slow
+ or on an unreachable mount. Run them on a short-lived daemon thread instead
+ and persist via the same profile-aware db the caller writes ``cwd`` to.
+
+ Best-effort: ``cwd`` itself is persisted synchronously by the caller, so a
+ probe failure just leaves these enrichment columns unset (the project tree
+ falls back to its live resolver / lazy backfill). Daemon, so a mid-flight
+ probe never delays gateway shutdown.
+ """
+ session_key = session.get("session_key", "")
+ if (
+ not session_key
+ or not cwd
+ or isinstance(generation, bool)
+ or not isinstance(generation, int)
+ or generation < 1
+ ):
+ return
+ # Snapshot the routing fields now; the live session dict may be gone by the
+ # time the thread runs. `_session_db` reopens the profile-correct db inside.
+ db_session = {"session_key": session_key, "profile_home": session.get("profile_home")}
+
+ def _run() -> None:
+ try:
+ branch = _git_branch_for_cwd(cwd)
+ root = _git_common_repo_root_for_cwd(cwd)
+ if not (branch or root):
+ return
+ with _session_db(db_session) as db:
+ if db is not None:
+ db.publish_session_git_metadata(
+ session_key,
+ cwd,
+ generation,
+ branch,
+ root,
+ )
+ except Exception:
+ logger.debug("failed to persist session git metadata", exc_info=True)
+
+ threading.Thread(target=_run, name="git-meta", daemon=True).start()
+
+
+def _persist_session_cwd_and_schedule_git_meta(
+ session: dict,
+ cwd: str,
+ *,
+ db=None,
+) -> int | None:
+ """Claim a DB-backed probe generation, then start Git enrichment."""
+ try:
+ if db is not None:
+ generation = db.update_session_cwd(
+ session.get("session_key", ""), cwd
+ )
+ else:
+ with _session_db(session) as owner_db:
+ if owner_db is None:
+ return None
+ generation = owner_db.update_session_cwd(
+ session.get("session_key", ""), cwd
+ )
+ except Exception:
+ logger.debug("failed to persist session cwd", exc_info=True)
+ return None
+
+ if (
+ isinstance(generation, bool)
+ or not isinstance(generation, int)
+ or generation < 1
+ ):
+ return None
+ _persist_session_git_meta(session, cwd, generation)
+ return generation
+
+
+def _set_session_cwd(session: dict, cwd: str) -> str:
+ from hermes_constants import translate_cwd_for_wsl_backend
+
+ cwd = translate_cwd_for_wsl_backend(str(cwd))
+ 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 — persist it as the workspace (and let a later
+ # lazy row creation persist it too, not the launch-dir fallback).
+ session["explicit_cwd"] = True
+ # A user's choice supersedes any earlier settle-adopted cwd: from here on
+ # the terminal wandering must not move the workspace again.
+ session["cwd_from_settle"] = False
+ _register_session_cwd(session)
+ # The synchronous DB write claims ordering authority; Git subprocesses stay
+ # off the hot path and may publish only for that exact generation.
+ _persist_session_cwd_and_schedule_git_meta(session, resolved)
+ try:
+ from tools.terminal_tool import cleanup_vm
+
+ cleanup_vm(session["session_key"])
+ except Exception:
+ pass
+ return resolved
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ bind_module(globals(), server, skip=("_",))