Skip to content

The agent that grows with you

fix(tui_gateway): a profile-bound ticket's legacy session reads stay in its profile

Teknium2ad1d913daa9
diff --git a/tests/tui_gateway/test_legacy_fallback_profile_scope.py b/tests/tui_gateway/test_legacy_fallback_profile_scope.py
new file mode 100644
index 00000000000..26de332187f
--- /dev/null
+++ b/tests/tui_gateway/test_legacy_fallback_profile_scope.py
@@ -0,0 +1,57 @@
+"""B11: a ticket bound to a secondary profile reads ITS profile through the legacy session fallback.
+
+``session.most_recent`` / ``session.workspace.move`` / ``session.foreign.*`` open ``_profile_db``
+(the LAUNCH store when no ``profile`` is named) and ``session.active_list`` lists every legacy
+session in the process, so a profile-bound Ink/CLI ticket got the launch profile's latest session id
+and title (and Ink's auto-resume resumed it) and another profile's live rows."""
+import threading
+import types
+
+import pytest
+
+
+def homes(tmp_path, monkeypatch):
+ from tui_gateway import server
+ launch = tmp_path / 'root'
+ bee = launch / 'profiles' / 'bee'
+ bee.mkdir(parents=True)
+ monkeypatch.setenv('HERMES_HOME', str(launch))
+ monkeypatch.setattr(server, '_hermes_home', launch)
+ monkeypatch.setattr(server, '_db', None)
+ return server, launch, bee
+
+
+def test_profile_bound_ticket_reads_only_its_own_profile(homes, monkeypatch):
+ from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES
+ from hermes_state import SessionDB
+ from tui_gateway.ws_legacy_fallback import dispatch_legacy, legacy_fallback_allowed
+ server, launch, bee = homes
+ with SessionDB(launch / 'state.db') as db:
+ db.create_session('launch-sid', 'cli')
+ db.set_session_title('launch-sid', 'LAUNCH_PROFILE_SECRET_TITLE')
+ with SessionDB(bee / 'state.db') as db:
+ db.create_session('bee-sid', 'cli')
+ db.set_session_title('bee-sid', 'BEE_TITLE')
+ for sid, home in (('live-launch', None), ('live-bee', str(bee))):
+ monkeypatch.setitem(server._sessions, sid, {
+ 'session_key': sid, 'history': [{'role': 'user', 'content': 'PRIVATE ' + sid}],
+ 'history_lock': threading.Lock(), 'profile_home': home, 'created_at': 1, 'last_active': 1})
+
+ def call(profile_id, method):
+ actor = types.SimpleNamespace(capabilities=frozenset(_PURPOSE_CAPABILITIES['interactive']),
+ profile_id=str(profile_id))
+ assert legacy_fallback_allowed(actor, method)
+ written, done = [], threading.Event()
+ transport = types.SimpleNamespace(write=lambda frame: written.append(frame) or done.set() or True)
+ reply = dispatch_legacy(server, {'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': {}}, transport, actor)
+ # A long handler answers from the pool through the bound transport.
+ return reply if reply is not None else (done.wait(10) and written[0])
+
+ recent = call(bee, 'session.most_recent')['result']
+ assert (recent['session_id'], recent['title']) == ('bee-sid', 'BEE_TITLE'), recent
+ assert [row['id'] for row in call(bee, 'session.active_list')['result']['sessions']] == ['live-bee']
+ # The launch profile's own ticket is unchanged (main's single-profile behaviour).
+ assert call(launch, 'session.most_recent')['result']['session_id'] == 'launch-sid'
+ assert {row['id'] for row in call(launch, 'session.active_list')['result']['sessions']} == {
+ 'live-launch', 'live-bee'}
diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.py
index 406dff16255..f4078bbc408 100644
--- a/tui_gateway/ws_legacy_fallback.py
+++ b/tui_gateway/ws_legacy_fallback.py
@@ -78,13 +78,43 @@ def _foreign_profile_home(server: Any, profile_id: Any) -> str | None:
return str(home)
+def _own_profile_read(server: Any, req: dict, home: str) -> dict:
+ """A store-wide session read for a ticket bound to the non-launch *home*. Those handlers default
+ to the LAUNCH profile's store and ``session.active_list`` lists every profile's live sessions, so
+ the ticket's own profile is named (or the read refused), never the launch profile's served."""
+ from hermes_constants import profile_name_for_home
+ params = req.get("params") if isinstance(req.get("params"), dict) else {}
+ name = params.get("profile") or profile_name_for_home(home)
+ try:
+ resolved = server._profile_home(name) if name else None
+ except (OSError, ValueError):
+ resolved = None
+ if resolved is None or Path(resolved).resolve() != Path(home).resolve():
+ return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4064, "message": "profile unavailable"}}
+ if req.get("method") != "session.active_list":
+ return dict(req, params={**params, "profile": name})
+ with server._sessions_lock:
+ live = list(server._sessions.items())
+ current = str(params.get("current_session_id") or "")
+ rows = [server._session_live_item(sid, session, current) for sid, session in live
+ if not session.get("_finalized") and Path(session.get("profile_home") or server._launch_home()).resolve()
+ == Path(home).resolve()]
+ return {"jsonrpc": "2.0", "id": req.get("id"), "result": {"sessions": rows}}
+
+
def dispatch_legacy(server: Any, req: dict, transport: Any, actor: Any) -> dict | None:
"""Run ``server.dispatch`` with the ticket's profile home bound (call from a worker thread;
the pool path copies this context, so long handlers see it too)."""
actions, refusal = _PROCESS_GLOBAL_ACTIONS.get(req.get("method"), ((), ""))
if (req.get("params") or {}).get("action", "status") in actions:
return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4030, "message": refusal}}
- token = _connection_profile_home.set(_foreign_profile_home(server, getattr(actor, "profile_id", None)))
+ home = _foreign_profile_home(server, getattr(actor, "profile_id", None))
+ if home is not None and req.get("method") in _SESSION_FALLBACK_ALLOWED:
+ scoped = _own_profile_read(server, req, home)
+ if "result" in scoped or "error" in scoped:
+ return scoped
+ req = scoped
+ token = _connection_profile_home.set(home)
try:
return server.dispatch(req, transport)
finally: