Skip to content

The agent that grows with you

fix(tui_gateway): lease takeover stays within the profile and spares the new owner's row

kshitijk4poor8039bb1e619e
diff --git a/tests/tui_gateway/test_cross_process_orphan_ownership.py b/tests/tui_gateway/test_cross_process_orphan_ownership.py
index 7c52e473d44..876e222e429 100644
--- a/tests/tui_gateway/test_cross_process_orphan_ownership.py
+++ b/tests/tui_gateway/test_cross_process_orphan_ownership.py
@@ -580,3 +580,65 @@ def test_new_runtime_never_takes_a_live_foreign_or_attached_lease(
attached["active_session_lease"].release()
finally:
_stop_child(child, release_file)
+
+
+def test_takeover_stays_within_the_profile(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Timestamp ids collide across profiles' stores (#100029): profile B's refusal must not lift profile A's
+ detached runtime's lease — the entry that refused lives in B's registry, not A's."""
+ home_a, home_b = tmp_path / "A", tmp_path / "B"
+ key = "20260916_175430_a9e77f"
+ sibling = {**_runtime_record(key, server._detached_ws_transport, running=True), "profile_home": str(home_a)}
+ new = {**_runtime_record(key, object(), running=False), "profile_home": str(home_b)}
+ monkeypatch.setattr(server, "_sessions", {"a": sibling, "b": new})
+ assert server._ensure_active_session_slot("a", sibling) is None
+ holder_b, message = try_acquire_active_session(
+ session_id=key, surface="desktop", config={}, metadata={"live_session_id": "other-window"},
+ track_liveness=True, registry_home=home_b)
+ assert holder_b is not None and message is None
+ try:
+ refusal = server._ensure_active_session_slot("b", new)
+ assert getattr(refusal, "reason", None) == "SESSION_NOT_OWNED"
+ assert new.get("active_session_lease") is None
+ assert sibling["active_session_lease"] is not None and not sibling["agent"].interrupted
+ finally:
+ holder_b.release()
+ sibling["active_session_lease"].release()
+
+
+def test_taken_over_runtime_finalize_spares_the_new_owners_row(monkeypatch: pytest.MonkeyPatch) -> None:
+ """After a takeover the old record's automatic reap must not end the durable row, interrupt the key's
+ delegations or unregister the approval callback — the new runtime is driving all three now."""
+ key = "restored-tui-chat"
+ old = {**_runtime_record(key, server._detached_ws_transport, running=True), "source": "tui", "slash_worker": None}
+ new = {**_runtime_record(key, object(), running=False), "source": "tui"}
+ monkeypatch.setattr(server, "_sessions", {"old": old, "new": new})
+ assert server._ensure_active_session_slot("old", old) is None
+ assert server._ensure_active_session_slot("new", new) is None
+ lease = new["active_session_lease"]
+
+ ended: list = []
+ key_interrupts: list = []
+ unregistered: list = []
+
+ class _FakeDB:
+ def get_session(self, target):
+ return {"id": target, "source": "tui"}
+
+ def end_session(self, target, reason):
+ ended.append((target, reason))
+
+ @contextlib.contextmanager
+ def _db(_session):
+ yield _FakeDB()
+
+ monkeypatch.setattr(server, "_session_db", _db)
+ monkeypatch.setattr(server, "_notify_session_boundary", lambda *a, **k: None)
+ monkeypatch.setattr("tools.async_delegation.interrupt_for_session",
+ lambda *a, **k: key_interrupts.append(k.get("session_key")))
+ monkeypatch.setattr("tools.approval.unregister_gateway_notify", lambda k: unregistered.append(k))
+ try:
+ server._teardown_session(old, end_reason="ws_orphan_reap")
+ assert ended == [] and key_interrupts == [""] and unregistered == []
+ assert lease.released is False and new["active_session_lease"] is lease
+ finally:
+ lease.release()
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index 9ba010f7be8..a1f2a85cbc0 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -105,13 +105,14 @@ def _take_over_detached_runtime_lease(sid: str, session: dict, key: str) -> bool
``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.
+ A live foreign pid, a sibling that still has a client, or a same-id runtime of another profile keeps
+ refusing — cross-process, multi-window and cross-profile (#100029) 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:
+ if (other is session or other.get("_finalized") or str(other.get("session_key") or "") != key
+ or not _live_profile_matches(other, session.get("profile_home"))):
continue
lease = other.get("active_session_lease")
if lease is None or getattr(lease, "released", False) or not _transport_is_dead(other.get("transport")):
@@ -120,6 +121,7 @@ def _take_over_detached_runtime_lease(sid: str, session: dict, key: str) -> bool
lease, session_id=key, metadata={"live_session_id": sid, "bot_live_delivery_consumer": True}):
return False
del other["active_session_lease"]
+ other["_lease_taken_over"] = True # its finalize must spare the row + key-wide state the new owner drives
session["active_session_lease"] = lease
break
else:
@@ -344,8 +346,11 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
# Fix for #20001.
if _desktop_automatic_cleanup and not session_id:
_release_active_session_slot(session)
+ # A record whose lease was taken over by a new runtime for the same chat no longer owns the row, the
+ # key-wide delegations or the approval callback — that runtime does (_take_over_detached_runtime_lease).
_lifecycle_guard = (_other_runtime_lease_guard(session_id, session)
- if _desktop_automatic_cleanup and session_id else contextlib.nullcontext(False))
+ if _desktop_automatic_cleanup and session_id
+ else contextlib.nullcontext(bool(session.get("_lease_taken_over"))))
with _lifecycle_guard as _other_runtime_owns_lifecycle:
_tui_owns_lifecycle = not _other_runtime_owns_lifecycle
if _other_runtime_owns_lifecycle:
@@ -408,7 +413,7 @@ def _teardown_session(session: dict | None, *, end_reason: str = "tui_close") ->
_announce_session_reclaimed(session, end_reason)
with contextlib.suppress(Exception):
from tools.approval import unregister_gateway_notify
- if key := session.get("session_key"):
+ if (key := session.get("session_key")) and not session.get("_lease_taken_over"):
unregister_gateway_notify(key)
# agent.close() → shutdown_memory_provider reads the provider's config/credentials at call time; same
# scope rule as _finalize_session (every caller here is an unscoped reaper/atexit/pool thread).