Skip to content

The agent that grows with you

fix(tui_gateway): scope live-session reuse to the requesting profile

Teknium54b2c0ea388c
diff --git a/tests/tui_gateway/test_resume_live_profile_scope.py b/tests/tui_gateway/test_resume_live_profile_scope.py
new file mode 100644
index 00000000000..f6fd13d84c4
--- /dev/null
+++ b/tests/tui_gateway/test_resume_live_profile_scope.py
@@ -0,0 +1,108 @@
+"""``session.resume`` reuses a live session only within the requested profile.
+
+The live registry is keyed by bare stored session id, and stored ids are
+timestamp-based, so the same id can legitimately be live under profile A while
+profile B's store also holds it. The resume fast path (and the post-build
+re-check / ``_claim_or_reuse_live``) used to hand profile B's resume profile
+A's runtime — the turn then ran with A's persona and wrote A's memory
+(#100029). Pinned here:
+
+* resume with profile B never reuses profile A's live session of the same id;
+* the launch profile (no ``profile``) still matches live records that carry
+ no ``profile_home`` — the pre-existing single-profile contract.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tui_gateway import server
+
+
+class _DB:
+ """Minimal ``SessionDB`` stand-in: every profile store knows ``s1``."""
+
+ def __init__(self, db_path=None, **_kwargs):
+ self.db_path = db_path
+
+ def close(self):
+ pass
+
+ def get_session(self, target):
+ return {"id": "s1", "cwd": ""} if target == "s1" else None
+
+ def get_session_by_title(self, _target):
+ return None
+
+ def resolve_resume_session_id(self, target):
+ return target
+
+ def reopen_session(self, _target):
+ pass
+
+ def get_resume_conversations(self, _target):
+ return ([], [])
+
+ def get_ancestor_display_prefix(self, _target):
+ return []
+
+ def get_messages_as_conversation(self, _target, **_kwargs):
+ return []
+
+
+def homes(monkeypatch, tmp_path):
+ homes = {name: tmp_path / name for name in ("a", "b")}
+ for home in homes.values():
+ home.mkdir()
+ monkeypatch.setattr("hermes_state.get_shared_session_db", _DB)
+ monkeypatch.setattr(server, "_get_db", lambda: _DB())
+ monkeypatch.setattr(server, "_profile_home", lambda p: homes.get(p) if p else None)
+ monkeypatch.setattr(server, "_profile_configured_cwd", lambda _home: str(tmp_path))
+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
+ monkeypatch.setattr(server, "_schedule_agent_build", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_default_session_cwd", lambda *a, **k: str(tmp_path))
+ monkeypatch.setattr(server, "_child_run_active", lambda _key: False)
+ monkeypatch.setattr(
+ server, "_live_session_payload", lambda sid, session, **_k: {"session_id": sid}
+ )
+ known = set(server._sessions)
+ yield homes
+ with server._sessions_lock:
+ for sid in [s for s in server._sessions if s not in known]:
+ server._sessions.pop(sid, None)
+
+
+def _resume(**params):
+ return server.handle_request({"id": "1", "method": "session.resume", "params": params})
+
+
+def _register_live(sid: str, profile_home) -> dict:
+ record = {"session_key": "s1", "history": [], "last_active": 0.0}
+ if profile_home is not None:
+ record["profile_home"] = str(profile_home)
+ with server._sessions_lock:
+ server._sessions[sid] = record
+ return record
+
+
+def test_resume_with_other_profile_never_reuses_live_session(homes):
+ _register_live("live-a", homes["a"])
+
+ same = _resume(session_id="s1", profile="a", source="desktop")
+ assert same["result"]["session_id"] == "live-a"
+
+ other = _resume(session_id="s1", profile="b", source="desktop")
+ new_sid = other["result"]["session_id"]
+ assert new_sid != "live-a"
+ assert server._sessions[new_sid]["profile_home"] == str(homes["b"])
+
+
+def test_launch_profile_still_matches_records_without_profile_home(homes):
+ _register_live("live-launch", None)
+ _register_live("live-a", homes["a"])
+
+ assert _resume(session_id="s1", source="desktop")["result"]["session_id"] == "live-launch"
+ assert _resume(session_id="s1", profile="a", source="desktop")["result"]["session_id"] == "live-a"
diff --git a/tests/tui_gateway/test_session_resume_db_ownership.py b/tests/tui_gateway/test_session_resume_db_ownership.py
index 29f050ec30e..3e4aa9cbfb1 100644
--- a/tests/tui_gateway/test_session_resume_db_ownership.py
+++ b/tests/tui_gateway/test_session_resume_db_ownership.py
@@ -98,7 +98,7 @@ def profile_dbs(monkeypatch, tmp_path):
# The handler builds nothing on the paths under test; keep it hermetic and
# off the real agent/secret/HERMES_HOME machinery.
monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
- monkeypatch.setattr(server, "_find_live_session_by_key", lambda _key: None)
+ monkeypatch.setattr(server, "_find_live_session_by_key", lambda _key, *_a: None)
monkeypatch.setattr(server, "_schedule_agent_build", lambda *a, **k: None)
monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **k: None)
monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *a, **k: None)
@@ -196,7 +196,7 @@ def test_resume_closes_profile_db_on_live_session_fast_path(profile_dbs, monkeyp
monkeypatch.setattr(
server,
"_find_live_session_by_key",
- lambda _key: ("live-sid", live_session),
+ lambda _key, *_a: ("live-sid", live_session),
)
monkeypatch.setattr(
server,
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 66ae830391e..64bad0798fc 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -752,9 +752,11 @@ def _(rid, params: dict) -> dict:
_cancel_ws_orphan_reap(sid)
return _ok(rid, _reuse_live_payload(sid, session))
- # Fast path: if the session is already live, reuse it under the lock.
+ # Fast path: if the session is already live IN THIS PROFILE, reuse it
+ # under the lock. Never another profile's runtime of the same stored id
+ # — that ran profile B's turn on profile A's agent/memory (#100029).
with _session_resume_lock:
- live = _find_live_session_by_key(target)
+ live = _find_live_session_by_key(target, profile_home)
if live is not None:
return _reuse_live_response(*live)
@@ -1077,7 +1079,7 @@ def _(rid, params: dict) -> dict:
# live session while we were building. Re-check under the lock; if it won,
# discard our just-built agent and reuse theirs (no worker/poller wired yet).
with _session_resume_lock:
- live = _find_live_session_by_key(target)
+ live = _find_live_session_by_key(target, profile_home)
if live is not None:
try:
if hasattr(agent, "close"):
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 16d144f35a5..64438a3eb10 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -10965,14 +10965,33 @@ def _deferred_session_record(
}
+_ANY_PROFILE = object() # default: match a live session regardless of profile
+
+
+def _live_profile_matches(session: dict, profile_home) -> bool:
+ """True when ``session`` belongs to ``profile_home`` (None = launch profile).
+
+ Same string compare as session.resume's ``_find_live_unpersisted``: a
+ record with no ``profile_home`` is the launch profile's. ``_ANY_PROFILE``
+ disables the check for callers that have no profile to scope by.
+ """
+ if profile_home is _ANY_PROFILE:
+ return True
+ want = str(profile_home) if profile_home else None
+ return (session.get("profile_home") or None) == want
+
+
def _claim_or_reuse_live(
sid: str, session_key: str, record: dict, lease
) -> tuple[str, dict] | None:
"""Register ``record`` as the live session for ``session_key`` under the
resume lock, or — if a concurrent resume already won — release ``lease`` and
return the winner for the caller to reuse."""
+ # The record carries the home this resume resolved; a live runtime of the
+ # same stored id under ANOTHER profile is not a winner to reuse (#100029).
+ profile_home = record.get("profile_home")
with _session_resume_lock:
- live = _find_live_session_by_key(session_key)
+ live = _find_live_session_by_key(session_key, profile_home)
if live is not None:
if lease is not None:
lease.release()
@@ -10990,7 +11009,7 @@ def _claim_or_reuse_live(
# those quietly so the reap doesn't later broadcast session.reclaimed
# for a session the client just re-resumed (auto-re-resume storm).
_cancel_ws_orphan_reap(sid)
- stale = _claim_parked_runtimes(session_key, keep_sid=sid)
+ stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)
# Slow finalization work stays OUTSIDE _session_resume_lock (see
# _pop_session_by_id) — the stale records are already claimed above.
_finalize_superseded_runtimes(stale)
@@ -10998,7 +11017,7 @@ def _claim_or_reuse_live(
def _claim_parked_runtimes(
- session_key: str, *, keep_sid: str
+ session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE
) -> list[tuple[str, dict]]:
"""Claim sentinel-parked stale runtimes of ``session_key`` for supersession.
@@ -11017,6 +11036,7 @@ def _claim_parked_runtimes(
if old_sid != keep_sid
and not old.get("_finalized")
and _session_lookup_key(old, fallback=old_sid) == session_key
+ and _live_profile_matches(old, profile_home)
and old.get("transport") is _detached_ws_transport
]
for old_sid, _old in candidates:
@@ -11245,11 +11265,19 @@ def _session_lookup_key(session: dict, *, fallback: str = "") -> str:
)
-def _find_live_session_by_key(session_key: str) -> tuple[str, dict] | None:
+def _find_live_session_by_key(
+ session_key: str, profile_home=_ANY_PROFILE
+) -> tuple[str, dict] | None:
+ # Stored session ids are timestamp-based and can legitimately exist in more
+ # than one profile's store, so a bare-id match can hand profile B's resume
+ # profile A's live runtime (#100029). Profile-aware callers pass the home
+ # they resolved; the match must then be on (profile_home, session_key).
for sid, session in list(_sessions.items()):
if session.get("_finalized"):
continue
- if _session_lookup_key(session, fallback=sid) == session_key:
+ if _session_lookup_key(session, fallback=sid) == session_key and _live_profile_matches(
+ session, profile_home
+ ):
return sid, session
return None