The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): a resumed named-profile chat lands in its own workspace
Brooklyn Nicholson21a9a1f0ec04
diff --git a/tests/tui_gateway/test_profile_resume_cwd.py b/tests/tui_gateway/test_profile_resume_cwd.pynew file mode 100644index 00000000000..2322ffc7c5a--- /dev/null+++ b/tests/tui_gateway/test_profile_resume_cwd.py@@ -0,0 +1,113 @@+"""A resumed session for a NAMED profile lands in THAT profile's workspace (#87584).++A Bot Chat is one forever-session, so fixing where new sessions start never reaches it: its row keeps whatever cwd+was stamped when it was created. Under the Docker image a named profile's chat was stamped with the launch profile's+``/opt/data``; resuming adopted that row as the session's explicit workspace, so ``pwd`` and the Files pane showed the+default profile's files. A resume with no stored cwd fell to ``_default_session_cwd()`` — the launch profile's — too.+"""++from __future__ import annotations++import pytest++import tui_gateway.server as server+from hermes_state import SessionDB+from tests.tui_gateway.test_tui_gateway_server import _write_profile_cfg++KEY = "20261005_120000_b07c4a7"+++class _ImmediateThread:+ def __init__(self, *, target, **_kwargs):+ self._target = target++ def start(self):+ self._target()+++def profile(monkeypatch):+ """A named local profile under the Hermes root (``/opt/data/profiles/austin``), placeholder ``terminal.cwd``."""+ root = server.get_hermes_home()+ home = _write_profile_cfg(root / "profiles" / "austin", ".")+ monkeypatch.setattr(server, "_profile_home", lambda name: home if name else None)+ monkeypatch.setenv("TERMINAL_CWD", str(root)) # the launch profile's workspace+ return home+++def resume(profile, monkeypatch):+ """``session.resume`` for ``profile`` against its real state.db; agent build and side schedulers off."""+ for name, value in {+ "_resolve_model": lambda: "test-model",+ "_enable_gateway_prompts": lambda: None,+ "_find_live_session_by_key": lambda _key, _home=None: None,+ "_schedule_agent_build": lambda *a, **k: None,+ "_schedule_session_cap_enforcement": lambda *a, **k: None,+ "_maybe_schedule_auto_continue": lambda *a, **k: None,+ "_child_run_active": lambda _key, _home=None: False,+ }.items():+ monkeypatch.setattr(server, name, value)+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(server.git_probe, "branch", lambda _cwd: None)+ monkeypatch.setattr(server.git_probe, "common_repo_root", lambda _cwd: None)+ db = SessionDB(db_path=profile / "state.db")+ known = set(server._sessions)++ def run(stored: str | None) -> dict:+ db.create_session(KEY, source="desktop", model="test-model", cwd=stored)+ resp = server.handle_request(+ {"id": "1", "method": "session.resume", "params": {"session_id": KEY, "profile": "austin"}}+ )+ assert "error" not in resp, resp+ return server._sessions[resp["result"]["session_id"]]++ run.db = db+ yield run+ with server._sessions_lock:+ for sid in [s for s in server._sessions if s not in known]:+ server._sessions.pop(sid, None)+ db.close()++[email protected]("stored", ["root", "sibling", "install", None])+def test_resume_lands_in_the_profiles_own_home(resume, profile, stored):+ root = server.get_hermes_home()+ sibling = root / "profiles" / "jordan"+ sibling.mkdir(parents=True, exist_ok=True)+ install = server.Path(server.__file__).resolve().parent.parent+ path = {"root": str(root), "sibling": str(sibling), "install": str(install), None: None}[stored]++ live = resume(path)++ assert live["cwd"] == str(profile)+ assert live["explicit_cwd"] is True+ assert server._terminal_task_cwd(live) == str(profile)++ # The agent build's hydration repairs the row, so the sidebar and later resumes agree with the live session.+ sid = next(s for s, rec in server._sessions.items() if rec is live)+ server._hydrate_session_cwd(sid, KEY, resume.db, str(profile))+ assert resume.db.get_session(KEY)["cwd"] == str(profile)+++def test_resume_keeps_a_folder_chosen_for_the_profile(resume, profile, tmp_path):+ inside = profile / "workspace"+ inside.mkdir()+ outside = tmp_path / "proj"+ outside.mkdir()++ live = resume(str(inside))++ assert live["cwd"] == str(inside)+ assert server._resumable_stored_cwd(str(outside), profile) == str(outside)+ assert server._resumable_stored_cwd(str(profile), profile) == str(profile)+ # A workspace a user keeps under the Hermes root (not Hermes's own dirs) is not another profile's.+ under_root = server.get_hermes_home() / "workspace"+ under_root.mkdir()+ assert server._resumable_stored_cwd(str(under_root), profile) == str(under_root)+++def test_launch_profile_resume_is_unchanged():+ """The launch profile (``profile_home`` None) keeps main's rule: its own root is a valid stored workspace."""+ root = str(server.get_hermes_home())+ assert server._resumable_stored_cwd(root, None) == rootdiff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 60f99535a64..a21a6860386 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -1071,7 +1071,7 @@ def _(rid, params: dict) -> dict:if (resp := _resume_guard(ctx)) is not None:return respctx.profile_resume_cwd = (_resumable_stored_cwd(_str_param(ctx.found, "cwd"), ctx.profile_home)- or _profile_workspace_cwd(ctx.profile_home))+ or _profile_default_cwd(ctx.profile_home))with _session_resume_lock: # fast path: reuse a session live IN THIS PROFILE, never another'slive = _find_live_session_by_key(ctx.target, ctx.profile_home)if live is not None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 849d42bfda6..5570ab0ba93 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2754,10 +2754,11 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Non_persist_session_cwd_and_schedule_git_meta(_sessions[sid], row["cwd"], db=db)except Exception:logger.debug("failed to enrich resumed session git metadata", exc_info=True)- elif not (row and row.get("cwd")) and hasattr(db, "update_session_cwd") and not _is_remote_launch_cwd(- _sessions.get(sid)- ):- # A stored cwd that was set aside (Hermes's own host tree) stays as stored: only an empty row is filled.+ elif (not (row and row.get("cwd")) or _is_other_profiles_cwd(row["cwd"], profile_home)) and hasattr(+ db, "update_session_cwd"+ ) and not _is_remote_launch_cwd(_sessions.get(sid)):+ # A stored cwd that was set aside (Hermes's own host tree) stays as stored: only an empty row is filled,+ # or a named profile's row holding another profile's dir (#87584), repaired to this session's own.try:_persist_session_cwd_and_schedule_git_meta(_sessions[sid], _sessions[sid]["cwd"], db=db)except Exception:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 07552881763..3e057af5c12 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -47,17 +47,9 @@ def _completion_cwd(params: dict | None = None) -> str:# env var; the dashboard's in-memory gateway does NOT inherit the PTY child's bridged TERMINAL_CWD, so a configured# terminal.cwd is read directly.named_ssh = profile_home is not None and _cwd_is_remote(profile_home)- # A NAMED profile with no configured workspace (placeholder/unset terminal.cwd) never inherits- # the LAUNCH profile's cwd (#87584): the Desktop stamps the app-global workspace into every- # pooled backend's TERMINAL_CWD, and _launch_configured_cwd()/that env var hold the launch- # profile's value — a session for another profile would land in the wrong workspace. Its own- # home is the same default its standalone gateway would use (placeholder → $HOME).- named_local_default = (- str(profile_home) if profile_home is not None and not named_ssh and not client_cwd and not session_cwd else None- )- raw = str(client_cwd or session_cwd or _profile_workspace_cwd(profile_home)+ raw = str(client_cwd or session_cwd or _profile_default_cwd(profile_home)# A named ssh profile never inherits the LAUNCH profile's host cwd: its remote default is ~.- or ("~" if named_ssh else "") or named_local_default or _launch_configured_cwd()+ or ("~" if named_ssh else "") or _launch_configured_cwd()or os.environ.get("TERMINAL_CWD") or _sandbox_workspace_cwd(None) or os.getcwd())# An ssh cwd lives on the remote host: host expansion/isdir cannot vouch for it, and ``~`` names the REMOTE# user's home, never this host's. The launch profile keeps main's host fast path for everything else.@@ -165,6 +157,17 @@ def _profile_workspace_cwd(profile_home) -> str | None:or (_sandbox_workspace_cwd(profile_home) if profile_home else None))+def _profile_default_cwd(profile_home) -> str | None:+ """Where a session for ``profile_home`` lands when nothing else is known: its configured workspace, else a NAMED+ local profile's own home. Never the LAUNCH profile's ``terminal.cwd``/``TERMINAL_CWD`` (#87584): those name+ another profile's workspace (``/opt/data`` in the Docker image). Its home is what its standalone gateway uses."""+ if workspace := _profile_workspace_cwd(profile_home):+ return workspace+ if profile_home is not None and _bound_terminal_backend(profile_home) == "local":+ return str(profile_home)+ return None++def _workspace_cwd(profile_home, raw: str) -> str:"""A picked workspace for a session bound to ``profile_home``: an ssh dir raw, else an existing host dir.Raises ValueError when a host dir does not exist."""@@ -287,12 +290,35 @@ def _is_hermes_owned_cwd(cwd: str, profile_home) -> bool:return any(path == root or root in path.parents for root in roots) or _is_install_tree(path)+def _is_other_profiles_cwd(cwd: str, profile_home) -> bool:+ """Whether a NAMED local profile's stored cwd is a directory that belongs to another profile or to Hermes itself:+ the root (``/opt/data``), its subprocess home (``/opt/data/home``), a sibling profile's tree, or the install tree.+ Those are launch-profile workspaces that leaked into this profile's row before #87584, never a folder chosen for+ it. Other folders under the root stay: a user may keep a workspace there."""+ if profile_home is None or _cwd_is_remote(profile_home) or not os.path.isabs(cwd):+ return False+ from agent.runtime_cwd import _is_install_tree+ from hermes_constants import get_default_hermes_root++ try:+ path, own = Path(cwd).resolve(), Path(profile_home).expanduser().resolve()+ root = get_default_hermes_root(home=own).resolve()+ except (OSError, RuntimeError):+ return False+ if path == own or own in path.parents:+ return False+ return path in (root, root / "home") or (root / "profiles") in path.parents or _is_install_tree(path)++def _resumable_stored_cwd(cwd, profile_home) -> str:"""A session row's stored cwd as a resume may adopt it: empty when an ssh session's row holds a path in Hermes's- own host tree (a host launch directory, never a remote workspace)."""+ own host tree (a host launch directory, never a remote workspace), or a named profile's row holds another+ profile's (the resume then lands in :func:`_profile_default_cwd` and re-persists it)."""cwd = str(cwd or "")if cwd and _cwd_is_remote(profile_home) and _is_hermes_owned_cwd(cwd, profile_home):return ""+ if cwd and _is_other_profiles_cwd(cwd, profile_home):+ return ""return cwd