The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): ssh "~" stays remote; docker named profiles keep main's task cwd
kshitijk4poorfd1ff96c8225
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex ba4f147f496..7e907ab83f0 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -1,3 +1,4 @@+import contextlibimport jsonimport loggingimport os@@ -22409,16 +22410,15 @@ def test_load_cfg_raw_sees_replacement_with_pinned_mtime_and_size(monkeypatch, tdef test_session_create_uses_bound_profile_backend_not_launch(monkeypatch, tmp_path):"""The regression: launch profile is LOCAL, the session is bound to an SSH profile.- session.create must read the BOUND profile's backend (via _profile_terminal_backend),- keep the remote cwd, and mark it explicit — not drop it to the launch dir."""+ session.create must read the BOUND profile's backend, keep the remote cwd, and mark it+ explicit — not drop it to the launch dir."""remote = "/home/felix/projects/xsd-parser"assert not os.path.isdir(remote)# Launch process looks local; only the bound profile is ssh.monkeypatch.setenv("TERMINAL_ENV", "local")monkeypatch.delenv("TERMINAL_CWD", raising=False)- monkeypatch.setattr(server, "_load_cfg", lambda: {"terminal": {"backend": "local"}})+ (tmp_path / "config.yaml").write_text("terminal:\n backend: ssh\n", encoding="utf-8")monkeypatch.setattr(server, "_profile_home", lambda name: tmp_path if name == "felix" else None)- monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: "ssh" if home == tmp_path else None)monkeypatch.setattr(server, "_schedule_agent_build", lambda sid: None)monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)@@ -22432,7 +22432,6 @@ def test_session_create_uses_bound_profile_backend_not_launch(monkeypatch, tmp_pserver._sessions.pop(sid, None)-def test_workspace_move_accepts_remote_dir_for_bound_ssh_profile(monkeypatch, tmp_path):"""session.workspace.move must not reject a remote project dir that does notexist on the host when the bound profile is ssh (the 'working directory does@@ -22440,16 +22439,15 @@ def test_workspace_move_accepts_remote_dir_for_bound_ssh_profile(monkeypatch, tmremote = "/home/felix/projects/xsd-parser"assert not os.path.isdir(remote)monkeypatch.setenv("TERMINAL_ENV", "local") # launch looks local+ (tmp_path / "config.yaml").write_text("terminal:\n backend: ssh\n", encoding="utf-8")monkeypatch.setattr(server, "_profile_home", lambda name: tmp_path if name == "felix" else None)- monkeypatch.setattr(server, "_profile_terminal_backend", lambda home: "ssh" if home == tmp_path else None)class _DB:def get_session(self, key):return {"session_key": key}def update_session_cwd(self, *a, **k):return 1- import contextlib as _ctx- monkeypatch.setattr(server, "_profile_db", lambda params, **_kw: _ctx.nullcontext(_DB()))+ monkeypatch.setattr(server, "_profile_db", lambda params, **_kw: contextlib.nullcontext(_DB()))monkeypatch.setattr(server.git_probe, "branch", lambda c: None)monkeypatch.setattr(server.git_probe, "common_repo_root", lambda c: None)@@ -22459,7 +22457,6 @@ def test_workspace_move_accepts_remote_dir_for_bound_ssh_profile(monkeypatch, tmassert resp["result"]["cwd"] == remote-@pytest.mark.parametrize("launch_backend", ["ssh", "local"])def test_ssh_named_profile_cwd_beats_launch_terminal_cwd(monkeypatch, tmp_path, launch_backend):"""A named SSH profile's terminal.cwd is on the remote. The desktop must use@@ -22489,7 +22486,9 @@ def test_ssh_named_profile_cwd_beats_launch_terminal_cwd(monkeypatch, tmp_path,) == "/opt/picked"# A local launch profile must not "heal" the remote dir to its nearest host ancestor (/home).assert server._display_session_cwd({"cwd": remote, "profile_home": str(home)}) == remote-+ # "~" names the REMOTE user's home, never this host's.+ (home / "config.yaml").write_text("terminal:\n backend: ssh\n cwd: ~/proj\n", encoding="utf-8")+ assert server._completion_cwd({"profile": "hunter", "cwd": launch, "cwd_explicit": False}) == "~/proj"def test_named_profile_without_backend_stays_local_under_ssh_launch(monkeypatch, tmp_path):diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex a14f8fed84f..18885bb68a9 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -376,7 +376,7 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->explicit_cwd = Falseraw_cwd = _str_param(params, "cwd") # unguarded, as on BASE: only the path check is best-effort# An ssh profile's cwd lives on the remote host, where the host isdir check cannot vouch for it.- remote_cwd = _cwd_is_remote(profile_home)+ remote_cwd = bool(raw_cwd) and _cwd_is_remote(profile_home)with contextlib.suppress(Exception):explicit_cwd = bool(raw_cwd) and (remote_cwd or os.path.isdir(os.path.abspath(os.path.expanduser(raw_cwd))))_enable_gateway_prompts()@@ -1007,11 +1007,10 @@ def _(rid, params: dict) -> dict:((sid, sess) for sid, sess in list(_sessions.items()) if sess.get("session_key") == target), ("", None))# The live session's profile decides (as _set_session_cwd below does); an ssh workspace is never host-validated.home = live.get("profile_home") if live is not None else _profile_home(params.get("profile"))- target_cwd = translate_cwd_for_wsl_backend(raw)- if not _cwd_is_remote(home):- target_cwd = os.path.abspath(os.path.expanduser(target_cwd))- if not os.path.isdir(target_cwd):- return _err(rid, 4017, f"working directory does not exist: {raw}")+ try:+ target_cwd = _workspace_cwd(home, translate_cwd_for_wsl_backend(raw))+ except ValueError:+ return _err(rid, 4017, f"working directory does not exist: {raw}")branch, root = git_probe.branch(target_cwd), git_probe.common_repo_root(target_cwd)with _profile_db(params, writer=True) as db:if db is None:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 7c23575d3df..0acbc41820c 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -628,30 +628,6 @@ def _profile_configured_cwd(profile_home: Path | None) -> str | None:return None-def _profile_terminal_policy(profile_home: Path | str | None) -> dict:- """A named profile's effective ``TERMINAL_*`` policy — the one its turns run under- (``tools/terminal_scope.py::build_profile_terminal_scope``: defaults <- ``.env`` <- ``config.yaml``).- {} for the launch profile or an unreadable profile."""- if profile_home is None:- return {}- from tools.terminal_scope import TerminalPolicyUnavailable, build_profile_terminal_scope- try:- return build_profile_terminal_scope(profile_home)- except TerminalPolicyUnavailable:- return {}---def _profile_terminal_backend(profile_home: Path | str | None) -> str | None:- """A named profile's terminal backend; None for the launch profile.-- At ``session.create`` the multiplex gateway has NOT yet rebound HERMES_HOME to the target profile, so- ``_effective_terminal_backend()`` reads the LAUNCH profile's backend, which must never leak into a named one.- """- if profile_home is None:- return None- return str(_profile_terminal_policy(profile_home).get("TERMINAL_ENV") or "local").strip().lower() or "local"--def _launch_configured_cwd() -> str | None:"""Launch profile's ``terminal.cwd`` from config.yaml: the dashboard's in-memory gateway gets no bridged``TERMINAL_CWD`` env (only the Node PTY child does), so a fresh /chat would otherwise start in ``os.getcwd()``."""diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 7ef7ac3966f..16b578f3485 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -29,7 +29,14 @@ def _completion_cwd(params: dict | None = None) -> str:# workspace pick (``cwd_explicit``) wins over the profile config. Path equality# cannot tell the two apart, so the desktop ships the flag alongside the path.client_cwd = params.get("cwd")- profile_home = _profile_home(params.get("profile"))+ profile = params.get("profile")+ profile_home = None+ if profile:+ # Main never resolved the profile for an explicit client cwd; a deleted one must not fail that path now.+ with contextlib.suppress(ProfileUnavailableError):+ profile_home = _profile_home(profile)+ if profile_home is None and not (params.get("cwd_explicit") and client_cwd):+ profile_home = _profile_home(profile)if not params.get("cwd_explicit") and client_cwd:if profile_cwd := _profile_workspace_cwd(profile_home):return profile_cwd@@ -39,13 +46,14 @@ def _completion_cwd(params: dict | None = None) -> str:raw = (client_cwd or _sessions.get(params.get("session_id") or "", {}).get("cwd")or _profile_workspace_cwd(profile_home) or _launch_configured_cwd()or os.environ.get("TERMINAL_CWD") or os.getcwd())+ # A named ssh profile's cwd lives on the remote host: host expansion/isdir cannot vouch for it (``~`` would name+ # THIS host's home). The launch profile keeps main's host check.+ if profile_home is not None and _cwd_is_remote(profile_home):+ return str(raw)with contextlib.suppress(Exception):resolved = os.path.abspath(os.path.expanduser(str(raw)))if os.path.isdir(resolved):return resolved- # An ssh cwd lives on the remote host, so the host isdir check above cannot vouch for it: pass it raw.- if _cwd_is_remote(profile_home):- return str(raw)return os.getcwd()@@ -58,9 +66,28 @@ def _workdir_terminal_cfg(key: str) -> str:return ""+def _profile_terminal_policy(profile_home) -> dict:+ """A named profile's effective ``TERMINAL_*`` policy — the one its turns run under+ (``build_profile_terminal_scope``: defaults <- ``.env`` <- ``config.yaml``). {} for the launch profile or an+ unreadable profile."""+ if not profile_home:+ return {}+ from tools.terminal_scope import TerminalPolicyUnavailable, build_profile_terminal_scope+ try:+ return build_profile_terminal_scope(Path(profile_home))+ except TerminalPolicyUnavailable:+ return {}+++def _policy_backend(policy: dict) -> str:+ return str(policy.get("TERMINAL_ENV") or "").strip().lower() or "local"++def _bound_terminal_backend(profile_home) -> str:- """Terminal backend of the profile a session/RPC is bound to: a named profile's own policy, else the process's."""- return _profile_terminal_backend(profile_home) or _effective_terminal_backend()+ """Terminal backend of the profile a session/RPC is bound to. A named profile reads ITS policy: at+ ``session.create`` the multiplex gateway has not rebound HERMES_HOME yet, so ``_effective_terminal_backend()``+ would report the LAUNCH profile's backend, which must never leak into a named one."""+ return _policy_backend(_profile_terminal_policy(profile_home)) if profile_home else _effective_terminal_backend()def _cwd_is_remote(profile_home) -> bool:@@ -73,18 +100,31 @@ def _declared_remote_profile_cwd(profile_home) -> str | None:"""A named ssh profile's own ``terminal.cwd`` (``~``, ``~/…`` or absolute), unchecked against this host.``_profile_configured_cwd`` requires ``os.path.isdir``; an ssh working directory lives on the remote, so that- check drops it and the launch profile's ``TERMINAL_CWD`` wins.+ check drops it (or expands ``~`` to THIS host's home) and the launch profile's ``TERMINAL_CWD`` wins."""+ from hermes_cli.config import _is_ssh_remote_tilde_cwd+policy = _profile_terminal_policy(profile_home)- if str(policy.get("TERMINAL_ENV") or "").strip().lower() != "ssh":+ backend, raw = _policy_backend(policy), str(policy.get("TERMINAL_CWD") or "").strip()+ if backend != "ssh":return None- raw = str(policy.get("TERMINAL_CWD") or "").strip()- return raw if raw == "~" or raw.startswith("~/") or os.path.isabs(raw) else None+ return raw if _is_ssh_remote_tilde_cwd(backend, raw) or os.path.isabs(raw) else Nonedef _profile_workspace_cwd(profile_home) -> str | None:- """A named profile's configured workspace: a host dir, or an ssh profile's remote dir."""- return _profile_configured_cwd(profile_home) or _declared_remote_profile_cwd(profile_home)+ """A named profile's configured workspace: an ssh profile's remote dir, else a host dir."""+ return _declared_remote_profile_cwd(profile_home) or _profile_configured_cwd(profile_home)+++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."""+ if _cwd_is_remote(profile_home):+ return raw+ resolved = os.path.abspath(os.path.expanduser(raw))+ if not os.path.isdir(resolved):+ raise ValueError(f"working directory does not exist: {raw}")+ return resolveddef _terminal_task_cwd(session: dict | None) -> str:@@ -98,7 +138,9 @@ def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:the global ``TERMINAL_CWD``/``terminal.cwd`` fallback — under per-session docker isolation that is a PREVIOUSsession's launch artifact, so terminal_tool refuses it as a bind-mount source."""profile_home = (session or {}).get("profile_home")- backend = _bound_terminal_backend(profile_home)+ # A named ssh profile's session is ssh whatever the launch process runs; other named backends keep main's+ # process-backend semantics (docker isolation's "process" vs "session" source depends on it).+ backend = "ssh" if profile_home and _cwd_is_remote(profile_home) else _effective_terminal_backend()if backend != "local":# THIS session's explicit workspace beats the LAST session's env var.if session and session.get("explicit_cwd") and session.get("cwd"):@@ -165,7 +207,11 @@ def _session_is_local_backend(session: dict | None) -> bool:process's: one multiplexed gateway serves many profiles, and a per-profile gateway (``hermes -p x``) may set``terminal.backend`` in config without ``TERMINAL_ENV`` — either way an env-only check would heal a live remotecwd to its nearest host ancestor (``/home``) and persist that."""- return _bound_terminal_backend(session.get("profile_home") if session else None) == "local"+ if session and session.get("profile_home"):+ return _bound_terminal_backend(session["profile_home"]) == "local"+ # Launch profile: main's env check, plus a per-profile gateway whose config (not env) says ssh.+ env_backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()+ return env_backend in ("", "local") and _effective_terminal_backend() != "ssh"def _effective_terminal_backend() -> str:@@ -589,13 +635,7 @@ def _persist_session_cwd_and_schedule_git_meta(session: dict, cwd: str, *, db=Nodef _set_session_cwd(session: dict, cwd: str) -> str:from hermes_constants import translate_cwd_for_wsl_backendcwd = translate_cwd_for_wsl_backend(str(cwd))- # An ssh workspace lives on the remote host: stored raw, never host-validated.- if _cwd_is_remote(session.get("profile_home")):- resolved = cwd- else:- resolved = os.path.abspath(os.path.expanduser(cwd))- if not os.path.isdir(resolved):- raise ValueError(f"working directory does not exist: {cwd}")+ resolved = _workspace_cwd(session.get("profile_home"), cwd)# An explicit user choice: persisted as the workspace (not the launch-dir fallback), superseding a settle-adopted cwd.session.update(cwd=resolved, explicit_cwd=True, cwd_from_settle=False)_register_session_cwd(session)