The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): stamp the login on the session record so rebuilds keep it
Erosika0b4df462554e
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.pyindex ac012b0f11d..2784b1a99e6 100644--- a/tests/test_tui_gateway_server.py+++ b/tests/test_tui_gateway_server.py@@ -4593,6 +4593,112 @@ def test_make_agent_passes_no_user_id_for_an_unknown_session(monkeypatch):assert captured["user_id"] is None+class _LoginSocket:+ """A live WS peer carrying the identity the upgrade auth minted."""++ def __init__(self, user_id="alice", provider="basic"):+ self.auth_identity = {"provider": provider, "user_id": user_id}+ self._closed = False++ def write(self, frame):+ return True+++def _login_session(monkeypatch, sid, key, transport, **extra) -> dict:+ """A record the way session.create stamps it: the login lives on the record, not the transport slot."""+ record = {"session_key": key, "transport": transport,+ "auth_user_id": server._transport_auth_user_id(transport), **extra}+ monkeypatch.setitem(server._sessions, sid, record)+ return record+++def test_make_agent_keeps_the_login_after_a_second_window_attaches_and_detaches(monkeypatch):+ """A pop-out turns the transport slot into a FanoutTransport, which names no login. The rebuild must read the+ login the record was created with, before and after the pop-out goes away."""+ captured = _capture_make_agent_kwargs(monkeypatch)+ first, popout = _LoginSocket(), _LoginSocket()+ record = _login_session(monkeypatch, "sid-popout", "k", first)++ assert server._attach_session_transport(record, popout)+ server._make_agent("sid-popout", "k")+ assert captured["user_id"] == "basic:alice"++ server._detach_session_transport(record, popout)+ server._make_agent("sid-popout", "k")+ assert captured["user_id"] == "basic:alice"+++def test_build_branch_agent_carries_the_parent_login(monkeypatch, tmp_path):+ """The branch agent is built before its record exists, so the parent's login is passed to the build and+ copied onto the new record."""+ captured = _capture_make_agent_kwargs(monkeypatch)+ socket = _LoginSocket()+ parent = _login_session(monkeypatch, "sid-parent", "parent-key", socket, cwd=str(tmp_path), source="desktop")++ def fake_init_session(sid, key, agent, history, **kwargs):+ monkeypatch.setitem(server._sessions, sid, {"session_key": key, "transport": server._stdio_transport})++ monkeypatch.setattr(server, "_set_session_context", lambda key: [])+ monkeypatch.setattr(server, "_clear_session_context", lambda tokens: None)+ monkeypatch.setattr(server, "_init_session", fake_init_session)+ monkeypatch.setattr(server, "_transfer_db_to_agent", lambda *args: False)+ token = bind_transport(socket)+ try:+ server._build_branch_agent(parent, "sid-branch", "branch-key", [], "desktop")+ finally:+ reset_transport(token)++ assert captured["user_id"] == "basic:alice"+ assert server._sessions["sid-branch"]["auth_user_id"] == "basic:alice"+++def test_deferred_session_record_stamps_the_creating_login():+ token = bind_transport(_LoginSocket("carol", "oidc"))+ try:+ record = server._deferred_session_record(+ "deferred-key", cols=80, cwd="/tmp", history=[], lease=None)+ finally:+ reset_transport(token)++ assert record["auth_user_id"] == "oidc:carol"+ assert server._session_auth_user_id(record) == "oidc:carol"+++def test_compute_host_turn_frame_carries_the_session_login(monkeypatch):+ record = _login_session(monkeypatch, "sid-host", "host-key", _LoginSocket(), history=[],+ history_lock=threading.Lock(), cwd="/tmp", cols=80)+ monkeypatch.setattr(server, "_session_cwd", lambda session: "/tmp")++ frame = server._compute_host_turn_frame("rid", "sid-host", record, "hello")++ assert frame["auth_user_id"] == "basic:alice"+++def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatch, caplog):+ """Ownership is not enforced. The record keeps the creator's login, and the attach is logged once with both+ ids rather than on every prompt the second client sends."""+ creator, other = _LoginSocket("alice"), _LoginSocket("bob")+ record = _login_session(monkeypatch, "sid-shared", "shared-key", creator)++ with caplog.at_level(logging.WARNING, logger="tui_gateway.server"):+ assert server._attach_session_transport(record, other)+ assert server._attach_session_transport(record, other)++ warnings = [rec.getMessage() for rec in caplog.records if "basic:bob" in rec.getMessage()]+ assert len(warnings) == 1+ assert "basic:alice" in warnings[0] and "shared-key" in warnings[0]+ assert server._session_auth_user_id(record) == "basic:alice"+++def test_attaching_the_same_login_again_does_not_warn(monkeypatch, caplog):+ record = _login_session(monkeypatch, "sid-same", "same-key", _LoginSocket("alice"))++ with caplog.at_level(logging.WARNING, logger="tui_gateway.server"):+ assert server._attach_session_transport(record, _LoginSocket("alice"))++ assert not [rec for rec in caplog.records if "logged in as" in rec.getMessage()]++def test_background_agent_kwargs_preserves_full_fallback_chain(monkeypatch):chain = [{"provider": "openrouter", "model": "openai/gpt-5.5"},diff --git a/tests/tui_gateway/test_compute_host_turn_protocol.py b/tests/tui_gateway/test_compute_host_turn_protocol.pyindex fb3b034b3a0..92e85bbd5bf 100644--- a/tests/tui_gateway/test_compute_host_turn_protocol.py+++ b/tests/tui_gateway/test_compute_host_turn_protocol.py@@ -240,3 +240,30 @@ def test_compute_host_interrupt_uses_explicit_stop_compatibility(monkeypatch, kiack = _frames(out)[-1]assert ack["type"] == "interrupt.ack" and ack["applied"] is Trueassert session["_turn_cancel_requested"] is True+++def test_host_builds_the_session_agent_with_the_frame_login(monkeypatch):+ """The host process has no record for a first turn, and its pipe names no login, so the agent is built+ from the login the frame carries and the new record keeps it for later rebuilds."""+ host = ComputeHost(stdout=io.StringIO(), heartbeat_secs=0)+ captured = {}++ def fake_make_agent(sid, key, **kwargs):+ captured.update(kwargs)+ return types.SimpleNamespace(session_id=key)++ def fake_init_session(sid, key, agent, history, **kwargs):+ monkeypatch.setitem(server._sessions, sid, {"agent": agent, "session_key": key})++ monkeypatch.setattr(server, "_make_agent", fake_make_agent)+ monkeypatch.setattr(server, "_transfer_db_to_agent", lambda agent, db: False)+ monkeypatch.setattr(server, "_init_session", fake_init_session)+ server._sessions.pop("s-login", None)++ session = host._build_server_session(+ server, {"sid": "s-login", "session_key": "login-key", "history": [], "auth_user_id": "basic:alice"},+ "s-login")++ assert captured["auth_user_id"] == "basic:alice"+ assert session["auth_user_id"] == "basic:alice"+ assert server._session_auth_user_id(session) == "basic:alice"diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.pyindex 2b76aa5b7b4..67502415182 100644--- a/tui_gateway/compute_host.py+++ b/tui_gateway/compute_host.py@@ -318,7 +318,7 @@ class ComputeHost:platform_override=frame.get("source"),context_cwd_is_launch_artifact=bool(frame.get("context_cwd_is_launch_artifact", False)),- session_db=session_db)+ session_db=session_db, auth_user_id=frame.get("auth_user_id"))if server._transfer_db_to_agent(agent, session_db):owns_db = Falsefinally:@@ -359,6 +359,8 @@ class ComputeHost:"transport": self._transport}session = server._sessions[sid]session["transport"] = self._transport+ # The host pipe names no login; the record carries the one the gateway stamped at creation.+ session["auth_user_id"] = frame.get("auth_user_id")session["profile_home"] = profile_home or session.get("profile_home")if frame.get("model_override") is not None:session["model_override"] = frame.get("model_override")diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.pyindex ab5fd9b0220..15fa092c604 100644--- a/tui_gateway/compute_host_bridge.py+++ b/tui_gateway/compute_host_bridge.py@@ -66,6 +66,7 @@ def _compute_host_turn_frame("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,+ "auth_user_id": _session_auth_user_id(session),"queued_prompt_generation": queued_prompt_generation}diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex d98537606ae..885f0f2e99b 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -357,7 +357,8 @@ def _(rid, params: dict) -> dict:"profile_home": str(profile_home) if profile_home is not None else None,"running": False, "session_key": key, "show_reasoning": _load_show_reasoning(), "source": source,"slash_worker": None, "tool_progress_mode": _load_tool_progress_mode(), "tool_started_at": {},- "transport": current_transport() or _stdio_transport}+ "transport": current_transport() or _stdio_transport,+ "auth_user_id": _transport_auth_user_id(current_transport())}_register_session_cwd(_sessions[sid])# No DB row here (drafts left "Untitled" litter): created on the first prompt — except seeded sessions.# NOTE: we intentionally do NOT persist a DB row here. Every TUI/desktop launch (and every "New agent" /@@ -781,7 +782,7 @@ def _resume_eager(ctx: _Resume) -> dict:agent = _make_agent_in_context(sid, ctx.target, session_db=ctx.db, platform_override=source,context_cwd_is_launch_artifact=(source in _LAUNCH_CWD_NOT_A_WORKSPACE and not ctx.profile_resume_cwd),- **stored_runtime_overrides)+ auth_user_id=_transport_auth_user_id(current_transport()), **stored_runtime_overrides)except Exception as e:return _err(ctx.rid, 5000, f"resume failed: {e}")with _session_resume_lock:@@ -1896,11 +1897,13 @@ def _build_branch_agent(session: dict, new_sid: str, new_key: str, history: list"""Build + register the branched agent in the parent's profile; the DEDICATED db handle is ours until``_transfer_db_to_agent`` (released here on failure)."""parent_home = session.get("profile_home")+ parent_user_id = _session_auth_user_id(session)branch_db, branch_owns_db = _profile_session_db(parent_home) if parent_home else (None, False)try:with _profile_build_scope(parent_home):agent = _make_agent_in_context(new_sid, new_key, session_db=branch_db, platform_override=source,- context_cwd_is_launch_artifact=_context_cwd_is_launch_artifact(session))+ context_cwd_is_launch_artifact=_context_cwd_is_launch_artifact(session),+ auth_user_id=parent_user_id)_init_session(new_sid, new_key, agent, list(history), cols=session.get("cols", 80),cwd=_session_cwd(session), session_db=branch_db, source=source, profile_home=parent_home,explicit_cwd=bool(session.get("explicit_cwd")))@@ -1908,6 +1911,7 @@ def _build_branch_agent(session: dict, new_sid: str, new_key: str, history: listbranch_owns_db = Falseif new_sid in _sessions:_sessions[new_sid]["active_session_lease"] = None # claimed lazily on the first turn+ _sessions[new_sid]["auth_user_id"] = parent_user_idreturn agentfinally:if branch_owns_db and branch_db is not None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex b728c36f119..165afabd008 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2255,21 +2255,32 @@ def _startup_system_prompt(cfg: dict, task_id: str) -> str:return system_prompt-def _session_auth_user_id(session: dict | None) -> str | None:- """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``session``'s transport, or None for- the legacy token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice``- and an OIDC ``alice`` apart."""- identity = getattr((session or {}).get("transport"), "auth_identity", None)+def _transport_auth_user_id(transport) -> str | None:+ """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``transport``, or None for the legacy+ token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice`` and an+ OIDC ``alice`` apart."""+ identity = getattr(transport, "auth_identity", None)if _methods_browser_control._is_authenticated_identity(identity):return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"return None+def _session_auth_user_id(session: dict | None) -> str | None:+ """The login ``session`` was created under, stamped on the record as ``auth_user_id``. A second window turns+ the transport slot into a FanoutTransport, which names no login, so only a record without the slot reads+ its transport."""+ session = session or {}+ if "auth_user_id" in session:+ return session["auth_user_id"]+ return _transport_auth_user_id(session.get("transport"))++def _make_agent(sid: str, key: str, session_id: str | None = None, session_db=None,model_override: dict | str | None = None, provider_override: str | None = None,reasoning_config_override: dict | None = None, service_tier_override: str | None = None,- platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None):+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,+ auth_user_id: str | None = None):# AC-4 test seam: dead unless armed by the isolated certify harness.from tui_gateway.synthetic_turn import maybe_build_synthetic_agentsynthetic = maybe_build_synthetic_agent(session_id or key, model_override)@@ -2307,7 +2318,8 @@ def _make_agent(provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,# The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.- user_id=_session_auth_user_id(session),+ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.+ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),@@ -2370,6 +2382,7 @@ def _init_session("model_override": None,# Async events go to the transport that created the session (stdio for Ink, WS for the dashboard)."transport": current_transport() or _stdio_transport,+ "auth_user_id": _transport_auth_user_id(current_transport()),}_session_todo_state(_sessions[sid])_hydrate_session_cwd(sid, key, session_db, profile_home)@@ -2434,6 +2447,7 @@ def _deferred_session_record("slash_worker": None, "source": source, "tool_progress_mode": _load_tool_progress_mode(),"tool_started_at": {}, "todo_state": todo_state,"transport": current_transport() or _stdio_transport,+ "auth_user_id": _transport_auth_user_id(current_transport()),}diff --git a/tui_gateway/session_transports.py b/tui_gateway/session_transports.pyindex 12ee7bc0465..07d5ecfe3ad 100644--- a/tui_gateway/session_transports.py+++ b/tui_gateway/session_transports.py@@ -35,6 +35,18 @@ def _session_has_live_transport(session: dict | None, *, excluding=None) -> boolreturn any(peer is not excluding for peer in _session_live_transports(session))+def _warn_foreign_login(session: dict, transport) -> None:+ """Ownership is not enforced; a second login sharing a session is only logged, and the agent keeps the+ creator's user id."""+ attaching = _transport_auth_user_id(transport)+ if attaching is None:+ return+ creator = _session_auth_user_id(session)+ if creator != attaching:+ logger.warning("Session %s keeps the user id %s it was created with; a client logged in as %s attached",+ session.get("session_key"), creator or "(none)", attaching)++def _attach_session_transport(session: dict | None, transport) -> bool:"""Add live peers; flatten captured queued fanouts without nesting authority."""if not session or transport is None:@@ -58,9 +70,12 @@ def _attach_session_transport(session: dict | None, transport) -> bool:if existing is transport:return Trueif isinstance(existing, FanoutTransport):+ if not existing.contains(transport):+ _warn_foreign_login(session, transport)existing.attach(transport)return existing.contains(transport)- elif _transport_is_live_peer(existing):+ _warn_foreign_login(session, transport)+ if _transport_is_live_peer(existing):session["transport"] = FanoutTransport(existing, transport)else:session["transport"] = transport