Skip to content

The agent that grows with you

fix(tui_gateway): a chat restored under a new runtime takes over its own detached lease

kshitijk4poor3ca367ad80c8
diff --git a/tests/tui_gateway/test_cross_process_orphan_ownership.py b/tests/tui_gateway/test_cross_process_orphan_ownership.py
index 8658289d4d0..7c52e473d44 100644
--- a/tests/tui_gateway/test_cross_process_orphan_ownership.py
+++ b/tests/tui_gateway/test_cross_process_orphan_ownership.py
@@ -508,3 +508,75 @@ def test_automatic_desktop_cleanup_preserves_sibling_and_releases_sole_owner_lea
assert ended == []
finally:
_stop_child(child, release_file)
+
+
+# ── #104691: a reconnecting client under a NEW runtime owns its own chat ──
+
+def _runtime_record(session_key: str, transport, *, running: bool) -> dict:
+ class _Agent:
+ interrupted = False
+
+ def request_interrupt(self, *args, **kwargs) -> None:
+ self.interrupted = True
+
+ def interrupt(self, *args, **kwargs) -> None:
+ self.interrupted = True
+
+ def clear_interrupt(self) -> None:
+ pass
+
+ return {
+ "agent": _Agent(), "agent_ready": None, "transport": transport, "running": running,
+ "last_active": time.time(), "created_at": time.time(), "source": "desktop",
+ "session_key": session_key, "history": [], "history_lock": threading.Lock(),
+ "active_session_lease": None, "profile_home": None,
+ }
+
+
+def test_new_runtime_takes_over_detached_sibling_lease_in_same_process(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Desktop restores a chat under a new runtime while the old, client-less runtime (wedged turn) still holds
+ the lease: the new runtime gets the lease, the old turn is interrupted, the registry follows."""
+ key = "restored-chat"
+ old = _runtime_record(key, server._detached_ws_transport, running=True)
+ new = _runtime_record(key, object(), running=False)
+ monkeypatch.setattr(server, "_sessions", {"old": old, "new": new})
+ assert server._ensure_active_session_slot("old", old) is None
+ lease = old["active_session_lease"]
+
+ assert server._ensure_active_session_slot("new", new) is None
+
+ assert new["active_session_lease"] is lease and "active_session_lease" not in old
+ assert old["agent"].interrupted and old["_turn_cancel_requested"] is True
+ (entry,) = active_session_registry_snapshot()
+ assert entry["lease_id"] == lease.lease_id and entry["metadata"]["live_session_id"] == "new"
+ lease.release()
+
+
[email protected]_system_guard_bypass
+def test_new_runtime_never_takes_a_live_foreign_or_attached_lease(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Takeover is same-process AND client-less only: a lease held by a live foreign process, or by a sibling
+ runtime that still has a client (second window), keeps refusing."""
+ hermes_home = Path(os.environ["HERMES_HOME"])
+ ready_file, release_file = tmp_path / "ready", tmp_path / "release"
+ child = _spawn_lease_holder(home=hermes_home, session_id="foreign-chat", ready_file=ready_file,
+ release_file=release_file)
+ try:
+ _wait_for_child_file(child, ready_file, label="foreign lease holder")
+ foreign = _runtime_record("foreign-chat", object(), running=False)
+ attached = _runtime_record("two-windows", object(), running=False)
+ second = _runtime_record("two-windows", object(), running=False)
+ monkeypatch.setattr(server, "_sessions", {"f": foreign, "w1": attached, "w2": second})
+ assert server._ensure_active_session_slot("w1", attached) is None
+
+ for sid, record in (("f", foreign), ("w2", second)):
+ refusal = server._ensure_active_session_slot(sid, record)
+ assert getattr(refusal, "reason", None) == "SESSION_NOT_OWNED"
+ assert record.get("active_session_lease") is None
+ assert attached["active_session_lease"] is not None and not attached["agent"].interrupted
+ attached["active_session_lease"].release()
+ finally:
+ _stop_child(child, release_file)
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index 92e790c5dcc..9ba010f7be8 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -85,14 +85,51 @@ def _ensure_active_session_slot(sid: str, session: dict) -> str | None:
that starve the messaging gateway sharing the cap. Anything holding a slot must be user-visible."""
if session.get("active_session_lease") is not None:
return None
+ key = str(session.get("session_key") or "")
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"))
+ key, live_session_id=sid, surface=_session_source(session), profile_home=session.get("profile_home"))
if limit_message is None:
session["active_session_lease"] = lease
+ return None
+ from hermes_cli.active_sessions import SESSION_NOT_OWNED
+ if getattr(limit_message, "reason", None) == SESSION_NOT_OWNED and _take_over_detached_runtime_lease(sid, session, key):
+ return None
return limit_message
+def _take_over_detached_runtime_lease(sid: str, session: dict, key: str) -> bool:
+ """Hand a detached sibling runtime's lease for ``key`` to ``session``; True when it now owns the slot.
+
+ Lease identity is (pid, live_session_id), so a client that reconnects under a NEW runtime — Desktop
+ restoring a chat after a renderer crash, a reload during the client-gone settle window (4009 fences
+ ``session.resume``) — is a "different writer" of its own chat and was refused ``SESSION_NOT_OWNED`` until
+ the old runtime's reap released the lease (up to grace + activity-stale + interrupt polls). The user IS the
+ owner: the old runtime is in THIS process and has no client, so its turn is interrupted and the lease moves.
+ A live foreign pid, or a sibling that still has a client, keeps refusing — cross-process and multi-window
+ exclusivity are untouched. See #104691.
+ """
+ from hermes_cli.active_sessions import transfer_active_session
+ with _session_resume_lock, _sessions_lock:
+ for other_sid, other in _sessions.items():
+ if other is session or other.get("_finalized") or str(other.get("session_key") or "") != key:
+ continue
+ lease = other.get("active_session_lease")
+ if lease is None or getattr(lease, "released", False) or not _transport_is_dead(other.get("transport")):
+ continue
+ if not transfer_active_session(
+ lease, session_id=key, metadata={"live_session_id": sid, "bot_live_delivery_consumer": True}):
+ return False
+ del other["active_session_lease"]
+ session["active_session_lease"] = lease
+ break
+ else:
+ return False
+ logger.info("Session %s took over lease for %s from detached runtime %s", sid, key, other_sid)
+ with contextlib.suppress(Exception):
+ _interrupt_session_turn(other_sid, other, request_id=f"lease-takeover-{sid}")
+ return True
+
+
def _lease_retry(attempts: int, fn) -> Exception | None:
"""Call ``fn`` up to ``attempts`` times (50ms*n backoff: registry writes contend across processes); last
exception when every try failed, else None."""