The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): don't resume an ssh session into Hermes's own host tree
yoniebans0a476f08afe7
diff --git a/tests/tui_gateway/test_ssh_session_cwd_persistence.py b/tests/tui_gateway/test_ssh_session_cwd_persistence.pyindex d74050e7605..534172ab9c0 100644--- a/tests/tui_gateway/test_ssh_session_cwd_persistence.py+++ b/tests/tui_gateway/test_ssh_session_cwd_persistence.py@@ -43,6 +43,33 @@ def db(tmp_path, monkeypatch):db.close()+def resume_db(db, monkeypatch, tmp_path):+ """``session.resume`` against the real SessionDB, 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,+ "_default_session_cwd": lambda *a, **k: str(tmp_path),+ "_child_run_active": lambda _key, _home=None: False,+ }.items():+ monkeypatch.setattr(server, name, value)+ known = set(server._sessions)+ yield db+ 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_live(key: str) -> dict:+ resp = server.handle_request({"id": "1", "method": "session.resume", "params": {"session_id": key}})+ assert "error" not in resp, resp+ return server._sessions[resp["result"]["session_id"]]++def _hydrate(db, key: str, session: dict) -> dict:sid = f"sid-{key}"server._sessions[sid] = session@@ -75,6 +102,74 @@ def test_host_backends_still_persist_the_launch_dir(backend, tmp_path, name):assert server._persisted_session_cwd({"source": "tui", "cwd": str(tmp_path)}) == str(tmp_path)+def test_hermes_owned_cwd(tmp_path):+ home = server.get_hermes_home()+ assert server._is_hermes_owned_cwd(str(home), None)+ assert server._is_hermes_owned_cwd(_hermes_home_subdir("home"), None)+ assert server._is_hermes_owned_cwd(str(server.Path(server.__file__).resolve().parent.parent), None)+ assert not server._is_hermes_owned_cwd("/home/me/proj", None)+ assert not server._is_hermes_owned_cwd(str(tmp_path), None)+++def test_hermes_owned_cwd_includes_the_root_for_a_named_profile():+ """A named profile's home sits under the Hermes root; the root's launch dirs (``/opt/data``, ``/opt/data/home``)+ are still Hermes's own."""+ root = server.get_hermes_home()+ profile = str(root / "profiles" / "work")+ assert server._is_hermes_owned_cwd(_hermes_home_subdir("home"), profile)+ assert server._is_hermes_owned_cwd(str(root), profile)+ assert server._is_hermes_owned_cwd(profile, profile)+ assert not server._is_hermes_owned_cwd("/home/me/proj", profile)+++def test_named_profile_resume_does_not_adopt_a_root_launch_dir(db):+ root = server.get_hermes_home()+ profile = root / "profiles" / "work"+ profile.mkdir(parents=True, exist_ok=True)+ (profile / "config.yaml").write_text("terminal:\n backend: ssh\n")+ stale = _hermes_home_subdir("home")+ db.create_session("named", source="tui", model="m", cwd=stale)+ session = {"session_key": "named", "source": "tui", "cwd": "~", "profile_home": str(profile)}+ server._sessions["sid-named"] = session+ try:+ server._hydrate_session_cwd("sid-named", "named", db, str(profile))+ finally:+ server._sessions.pop("sid-named", None)+ assert not session.get("explicit_cwd")+ assert server._terminal_task_cwd(session) == "~"+++def test_resume_leaves_a_set_aside_row_unchanged(backend, db):+ """With ``terminal.cwd`` set the session falls back to it as explicit; the stored row is still not rewritten."""+ stale = _hermes_home_subdir("home")+ db.create_session("aside", source="tui", model="m", cwd=stale)+ session = _hydrate(db, "aside", {"session_key": "aside", "source": "tui", "cwd": "/remote/default", "explicit_cwd": True})+ assert session["cwd"] == "/remote/default"+ assert db.get_session("aside")["cwd"] == stale++[email protected]("stored", ["~", "~/proj"])+def test_resume_keeps_a_remote_tilde_cwd_when_home_is_inside_hermes_home(backend, db, monkeypatch, tmp_path, stored):+ """The Docker image's HOME (``/opt/data/home``) sits inside HERMES_HOME; ``~`` still names the REMOTE home."""+ monkeypatch.setenv("HOME", _hermes_home_subdir("home"))+ db.create_session("tilde", source="tui", model="m", cwd=stored)+ session = _hydrate(db, "tilde", {"session_key": "tilde", "source": "tui", "cwd": str(tmp_path)})++ assert session["cwd"] == stored+ assert session["explicit_cwd"] is True+++def test_resume_does_not_adopt_a_stored_hermes_home_cwd(backend, db, tmp_path):+ """The ticket: a row stamped with ``/opt/data/home`` before this rule existed."""+ stale = _hermes_home_subdir("home")+ db.create_session("legacy", source="tui", model="m", cwd=stale)+ session = _hydrate(db, "legacy", {"session_key": "legacy", "source": "tui", "cwd": str(tmp_path)})++ assert session["cwd"] == str(tmp_path)+ assert not session.get("explicit_cwd")+ assert db.get_session("legacy")["cwd"] == stale # left as-is: every resume heals it again++def test_resume_keeps_a_stored_remote_workspace(backend, db, tmp_path):db.create_session("picked", source="tui", model="m", cwd="/home/me/proj")session = _hydrate(db, "picked", {"session_key": "picked", "source": "tui", "cwd": str(tmp_path)})@@ -119,3 +214,33 @@ def test_ssh_branch_seed_skips_the_launch_dir(backend, monkeypatch, explicit, exserver._seed_branch_row(record, "child", "parent", [], "desktop", None)assert seen["cwd"] == expected+++KEY = "20261003_120000_c0ffee"+++def test_session_resume_does_not_adopt_a_stored_hermes_home_cwd(backend, resume_db, tmp_path):+ resume_db.create_session(KEY, source="tui", model="test-model", cwd=_hermes_home_subdir("home"))+ live = _resume_live(KEY)++ assert live["cwd"] == str(tmp_path)+ assert not live.get("explicit_cwd")+++def test_session_resume_keeps_a_stored_remote_workspace(backend, resume_db):+ resume_db.create_session(KEY, source="tui", model="test-model", cwd="/home/me/proj")+ live = _resume_live(KEY)++ assert live["cwd"] == "/home/me/proj"+ assert live["explicit_cwd"] is True++[email protected]("name", ["local", "docker"])+def test_session_resume_on_host_backends_unchanged(backend, resume_db, name):+ backend(name)+ stored = _hermes_home_subdir("home")+ resume_db.create_session(KEY, source="tui", model="test-model", cwd=stored)+ live = _resume_live(KEY)++ assert live["cwd"] == stored+ assert live["explicit_cwd"] is Truediff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex b6f3c7e4058..50062ce2642 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -1062,7 +1062,8 @@ def _(rid, params: dict) -> dict:_resume_follow_tip(ctx)if (resp := _resume_guard(ctx)) is not None:return resp- ctx.profile_resume_cwd = _str_param(ctx.found, "cwd") or _profile_workspace_cwd(ctx.profile_home)+ ctx.profile_resume_cwd = (_resumable_stored_cwd(_str_param(ctx.found, "cwd"), ctx.profile_home)+ or _profile_workspace_cwd(ctx.profile_home))# Fast path: reuse a session live IN THIS PROFILE (never another profile's runtime).with _session_resume_lock:live = _find_live_session_by_key(ctx.target, ctx.profile_home)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 4b6fd1d910d..f7755d47607 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -2715,7 +2715,7 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Nontry:if db is not None:row = db.get_session(key) if hasattr(db, "get_session") else None- if row and row.get("cwd"):+ if row and _resumable_stored_cwd(row.get("cwd"), profile_home):# An ssh session's stored cwd is its workspace: explicit, so the remote terminal uses it instead of# the profile's ~. Other backends keep main's semantics (resolved outside the sessions lock: I/O).remote = _cwd_is_remote(profile_home)@@ -2734,7 +2734,10 @@ 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 hasattr(db, "update_session_cwd") and not _is_remote_launch_cwd(_sessions.get(sid)):+ 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.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 c2391cdb1ff..39f0f63df35 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -232,6 +232,33 @@ def _is_remote_launch_cwd(session: dict | None) -> bool:return bool(session) and not session.get("explicit_cwd") and _cwd_is_remote(session.get("profile_home"))+def _is_hermes_owned_cwd(cwd: str, profile_home) -> bool:+ """Whether ``cwd`` is inside Hermes's own host tree: the Hermes root (``/opt/data`` and its ``/opt/data/home``+ subprocess home in the Docker image, which also holds every named profile) or the install tree+ (``/opt/hermes``). A ``~`` path is the remote's home, never this host's."""+ from agent.runtime_cwd import _is_install_tree+ from hermes_constants import get_default_hermes_root++ if not os.path.isabs(cwd):+ return False+ try:+ path = Path(cwd).resolve()+ home = Path(profile_home or get_hermes_home()).expanduser()+ roots = {home.resolve(), get_default_hermes_root(home=home).resolve()}+ except (OSError, RuntimeError):+ return False+ return any(path == root or root in path.parents for root in roots) 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)."""+ cwd = str(cwd or "")+ if cwd and _cwd_is_remote(profile_home) and _is_hermes_owned_cwd(cwd, profile_home):+ return ""+ return cwd++def _heal_dead_cwd(cwd: str) -> str:"""Resolve a session cwd inside a now-deleted directory (e.g. a removed linked worktree, which probes to no branchwhile the sidebar folds it to the main lane): walk up to the first existing ancestor and take its common git root.