Skip to content

The agent that grows with you

fix(tui): never persist an ssh session's launch directory as its workspace

yoniebansb97545ba4bf8
diff --git a/tests/tui_gateway/test_ssh_session_cwd_persistence.py b/tests/tui_gateway/test_ssh_session_cwd_persistence.py
new file mode 100644
index 00000000000..d74050e7605
--- /dev/null
+++ b/tests/tui_gateway/test_ssh_session_cwd_persistence.py
@@ -0,0 +1,121 @@
+"""An ssh session's launch directory is a host path: kept in memory, never persisted as its remote workspace.
+
+A resume adopts a stored ssh cwd as the remote workspace, so a persisted launch directory (in the Docker image
+``/opt/hermes``, ``/opt/data`` or ``/opt/data/home``) made every remote terminal and file call ``cd`` into a path that
+only exists on the Hermes host.
+"""
+
+from __future__ import annotations
+
+import contextlib
+
+import pytest
+
+import tui_gateway.server as server
+from hermes_state import SessionDB
+
+
+class _ImmediateThread:
+ def __init__(self, *, target, **_kwargs):
+ self._target = target
+
+ def start(self):
+ self._target()
+
+
+def backend(monkeypatch):
+ def use(name: str) -> None:
+ monkeypatch.setattr(server, "_effective_terminal_backend", lambda: name)
+
+ use("ssh")
+ return use
+
+
+def db(tmp_path, monkeypatch):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ 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)
+ yield db
+ db.close()
+
+
+def _hydrate(db, key: str, session: dict) -> dict:
+ sid = f"sid-{key}"
+ server._sessions[sid] = session
+ try:
+ server._hydrate_session_cwd(sid, key, db, None)
+ finally:
+ server._sessions.pop(sid, None)
+ return session
+
+
+def _hermes_home_subdir(name: str) -> str:
+ path = server.get_hermes_home() / name
+ path.mkdir(parents=True, exist_ok=True)
+ return str(path)
+
+
+def test_ssh_launch_dir_is_not_persisted(backend, tmp_path):
+ launch = str(tmp_path)
+ assert server._persisted_session_cwd({"source": "tui", "cwd": launch}) is None
+
+
+def test_ssh_explicit_cwd_is_persisted(backend):
+ session = {"source": "tui", "cwd": "/home/me/proj", "explicit_cwd": True}
+ assert server._persisted_session_cwd(session) == "/home/me/proj"
+
+
[email protected]("name", ["local", "docker"])
+def test_host_backends_still_persist_the_launch_dir(backend, tmp_path, name):
+ backend(name)
+ assert server._persisted_session_cwd({"source": "tui", "cwd": str(tmp_path)}) == str(tmp_path)
+
+
+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)})
+
+ assert session["cwd"] == "/home/me/proj"
+ assert session["explicit_cwd"] is True
+
+
+def test_resume_without_a_stored_cwd_does_not_persist_the_launch_dir(backend, db, tmp_path):
+ db.create_session("fresh", source="tui", model="m")
+ session = _hydrate(db, "fresh", {"session_key": "fresh", "source": "tui", "cwd": str(tmp_path)})
+
+ assert session["cwd"] == str(tmp_path)
+ assert not session.get("explicit_cwd")
+ assert db.get_session("fresh")["cwd"] is None
+
+
[email protected]("name", ["local", "docker"])
+def test_host_backends_resume_unchanged(backend, db, tmp_path, name):
+ """Docker installs on the local or docker backend keep adopting a stored cwd under HERMES_HOME."""
+ backend(name)
+ stored = _hermes_home_subdir("home")
+ db.create_session("host", source="tui", model="m", cwd=stored)
+ session = _hydrate(db, "host", {"session_key": "host", "source": "tui", "cwd": str(tmp_path)})
+
+ assert session["cwd"] == stored
+ assert not session.get("explicit_cwd")
+
+ db.create_session("host-fresh", source="tui", model="m")
+ _hydrate(db, "host-fresh", {"session_key": "host-fresh", "source": "tui", "cwd": str(tmp_path)})
+ assert db.get_session("host-fresh")["cwd"] == str(tmp_path)
+
+
[email protected](("explicit", "expected"), [(False, None), (True, "/home/me/proj")])
+def test_ssh_branch_seed_skips_the_launch_dir(backend, monkeypatch, explicit, expected):
+ seen = {}
+ monkeypatch.setattr(server, "_session_db", lambda _record: contextlib.nullcontext(object()))
+ monkeypatch.setattr(server, "_branch_title", lambda *_a: "t")
+ monkeypatch.setattr(server, "_persist_branch", lambda *_a, cwd, **_k: seen.setdefault("cwd", cwd))
+ record = {"cwd": "/home/me/proj" if explicit else "/opt/hermes", "explicit_cwd": explicit}
+
+ server._seed_branch_row(record, "child", "parent", [], "desktop", None)
+
+ assert seen["cwd"] == expected
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 6373e6a2f4b..b6f3c7e4058 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -292,7 +292,7 @@ def _seed_branch_row(record: dict, key: str, parent_session_id: str, history: li
if db is None:
return
_persist_branch(db, key, parent_session_id, _branch_title(db, parent_session_id), history,
- source=source, cwd=record["cwd"],
+ source=source, cwd=None if _is_remote_launch_cwd(record) else record["cwd"],
profile_name=profile_name_for_home(profile_home) or _current_profile_name(),
model=_session_default_model(record), compensate=True, title_source="derived", user_id=_session_auth_user_id(record))
record["pending_title"] = None
@@ -2297,7 +2297,8 @@ def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = Fals
try:
title = params.get("name", "") or _branch_title(db, old_key)
home = session.get("profile_home")
- _persist_branch(db, new_key, old_key, title, history, source=source, cwd=_session_cwd(session),
+ _persist_branch(db, new_key, old_key, title, history, source=source,
+ cwd=None if _is_remote_launch_cwd(session) else _session_cwd(session),
profile_name=profile_name_for_home(home) or _current_profile_name(),
model=_session_default_model(session), copy_fields=_BRANCH_COPY_FIELDS,
title_source="user" if params.get("name") else "derived",
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 422e3bb18ee..4b6fd1d910d 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2734,7 +2734,7 @@ 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"):
+ elif hasattr(db, "update_session_cwd") and not _is_remote_launch_cwd(_sessions.get(sid)):
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.py
index beb645f4ba1..c2391cdb1ff 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -220,11 +220,18 @@ def _persisted_session_cwd(session: dict) -> str | None:
"""The cwd to stamp on the session's DB row, or None to leave it unset (launch-dir rule: ``_ensure_session_db_row``)."""
if session.get("explicit_cwd"):
return _session_cwd(session)
- if _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE:
+ if _session_source(session) in _LAUNCH_CWD_NOT_A_WORKSPACE or _is_remote_launch_cwd(session):
return None
return str(session.get("cwd") or "") or None # the session's OWN dir, never _session_cwd's gateway-wide fallback
+def _is_remote_launch_cwd(session: dict | None) -> bool:
+ """An ssh session's cwd that nobody picked: the gateway's launch directory, a path on THIS host. Host-side context
+ discovery reads it from memory, but it is never persisted: a resume adopts a stored ssh cwd as the remote
+ workspace."""
+ return bool(session) and not session.get("explicit_cwd") and _cwd_is_remote(session.get("profile_home"))
+
+
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 branch
while the sidebar folds it to the main lane): walk up to the first existing ancestor and take its common git root.