The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): record the logged-in user_id on session rows
finn763cf398aba40b7
diff --git a/tests/tui_gateway/test_desktop_session_login_identity.py b/tests/tui_gateway/test_desktop_session_login_identity.pynew file mode 100644index 00000000000..57b20adfc34--- /dev/null+++ b/tests/tui_gateway/test_desktop_session_login_identity.py@@ -0,0 +1,102 @@+"""A Desktop session's state.db row must record the login that created it.++The dashboard/serve backend resolves the human at WS-upgrade auth (it writes+``login_success`` with the right ``user_id`` to logs/dashboard-auth.log) and the+runtime already carries that identity on the session record as ``auth_user_id``+(``_transport_auth_user_id``) — the same value the agent is built with. The+row-creating write just never passed it on, so every Desktop session read back+from ``state.db`` with an empty ``user_id`` while Discord/Telegram sessions+carried theirs (their adapters put the sender on the row at creation).++Anonymous sessions (no password provider, legacy token, stdio) stay+identity-less: nothing is inferred and nothing is stamped.+"""++from __future__ import annotations++from hermes_state import SessionDB+from tui_gateway import server+from tui_gateway.transport import bind_transport, reset_transport++_LOADED_USER = "alice"+_LOGIN = f"basic:{_LOADED_USER}"+++class _LoginSocket:+ """A live Desktop WS peer carrying the identity the upgrade auth minted."""++ def __init__(self, user_id=_LOADED_USER, provider="basic"):+ self.auth_identity = {"provider": provider, "user_id": user_id}++ def write(self, frame):+ return True+++class _AnonymousSocket:+ """A peer with no login behind it (stdio, legacy token, auth disabled)."""++ def write(self, frame):+ return True+++def _real_db(monkeypatch, tmp_path) -> SessionDB:+ db = SessionDB(db_path=tmp_path / "state.db")+ monkeypatch.setattr(server, "_get_db", lambda: db)+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")+ monkeypatch.setattr(server, "_start_agent_build", lambda *a, **k: None)+ return db+++def _create_desktop_session(transport, tmp_path) -> tuple[dict, str, str]:+ """``session.create`` as the Desktop client sends it; returns (record, sid, stored key)."""+ token = bind_transport(transport)+ try:+ resp = server.handle_request({+ "id": "1", "method": "session.create",+ "params": {"cols": 80, "source": "desktop", "cwd": str(tmp_path)},+ })+ sid = resp["result"]["session_id"]+ return dict(server._sessions[sid]), sid, resp["result"]["stored_session_id"]+ finally:+ reset_transport(token)+++def test_desktop_session_row_records_the_logged_in_user(monkeypatch, tmp_path):+ """Login succeeded, then a conversation: the row must name the human."""+ db = _real_db(monkeypatch, tmp_path)+ record, sid, key = _create_desktop_session(_LoginSocket(), tmp_path)+ try:+ assert record["auth_user_id"] == _LOGIN+ # What prompt.submit does before the agent exists (the first row write).+ assert server._ensure_session_db_row(record) is True+ finally:+ server._sessions.pop(sid, None)++ assert db.get_session(key)["user_id"] == _LOGIN+++def test_anonymous_desktop_session_row_stays_identity_less(monkeypatch, tmp_path):+ """No login on the transport => the row keeps its empty user_id."""+ db = _real_db(monkeypatch, tmp_path)+ record, sid, key = _create_desktop_session(_AnonymousSocket(), tmp_path)+ try:+ assert record["auth_user_id"] is None+ assert server._ensure_session_db_row(record) is True+ finally:+ server._sessions.pop(sid, None)++ assert not (db.get_session(key)["user_id"] or "").strip()+++def test_branch_child_row_carries_the_creators_login(monkeypatch, tmp_path):+ """A branch is a Desktop session too — the child row names the same human."""+ db = _real_db(monkeypatch, tmp_path)+ record, sid, key = _create_desktop_session(_LoginSocket(), tmp_path)+ try:+ assert server._ensure_session_db_row(record) is True # parent row the child FKs to+ server._seed_branch_row(record, "branch-key", key, [{"role": "user", "content": "hi"}],+ "desktop", None)+ finally:+ server._sessions.pop(sid, None)++ assert db.get_session("branch-key")["user_id"] == _LOGINdiff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 70f2e32facb..d493de3027c 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -7970,7 +7970,7 @@ def test_ensure_session_db_row_persists_explicit_cwd(monkeypatch, tmp_path):created = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"key": key, "source": source, "model": model, "model_config": model_config, "cwd": cwd})@@ -7991,7 +7991,7 @@ def test_ensure_session_db_row_persists_session_source(monkeypatch):created = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"key": key, "source": source, "model": model, "model_config": model_config, "cwd": cwd})@@ -8016,7 +8016,7 @@ def test_ensure_session_db_row_records_a_terminal_workspace(monkeypatch, tmp_patcreated = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"key": key, "source": source, "model": model, "model_config": model_config, "cwd": cwd})@@ -8039,7 +8039,7 @@ def test_ensure_session_db_row_defaults_desktop_to_no_workspace(monkeypatch, tmpcreated = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"key": key, "source": source, "model": model, "model_config": model_config, "cwd": cwd})@@ -8066,7 +8066,7 @@ def test_ensure_session_db_row_persists_session_model_override(monkeypatch):created = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"key": key, "model": model, "model_config": model_config, "cwd": cwd})@@ -8098,7 +8098,7 @@ def test_ensure_session_db_row_no_override_uses_global(monkeypatch):created = []class _FakeDB:- def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None):+ def create_session(self, key, source=None, model=None, model_config=None, parent_session_id=None, cwd=None, profile_name=None, user_id=None):created.append({"model": model, "model_config": model_config})monkeypatch.setattr(server, "_get_db", lambda: _FakeDB())diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex e56bae5cc8a..45c054dd9f5 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -223,14 +223,16 @@ def _billing_pending_change(result: dict) -> dict:# ── session.create / list / most_recent / facts ──────────────────────def _persist_branch(db, new_key: str, parent_key: str, title: str, history: list, *, source, cwd, profile_name,- copy_fields=(), compensate: bool = False, title_source: str = "user") -> None:+ copy_fields=(), compensate: bool = False, title_source: str = "user",+ user_id: str | None = None) -> None:"""Branch child row + parent transcript (bounded-chunk transactions) + title. ``_branched_from`` keeps therow visible in list_sessions_rich() (the live parent never matches the legacy end_reason='branched'heuristic); NULL ``profile_name`` rows drop out of profile-keyed sidebar matching / deep links. ``compensate``deletes a committed row whose transcript/title failed (a durable-but-empty row would defeat the INSERT OR- IGNORE first-prompt seed) — except on disk-full, where the delete cannot land."""+ IGNORE first-prompt seed) — except on disk-full, where the delete cannot land. ``user_id`` is the creating+ login: the child is a Desktop session too, and the row only records identity at insert."""db.create_session(new_key, source=source, model=_resolve_model(), model_config={"_branched_from": parent_key},- parent_session_id=parent_key, cwd=cwd, profile_name=profile_name)+ parent_session_id=parent_key, cwd=cwd, profile_name=profile_name, user_id=user_id)try:# Compensation guard (#93959 review): if the transcript copy or title write fails AFTER the row# committed, the durable-but-empty row would defeat the lazy first-prompt fallback@@ -267,7 +269,7 @@ def _seed_branch_row(record: dict, key: str, parent_session_id: str, history: li_persist_branch(db, key, parent_session_id, _branch_title(db, parent_session_id), history,source=source, cwd=record["cwd"],profile_name=profile_name_for_home(profile_home) or _current_profile_name(),- compensate=True, title_source="derived")+ compensate=True, title_source="derived", user_id=_session_auth_user_id(record))record["pending_title"] = None# The first submit's _persist_branch_seed is the fallback for a failed seed, not a second copy.record["_branch_seed_persisted"] = True@@ -2006,7 +2008,8 @@ def _(rid, params: dict, session: dict) -> dict:_persist_branch(db, new_key, old_key, title, history, source=source, cwd=_session_cwd(session),profile_name=profile_name_for_home(home) or _current_profile_name(),copy_fields=_BRANCH_COPY_FIELDS,- title_source="user" if params.get("name") else "derived")+ title_source="user" if params.get("name") else "derived",+ user_id=_session_auth_user_id(session))except Exception as e:return _err(rid, 5008, f"branch failed: {e}")try:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex bb3caf00569..83a79e9b75b 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -273,6 +273,11 @@ def _ensure_session_db_row(session: dict) -> bool:db.create_session(key, source=_session_source(session), model=row_model, model_config=model_config or None,parent_session_id=session.get("parent_session_id") or None, cwd=_persisted_session_cwd(session),+ # The login this session was opened under, in the same ``<provider>:<id>`` form the agent is+ # built with — the row is the only place the identity reaches the store, and the upsert can't+ # add it later (user_id is set at insert). None (no password provider, legacy token, stdio)+ # leaves the column empty exactly as before.+ user_id=_session_auth_user_id(session),# Self-describing rows: aggregators merging several profile DBs can't rely on which file a row came# from; a NULL is only repaired by the one-shot backfill.# Stamp the launch profile explicitly instead of leaving NULL — NULL is exactly what the