The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): keep a container backend's terminal.cwd as the session workspace
Austin Pickettbf84561b9d41
diff --git a/tests/tools/test_credential_files.py b/tests/tools/test_credential_files.pyindex 26928f18eb3..63bb3854a15 100644--- a/tests/tools/test_credential_files.py+++ b/tests/tools/test_credential_files.py@@ -552,6 +552,24 @@ class TestToAgentVisiblePathPerBackend:from tools.credential_files import to_agent_visible_cache_pathassert to_agent_visible_cache_path("/etc/hosts") == "/etc/hosts"+ def test_symlinked_home_maps_resolved_path(self, tmp_path, monkeypatch):+ """#103147: ``@file:`` expansion resolves the staged path, but the mount roots+ keep HERMES_HOME's symlinked spelling; the resolved path must still map."""+ real_home = tmp_path / "real-hermes"+ (real_home / "attachments").mkdir(parents=True)+ link_home = tmp_path / ".hermes"+ link_home.symlink_to(real_home, target_is_directory=True)+ monkeypatch.setenv("HERMES_HOME", str(link_home))+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ staged = link_home / "attachments" / "paste.txt"+ staged.write_text("x", encoding="utf-8")+ from tools.credential_files import to_agent_visible_cache_path+ assert to_agent_visible_cache_path(str(staged.resolve())) == "/root/.hermes/attachments/paste.txt"+ assert to_agent_visible_cache_path(str(staged)) == "/root/.hermes/attachments/paste.txt"+ # A sibling outside the mounted dirs still passes through.+ outside = real_home / "notes.txt"+ assert to_agent_visible_cache_path(str(outside)) == str(outside)+class TestIterCacheFiles:"""Tests for iter_cache_files()."""diff --git a/tests/tui_gateway/test_container_backend_workdir.py b/tests/tui_gateway/test_container_backend_workdir.pynew file mode 100644index 00000000000..d7590653c01--- /dev/null+++ b/tests/tui_gateway/test_container_backend_workdir.py@@ -0,0 +1,113 @@+"""#103147: a container backend's ``terminal.cwd`` (docker ``/workspace``) lives inside the sandbox.++The gateway used to host-validate it with ``os.path.isdir``, fail, and fall back to its own launch+directory ($HOME for the desktop). Every host file then looked "inside the workspace", so+``file.attach`` skipped staging into the bind-mounted ``attachments/`` dir and the agent was handed a+host path that does not exist in the container.+"""++import os+import uuid+from pathlib import Path++import pytest++from agent.context_references import preprocess_context_references+from tui_gateway import server+++def _container_dir() -> str:+ path = f"/hermes-test-workspace-{uuid.uuid4().hex[:8]}"+ assert not os.path.isdir(path)+ return path+++def _write_cfg(home: Path, body: str) -> Path:+ home.mkdir(parents=True, exist_ok=True)+ (home / "config.yaml").write_text(body, encoding="utf-8")+ return home+++def launch_home(tmp_path, monkeypatch):+ """A temp launch HERMES_HOME the gateway and the cache-mount mapper both read."""+ home = tmp_path / "hermes-home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(server, "_hermes_home", home)+ monkeypatch.delenv("TERMINAL_ENV", raising=False)+ monkeypatch.delenv("TERMINAL_CWD", raising=False)+ # The desktop's gateway runs from the user's home: a host dir holding the user's files.+ launch_dir = tmp_path / "user-home"+ launch_dir.mkdir()+ monkeypatch.chdir(launch_dir)+ return home++[email protected]("bridged", [False, True], ids=["config-only", "env-bridged"])+def test_container_cwd_is_the_session_workspace(launch_home, monkeypatch, bridged):+ container = _container_dir()+ if bridged: # launchers bridge terminal.* into TERMINAL_ENV / TERMINAL_CWD+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_CWD", container)+ else: # in-process desktop gateway: only config.yaml says docker+ _write_cfg(launch_home, f"terminal:\n backend: docker\n cwd: {container}\n")++ assert server._completion_cwd({}) == container+ # Same answer the terminal tool already gets.+ assert server._terminal_task_cwd(None) == container+ session = {"cwd": server._completion_cwd({}), "profile_home": None}+ assert not server._session_is_local_backend(session)+ # Never "healed" to the nearest host ancestor (``/``).+ assert server._display_session_cwd(session) == container+++def test_local_backend_missing_cwd_still_falls_back(launch_home):+ _write_cfg(launch_home, f"terminal:\n backend: local\n cwd: {_container_dir()}\n")+ assert server._completion_cwd({}) == os.getcwd()+++def test_container_backend_host_cwd_keeps_host_path(launch_home, tmp_path):+ """A host dir (the ``docker_mount_cwd_to_workspace`` source) is still validated and kept."""+ project = tmp_path / "project"+ project.mkdir()+ _write_cfg(launch_home, f"terminal:\n backend: docker\n cwd: {project}\n")+ assert server._completion_cwd({}) == str(project)+++def test_named_container_profile_uses_its_container_cwd(launch_home, tmp_path, monkeypatch):+ container = _container_dir()+ profile = _write_cfg(tmp_path / "box", f"terminal:\n backend: docker\n cwd: {container}\n")+ monkeypatch.setattr(server, "_profile_home", lambda name: profile if name == "box" else None)+ inherited = str(tmp_path / "user-home")++ assert server._completion_cwd({"profile": "box", "cwd": inherited, "cwd_explicit": False}) == container+ assert server._completion_cwd({"profile": "box"}) == container+ assert not server._session_is_local_backend({"cwd": container, "profile_home": str(profile)})+++def test_attached_host_file_is_staged_and_agent_sees_container_path(launch_home, monkeypatch):+ container = _container_dir()+ _write_cfg(launch_home, f"terminal:\n backend: docker\n cwd: {container}\n")+ report = Path.cwd() / "Downloads" / "report.pdf"+ report.parent.mkdir()+ report.write_bytes(b"%PDF-1.4\x00\x01binary")+ session = {"cwd": server._completion_cwd({}), "profile_home": None}++ stored, uploaded = server._stage_session_file_attachment(+ session, raw_path=str(report), data_url="", name="")++ assert uploaded is True+ assert stored.parent == (launch_home / "attachments").resolve()+ assert stored.read_bytes() == report.read_bytes()+ ref_path = server._attachment_ref_path(session, stored)+ assert ref_path == str(stored) # absolute, never relative to the host launch dir++ # The turn expands the ref against the session cwd; the agent gets the mounted path.+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ cwd = server._session_cwd(session)+ ctx = preprocess_context_references(+ f"summarise @file:{server._format_ref_value(ref_path)}", cwd=cwd, allowed_root=cwd,+ context_length=200_000)+ assert not ctx.warnings, ctx.warnings+ assert f"available on disk at `/root/.hermes/attachments/{stored.name}`" in ctx.messagediff --git a/tools/credential_files.py b/tools/credential_files.pyindex fc9881b8d17..89872fff05d 100644--- a/tools/credential_files.py+++ b/tools/credential_files.py@@ -306,8 +306,26 @@ def _remap_cache_path(path: str, container_base: str, src: str, dst: str, join:def map_cache_path_to_container(host_path: str, container_base: str = "/root/.hermes") -> Optional[str]:- """POSIX container path for a host path under an auto-mounted cache dir, else None."""- return _remap_cache_path(host_path, container_base, "host_path", "container_path", lambda root, rel: posixpath.join(root, rel.as_posix()))+ """POSIX container path for a host path under an auto-mounted cache dir, else None.++ Also matches through symlinks: ``@file:`` expansion hands over RESOLVED paths while the mount roots keep+ HERMES_HOME's configured spelling, so a symlinked home (``~/.hermes`` -> dotfiles, macOS ``/var`` ->+ ``/private/var``) left a staged attachment's host path in front of the sandboxed agent (#103147)."""+ def join(root: str, rel: Path) -> str:+ return posixpath.join(root, rel.as_posix())++ mapped = _remap_cache_path(host_path, container_base, "host_path", "container_path", join)+ if mapped is not None:+ return mapped+ try:+ real = Path(host_path).resolve()+ for mount in get_cache_directory_mounts(container_base=container_base):+ root = Path(mount["host_path"]).resolve()+ if real.is_relative_to(root):+ return join(mount["container_path"], real.relative_to(root))+ except (OSError, RuntimeError):+ pass+ return Nonedef from_agent_visible_cache_path(container_path: str, container_base: str = "/root/.hermes") -> str:diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex 956b7a60632..2afacb0c863 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -48,7 +48,7 @@ def _completion_cwd(params: dict | None = None) -> str:raw = str(client_cwd or session_cwd or _profile_workspace_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 _launch_configured_cwd()- or os.environ.get("TERMINAL_CWD") or os.getcwd())+ 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.if named_ssh:@@ -61,6 +61,11 @@ def _completion_cwd(params: dict | None = None) -> str:return resolvedif profile_home is None and _is_remote_cwd_shape(raw) and _cwd_is_remote(None):return raw+ # A container backend's cwd (docker ``/workspace``) lives inside the sandbox, like ``_terminal_task_cwd``'s: the+ # host has no such dir. Falling back to the gateway's own cwd ($HOME for the desktop) made every host file look+ # "inside the workspace", so attachments were never staged into the mounted dir (#103147).+ if _is_container_path(raw) and _bound_terminal_backend(profile_home) != "local":+ return rawreturn os.getcwd()@@ -122,9 +127,32 @@ def _is_remote_cwd_shape(raw: str) -> bool:return _is_ssh_remote_tilde_cwd("ssh", raw) or os.path.isabs(raw)+def _is_container_path(raw: str) -> bool:+ """An absolute POSIX path, the only shape a container backend's working directory takes."""+ return raw.startswith("/") and not raw.startswith("//")+++def _sandbox_workspace_cwd(profile_home) -> str | None:+ """A container backend's configured ``terminal.cwd`` (docker ``/workspace``), unchecked against this host.++ ``_profile_configured_cwd``/``_launch_configured_cwd`` require ``os.path.isdir``, which a path inside the+ sandbox fails. Only a path missing on the host qualifies: an existing host dir keeps the host path (it is the+ ``docker_mount_cwd_to_workspace`` source). ssh has its own remote-cwd rules above."""+ if profile_home:+ policy = _profile_terminal_policy(profile_home)+ backend, raw = _policy_backend(policy), str(policy.get("TERMINAL_CWD") or "").strip()+ else:+ backend = _effective_terminal_backend()+ raw = os.environ.get("TERMINAL_CWD", "").strip() or _workdir_terminal_cfg("cwd")+ if backend in {"local", "ssh"} or not _is_container_path(raw) or os.path.isdir(raw):+ return None+ return raw++def _profile_workspace_cwd(profile_home) -> str | None:- """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)+ """A named profile's configured workspace: an ssh profile's remote dir, a host dir, else a container dir."""+ return (_declared_remote_profile_cwd(profile_home) or _profile_configured_cwd(profile_home)+ or (_sandbox_workspace_cwd(profile_home) if profile_home else None))def _workspace_cwd(profile_home, raw: str) -> str:@@ -222,11 +250,11 @@ def _session_is_local_backend(session: dict | None) -> bool:whatever the launch process runs (one multiplexed gateway serves many profiles), and a per-profile gateway(``hermes -p x``) may set ``terminal.backend: ssh`` in config without ``TERMINAL_ENV``: an env-only check wouldheal a live remote cwd to its nearest host ancestor (``/home``) and persist that."""- if session and session.get("profile_home") and _cwd_is_remote(session["profile_home"]):+ if session and session.get("profile_home") and _bound_terminal_backend(session["profile_home"]) != "local":return False- # Otherwise 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"+ # Otherwise the launch backend, env or config: an in-process gateway (no TERMINAL_ENV bridge) under+ # ``terminal.backend: docker`` holds a container cwd (``/workspace``) that healing would walk up to ``/``.+ return _effective_terminal_backend() == "local"def _effective_terminal_backend() -> str: