The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): remote backends no longer inherit the TUI process launch directory as their working directory
Ben Barclay781d8e546e15
diff --git a/tests/tools/test_file_tools_cwd_resolution.py b/tests/tools/test_file_tools_cwd_resolution.pyindex 3482a2cc18b..7e9ef4ec574 100644--- a/tests/tools/test_file_tools_cwd_resolution.py+++ b/tests/tools/test_file_tools_cwd_resolution.py@@ -352,3 +352,21 @@ def test_v4a_delete_and_move_act_on_a_symlink_not_its_target(assert str(link) in out["files_modified"]if dest:assert os.readlink(workspace / dest) == "safe/base.yaml"++[email protected]("live_cwd", [None, "/home/sprite"], ids=["config-default", "live-env"])+def test_container_relative_path_without_a_recorded_cwd_uses_the_backend_cwd(_isolated_cwd, monkeypatch, live_cwd):+ """A container session with no recorded cwd resolves relative paths against the sandbox's own cwd: the+ process cwd is a host directory (``/opt/data`` in the hosted image) that does not exist in the sandbox."""+ _workspace, decoy = _isolated_cwd+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: {"env_type": "modal", "cwd": "/root"})+ envs = {}+ if live_cwd:+ envs["default"] = type("ModalEnvironment", (), {"cwd": live_cwd})()+ monkeypatch.setattr(terminal_tool, "_active_environments", envs)++ resolved = ftp._resolve_path_for_task("notes/todo.md", task_id="default")++ assert resolved == PurePosixPath(live_cwd or "/root") / "notes" / "todo.md"+ assert not str(resolved).startswith(str(decoy))diff --git a/tests/tui_gateway/test_remote_backend_launch_cwd.py b/tests/tui_gateway/test_remote_backend_launch_cwd.pynew file mode 100644index 00000000000..218750bad9a--- /dev/null+++ b/tests/tui_gateway/test_remote_backend_launch_cwd.py@@ -0,0 +1,145 @@+"""A TUI/dashboard session on a sandbox backend never sends the gateway's launch directory to the sandbox.++The hosted image runs the gateway with cwd ``/opt/data`` (the Hermes home). A session created with no workspace kept+that host directory as its cwd, and ``_terminal_task_cwd_with_source`` registered it as the terminal cwd of a modal /+daytona / sprites / plugin sandbox, where it does not exist: every command failed ``cd: /opt/data: No such file or+directory`` (exit 126). The backend's own default applies instead, as on the messaging gateway.+"""++from __future__ import annotations++import pytest++from tools import terminal_tool+from tui_gateway import server+++def launch_dir(tmp_path, monkeypatch):+ """The gateway's launch directory: an existing host dir nobody picked, with no configured terminal.cwd."""+ home = tmp_path / "hermes-home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(server, "_hermes_home", home)+ for name in ("TERMINAL_ENV", "TERMINAL_CWD", "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"):+ monkeypatch.delenv(name, raising=False)+ launch = tmp_path / "opt-data"+ launch.mkdir()+ monkeypatch.chdir(launch)+ return launch+++def _backend(monkeypatch, name: str, **env: str) -> None:+ monkeypatch.setenv("TERMINAL_ENV", name)+ for key, value in env.items():+ monkeypatch.setenv(key, value)+++def _fresh_session(key: str) -> dict:+ """What ``session.create`` stores for a TUI session that sent no cwd (no ``HERMES_TUI_CWD``)."""+ explicit, cwd, _remote = server._resolve_create_cwd({}, "tui", None)+ return {"session_key": key, "cwd": cwd, "explicit_cwd": explicit, "profile_home": None, "source": "tui"}++[email protected]("backend", ["modal", "daytona", "singularity"])+def test_sandbox_session_does_not_register_the_launch_dir(launch_dir, monkeypatch, backend):+ _backend(monkeypatch, backend)+ session = _fresh_session(f"launch-{backend}")+ assert session["cwd"] == str(launch_dir) and not session["explicit_cwd"]++ assert server._terminal_task_cwd_with_source(session) == ("", "process")++ server._register_session_cwd(session)+ try:+ assert terminal_tool.get_session_cwd(session["session_key"]) is None+ # The per-command cwd is the backend default, never the host launch dir.+ assert terminal_tool._resolve_command_cwd(+ workdir=None, default_cwd="/root", session_key=session["session_key"], env_type=backend) == "/root"+ finally:+ terminal_tool.clear_task_env_overrides(session["session_key"])+++def test_plugin_sandbox_backend_does_not_register_the_launch_dir(launch_dir, monkeypatch):+ """A plugin backend (sprites) declaring ``is_remote``/``is_container``."""+ import agent.terminal_env_registry as registry++ _backend(monkeypatch, "sprites")+ monkeypatch.setattr(registry, "provider_flag", lambda name, attr, default=False: name == "sprites")+ session = _fresh_session("launch-sprites")++ assert server._terminal_task_cwd_with_source(session) == ("", "process")+ assert server._persisted_session_cwd(session) is None+++def test_plugin_host_backend_keeps_the_launch_dir(launch_dir, monkeypatch):+ """A plugin backend declaring neither flag runs on this host: the launch dir stays its cwd."""+ import agent.terminal_env_registry as registry++ _backend(monkeypatch, "hostrunner")+ monkeypatch.setattr(registry, "provider_flag", lambda name, attr, default=False: False)+ session = _fresh_session("launch-hostrunner")++ assert server._terminal_task_cwd_with_source(session) == (str(launch_dir), "session")+++def test_explicit_workspace_still_wins_on_a_sandbox_backend(launch_dir, monkeypatch, tmp_path):+ _backend(monkeypatch, "modal")+ project = tmp_path / "project"+ project.mkdir()+ explicit, cwd, _remote = server._resolve_create_cwd({"cwd": str(project)}, "tui", None)+ session = {"session_key": "explicit", "cwd": cwd, "explicit_cwd": explicit, "profile_home": None}++ assert explicit+ assert server._terminal_task_cwd_with_source(session) == (str(project), "session")+++def test_configured_sandbox_cwd_still_wins(launch_dir, monkeypatch):+ _backend(monkeypatch, "modal", TERMINAL_CWD="/workspace")+ session = _fresh_session("configured")++ assert server._terminal_task_cwd_with_source(session) == ("/workspace", "process")+++def test_local_backend_keeps_the_launch_dir(launch_dir, monkeypatch):+ session = _fresh_session("local")++ assert server._terminal_task_cwd_with_source(session) == (str(launch_dir), "session")+ assert server._persisted_session_cwd(session) == str(launch_dir)++[email protected]("mount", ["true", "false"])+def test_docker_keeps_the_host_dir(launch_dir, monkeypatch, mount):+ """docker is unchanged: with ``docker_mount_cwd_to_workspace`` the host dir is the bind-mount source, tagged+ ``session`` so per-session isolation mounts it (terminal_tool remaps it to /workspace); without it the session+ keeps its workspace container key."""+ _backend(monkeypatch, "docker", TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE=mount)+ session = _fresh_session(f"docker-mount-{mount}")++ assert server._terminal_task_cwd_with_source(session) == (str(launch_dir), "session")+ assert server._persisted_session_cwd(session) == str(launch_dir)+++def test_sandbox_resume_drops_a_stored_hermes_home_cwd(launch_dir, monkeypatch):+ """A row persisted before the fix with the Hermes home as cwd is not re-adopted as the sandbox workspace."""+ hermes_home = str(server._hermes_home)+ _backend(monkeypatch, "modal")+ assert server._resumable_stored_cwd(hermes_home, None) == ""++ monkeypatch.setenv("TERMINAL_ENV", "local")+ assert server._resumable_stored_cwd(hermes_home, None) == hermes_home+++def test_sandbox_path_completion_lists_the_backend_cwd(launch_dir, monkeypatch):+ """``complete.path`` with no terminal cwd lists relative to the backend's own cwd, never the host dir."""+ _backend(monkeypatch, "modal")+ seen = {}++ def fake_entries(search_dir, session_key):+ seen["dir"] = search_dir+ return [("notes.md", False)]++ monkeypatch.setattr(server, "_backend_dir_entries", fake_entries)+ resp = server.handle_request({"id": "1", "method": "complete.path", "params": {"word": "no"}})++ assert seen["dir"] == "."+ assert [i["text"] for i in resp["result"]["items"]] == ["notes.md"]diff --git a/tools/file_tools_paths.py b/tools/file_tools_paths.pyindex 4422086e3ae..8e3b2fa3fbc 100644--- a/tools/file_tools_paths.py+++ b/tools/file_tools_paths.py@@ -259,11 +259,27 @@ def _resolve_base_dir(if _terminal_env_type_for_task(task_id) == "ssh":return _resolve_ssh_path(".", task_id)container_paths = _uses_container_paths(task_id)- root = _authoritative_workspace_root(task_id)+ root = _authoritative_workspace_root(task_id) or (_container_default_cwd(task_id) if container_paths else None)# A backend's relative cwd is anchored to the process cwd once, here.return _anchor(_host_text(root or os.getcwd(), container_paths), os.getcwd, container_paths)+def _container_default_cwd(task_id: str = "default") -> str | None:+ """A container backend's own working directory when the session recorded none: the live env's cwd, else the+ configured one (already sanitized to the backend default). The process cwd is a host directory (``/opt/data``+ in the Docker image) the sandbox does not have, and terminal commands do not run there."""+ try:+ from tools.terminal_tool import _get_env_config+ from tools.terminal_tool_lifecycle import get_active_env++ for cwd in (getattr(get_active_env(task_id), "cwd", None), _get_env_config().get("cwd")):+ if isinstance(cwd, str) and posixpath.isabs(cwd):+ return cwd+ except Exception:+ pass+ return None++def _resolve_path_for_task(filepath: str, task_id: str = "default") -> Path | PurePosixPath:"""Resolve *filepath* against the task's absolute base directory(absolute inputs are returned resolved-but-unanchored)."""diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 43ac54229cf..ec944b782b7 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -235,8 +235,8 @@ def _(rid, params: dict) -> dict:session = _sessions.get(params.get("session_id", ""))local = _effective_terminal_backend() == "local"# A non-local backend's cwd lives inside the target; the host cannot validate it, so take the composer's- # session cwd (Desktop sends it) or the session's terminal cwd as-is.- root = _completion_cwd(params) if local else (params.get("cwd") or _terminal_task_cwd(session))+ # session cwd (Desktop sends it) or the session's terminal cwd as-is ("." = the backend's own cwd).+ root = _completion_cwd(params) if local else (params.get("cwd") or _terminal_task_cwd(session) or ".")session_key = session.get("session_key") if session else Nonereturn _ok(rid, {"items": _path_completion_items(word, root, session_key, local)})diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 3e057af5c12..9fff545600e 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -183,7 +183,7 @@ def _workspace_cwd(profile_home, raw: str) -> str:def _terminal_task_cwd(session: dict | None) -> str:"""The cwd terminal_tool should use for this TUI session (NOT host-validated: a non-local backend's cwd lives- inside the target environment)."""+ inside the target environment). "" when the backend's own default applies."""return _terminal_task_cwd_with_source(session)[0]@@ -209,8 +209,14 @@ def _terminal_task_cwd_with_source(session: dict | None) -> tuple[str, str]:return raw, "process"if backend == "ssh":return "~", "process"+ # A host directory nobody picked (the gateway's launch dir) names nothing inside a sandbox: register no cwd, so+ # the backend's own default applies, as on the messaging gateway. "" is that "no cwd" answer.+ if _is_remote_launch_cwd(session):+ return "", "process"if session and session.get("cwd"):return str(session["cwd"]), "session"+ if not _host_cwd_is_terminal_cwd(profile_home):+ return "", "process"return _completion_cwd(), "process"@@ -266,10 +272,34 @@ def _persisted_session_cwd(session: dict) -> str | None: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"))+ """A cwd nobody picked for a session whose terminal does not run in host directories: an ssh session's, or a+ sandbox backend's (modal, daytona, singularity, sprites, ...) when it is a directory on THIS host: the gateway's+ launch directory (``/opt/data`` in the Docker image). Host-side context discovery reads it from memory, but it+ never becomes the terminal cwd and is never persisted: a resume adopts a stored cwd as the session's workspace.+ A sandbox path (``/workspace``) is not a host directory and stays."""+ if not session or session.get("explicit_cwd"):+ return False+ profile_home = session.get("profile_home")+ if _cwd_is_remote(profile_home):+ return True+ cwd = str(session.get("cwd") or "")+ return bool(cwd) and not _host_cwd_is_terminal_cwd(profile_home) and os.path.isdir(cwd)+++def _host_cwd_is_terminal_cwd(profile_home) -> bool:+ """Whether a host directory can be the terminal cwd of a session bound to ``profile_home``: the local backend runs+ in it, docker mounts it at ``/workspace`` (``docker_mount_cwd_to_workspace``) or creates it (``docker run -w``),+ and a plugin backend declaring neither ``is_remote`` nor ``is_container`` runs on this host. ssh, modal, daytona,+ singularity, sprites and the other sandboxes run somewhere the host's directories do not exist."""+ backend = _bound_terminal_backend(profile_home)+ if backend in {"local", "docker"}:+ return True+ from tools.terminal_tool_config import _BUILTIN_BACKENDS+ if backend in _BUILTIN_BACKENDS:+ return False+ # An unknown or unloaded plugin is treated as remote: sending it a host path is the failure this guards.+ from agent.terminal_env_registry import provider_flag+ return not (provider_flag(backend, "is_remote", True) or provider_flag(backend, "is_container", True))def _is_hermes_owned_cwd(cwd: str, profile_home) -> bool:@@ -311,11 +341,12 @@ def _is_other_profiles_cwd(cwd: str, profile_home) -> bool: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), or a named profile's row holds another- profile's (the resume then lands in :func:`_profile_default_cwd` and re-persists it)."""+ """A session row's stored cwd as a resume may adopt it: empty when the row of a session whose terminal does not+ run in host directories (ssh, sandboxes) holds a path in Hermes's 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):+ if cwd and not _host_cwd_is_terminal_cwd(profile_home) and _is_hermes_owned_cwd(cwd, profile_home):return ""if cwd and _is_other_profiles_cwd(cwd, profile_home):return ""