The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(docker): keep unmounted Desktop sessions on the profile sandbox
Gille7750d1a1d23b
diff --git a/tests/gateway/test_docker_session_workspace.py b/tests/gateway/test_docker_session_workspace.pyindex fad26ffefd8..fea13b026eb 100644--- a/tests/gateway/test_docker_session_workspace.py+++ b/tests/gateway/test_docker_session_workspace.py@@ -38,14 +38,14 @@ def _policy(home, cwd, persistent, mount=True):return restore_policy(asdict(build_policy({'source': 'cli', 'cwd': str(cwd), 'model': 'm'}, {})))-def _turn(policy, session_id):+def _turn(policy, session_id, profile=''):"""The gateway turn's own scope: frozen policy, session key, and the turn's workspace binding."""from contextlib import ExitStackfrom gateway.session_context import clear_session_vars, set_session_varsfrom gateway.session_policy import bind_turn_workspace, policy_scopestack = ExitStack()stack.enter_context(policy_scope(policy))- tokens = set_session_vars(session_key=f'agent:main:local:dm:{session_id}')+ tokens = set_session_vars(session_key=f'agent:main:local:dm:{session_id}', profile=profile)stack.callback(clear_session_vars, tokens)bind_turn_workspace(policy, session_id)return stack@@ -81,6 +81,67 @@ def test_persistent_container_is_keyed_per_workspace_not_per_profile(home, tmp_passert plans['local-c'] == plans['local-a'][email protected]("mount", [False, True])[email protected]("profile", ["default", "beta"])+def test_desktop_workspace_registration_preserves_unmounted_profile_sandbox(+ home, tmp_path, monkeypatch, mount, profile+):+ from tools import terminal_tool+ from tui_gateway import server++ profile_home = home if profile == "default" else home / "profiles" / profile+ profile_home.mkdir(parents=True, exist_ok=True)+ monkeypatch.setenv("HERMES_HOME", str(profile_home))+ workspaces = [tmp_path / "first", tmp_path / "second"]+ plans = []+ for index, workspace in enumerate(workspaces):+ workspace.mkdir()+ sid = f"desktop-{index}"+ policy = _policy(profile_home, workspace, persistent=True, mount=mount)+ with _turn(policy, sid, profile):+ # Desktop registers its cwd independently of the gateway's host-mount binding.+ vars(server)["_register_session_cwd"](+ {+ "session_key": sid,+ "cwd": str(workspace),+ "explicit_cwd": True,+ "source": "desktop",+ }+ )+ overrides = terminal_tool.resolve_task_overrides(sid)+ assert overrides["cwd_source"] == ("session" if mount else "process")+ if not mount:+ assert overrides["cwd"] == ""+ terminal_tool.record_session_cwd(sid, "/workspace/subdir")+ vars(server)["_register_session_cwd"](+ {+ "session_key": sid,+ "cwd": str(workspace),+ "explicit_cwd": True,+ "source": "desktop",+ }+ )+ assert terminal_tool.get_session_cwd(sid) == "/workspace/subdir"+ plans.append(_plan(sid))+ assert (+ terminal_tool._resolve_container_task_id(plans[-1][0]) == plans[-1][0]+ )++ with _turn(policy, "cli-without-workspace", profile):+ terminal_tool.clear_task_env_overrides("cli-without-workspace")+ cli_key = _plan("cli-without-workspace")[0]++ if mount:+ assert plans[0][0] != plans[1][0]+ assert [plan[1] for plan in plans] == [+ str(workspace) for workspace in workspaces+ ]+ else:+ expected = "default" if profile == "default" else f"profile:{profile}"+ assert cli_key == expected+ assert plans == [(expected, None), (expected, None)]++def test_binding_keeps_a_cd_and_follows_a_workspace_move(home, tmp_path):from tools.terminal_tool import get_session_cwd, record_session_cwdws1, ws2 = tmp_path / 'ws1', tmp_path / 'ws2'diff --git a/tests/tools/test_docker_backend_real.py b/tests/tools/test_docker_backend_real.pyindex fdb5616c072..007a103847c 100644--- a/tests/tools/test_docker_backend_real.py+++ b/tests/tools/test_docker_backend_real.py@@ -153,3 +153,86 @@ def test_home_survives_a_container_replacement(docker_task):assert r["output"].strip() == "durable"second = _container_id(docker_task)assert second and second != first++[email protected]("mount", [False, True])+def test_desktop_workspace_selection_and_recreation(+ docker_task, tmp_path, monkeypatch, mount+):+ """Desktop shares CLI's original sandbox unless a host workspace is actually selected for mounting."""+ from gateway.session_context import clear_session_vars, set_session_vars+ from tools import terminal_tool+ from tools.file_tools import read_file_tool+ from tools.terminal_tool_lifecycle import cleanup_vm+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope+ from tui_gateway import server++ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "true")+ monkeypatch.setenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false")+ monkeypatch.setenv("TERMINAL_SANDBOX_DIR", str(tmp_path / "sandboxes"))+ assert (+ _run("printf original > /workspace/identity.txt", docker_task)["exit_code"] == 0+ )+ original = _container_id(docker_task)+ assert original+ containers = []+ for index in range(2):+ workspace = tmp_path / f"project-{index}"+ workspace.mkdir()+ (workspace / "identity.txt").write_text(f"project-{index}", encoding="utf-8")+ sid = f"{docker_task}-desktop-{index}"+ tokens = set_session_vars(session_key=sid)+ # The gateway freezes the selected host workspace into the turn's terminal policy.+ terminal = {+ name: value+ for name, value in os.environ.items()+ if name.startswith("TERMINAL_")+ }+ terminal["TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"] = str(mount).lower()+ terminal["TERMINAL_CWD"] = str(workspace) if mount else "/root"+ scope_token = set_terminal_scope(terminal)+ key = None+ try:+ vars(server)["_register_session_cwd"](+ {+ "session_key": sid,+ "cwd": str(workspace),+ "explicit_cwd": True,+ "source": "desktop",+ }+ )+ assert terminal_tool.resolve_task_overrides(sid)["cwd_source"] == (+ "session" if mount else "process"+ )+ key = _env_key(sid)+ expected = f"project-{index}" if mount else "original"+ for _ in range(2):+ result = _run("cat /workspace/identity.txt", sid)+ assert (+ result["exit_code"] == 0 and result["output"].strip() == expected+ ), result+ read = json.loads(+ read_file_tool("/workspace/identity.txt", task_id=sid)+ )+ assert expected in read.get("content", ""), read+ cid = _container_id(sid)+ assert cid+ containers.append(cid)+ if not mount:+ assert key == "default"+ _teardown(sid)+ finally:+ if key is not None:+ cleanup_vm(key, force_remove=True)+ terminal_tool.clear_task_env_overrides(sid)+ reset_terminal_scope(scope_token)+ clear_session_vars(tokens)+ if mount:+ assert original not in containers+ else:+ assert containers[0] == original+ assert len(set(containers)) == len(containers)+ # Neither Desktop workspace nor recreating its container moves/deletes CLI's files.+ assert (+ _run("cat /workspace/identity.txt", docker_task)["output"].strip() == "original"+ )diff --git a/tests/tui_gateway/test_unmounted_docker_cwd.py b/tests/tui_gateway/test_unmounted_docker_cwd.pynew file mode 100644index 00000000000..20003f4e54a--- /dev/null+++ b/tests/tui_gateway/test_unmounted_docker_cwd.py@@ -0,0 +1,102 @@+"""Desktop host cwd must not replace an unmounted Docker profile's execution cwd."""++import json+import os++import pytest++[email protected]("mount", [False, True])+def test_registration_uses_the_target_profiles_mount_policy(+ tmp_path, monkeypatch, mount+):+ import hermes_constants as hc+ from tools import terminal_tool+ from tools.terminal_scope import (+ install_and_reset_profile_terminal_scope,+ terminal_env,+ )+ from tui_gateway import server++ home = tmp_path / "home"+ profile = home / "profiles" / "beta"+ profile.mkdir(parents=True)+ workspace = tmp_path / "host-project"+ workspace.mkdir()+ (profile / "config.yaml").write_text(+ json.dumps(+ {+ "terminal": {+ "backend": "docker",+ "cwd": "/workspace",+ "docker_mount_cwd_to_workspace": mount,+ }+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("TERMINAL_ENV", "local")+ monkeypatch.setenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", str(not mount).lower())+ before = dict(os.environ)+ session = {+ "session_key": "profile-cwd",+ "cwd": str(workspace),+ "explicit_cwd": True,+ "source": "desktop",+ "profile_home": str(profile),+ }+ vars(server)["_register_session_cwd"](session)++ token = hc.set_hermes_home_override(str(profile))+ try:+ overrides = terminal_tool.resolve_task_overrides("profile-cwd")+ assert overrides == {+ "cwd": str(workspace) if mount else "",+ "cwd_source": "session" if mount else "process",+ }+ if not mount:+ with install_and_reset_profile_terminal_scope(profile):+ assert terminal_env("TERMINAL_CWD") == "/workspace"+ finally:+ terminal_tool.clear_task_env_overrides("profile-cwd")+ hc.reset_hermes_home_override(token)+ assert session["cwd"] == str(workspace)+ assert os.environ == before++[email protected]("posix")+def test_unmounted_registration_preserves_configured_container_cwd(tmp_path):+ from tools import terminal_tool+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope+ from tui_gateway import server++ token = set_terminal_scope(+ {+ "TERMINAL_ENV": "docker",+ "TERMINAL_CWD": "/work",+ "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE": "false",+ }+ )+ try:+ vars(server)["_register_session_cwd"](+ {+ "session_key": "configured-cwd",+ "cwd": str(tmp_path),+ "explicit_cwd": True,+ }+ )+ config = terminal_tool._get_env_config()+ assert config["cwd"] == "/work"+ assert (+ terminal_tool._resolve_command_cwd(+ workdir=None,+ default_cwd=config["cwd"],+ session_key="configured-cwd",+ env_type="docker",+ )+ == "/work"+ )+ finally:+ terminal_tool.clear_task_env_overrides("configured-cwd")+ reset_terminal_scope(token)diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex b3cd0ada3b9..44ce3fd5804 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -565,7 +565,9 @@ def _workspace_container_key(base: str, task_id: Optional[str]) -> str:followed: the child runs in its parent's workspace container, never the profile's.Reads the raw table (not :func:`resolve_task_overrides`, which calls back into key resolution)."""- if not task_id:+ # Desktop/ACP also register a cwd when no host folder is mounted. That cwd must+ # not split the profile's persistent sandbox away from its existing CLI files.+ if not task_id or not _tenv_bool("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false"):return baseif task_id.startswith(f"{base}:ws:"):return task_iddiff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.pyindex c0cf3d46e87..1d28622520f 100644--- a/tui_gateway/session_workdir.py+++ b/tui_gateway/session_workdir.py@@ -510,18 +510,25 @@ def _register_session_cwd(session: dict | None) -> None:if hints is not None and hasattr(hints, "rebind_working_dir"):hints.rebind_working_dir(str(session.get("cwd")))with contextlib.suppress(Exception):- from tools.terminal_tool import register_task_env_overrides+ from tools.terminal_tool import _get_env_config, register_task_env_overridescwd, cwd_source = _terminal_task_cwd_with_source(session)# The cwd/override record is keyed by the ROUTED home (#123989). session.create is a plain# @method, so bind the session's own profile home here or the record lands under the raw key# and the scoped turn (`profile:<p>:<key>`) misses it until the first `cd`. Callers already# inside the session's scope (the turn) bind nothing: the routed home is theirs already.import hermes_constants as hc+ from tools.terminal_scope import install_and_reset_profile_terminal_scopewith contextlib.ExitStack() as stack:profile_home = session.get("profile_home")if profile_home and hc.hermes_home_key(hc.get_hermes_home()) != hc.hermes_home_key(profile_home):stack.callback(hc.reset_hermes_home_override, hc.set_hermes_home_override(str(profile_home)))+ stack.enter_context(install_and_reset_profile_terminal_scope(profile_home))+ terminal = _get_env_config()+ if terminal["env_type"] == "docker" and not terminal["docker_mount_cwd_to_workspace"]:+ # The Desktop workspace is host context, not a directory in this sandbox.+ # An empty override leaves its configured cwd and subsequent in-container cd intact.+ cwd, cwd_source = "", "process"register_task_env_overrides(session["session_key"], {"cwd": cwd, "cwd_source": cwd_source})diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 889057dc257..1318c3fc2e9 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -367,7 +367,9 @@ The agent has the same filesystem access as your user account. Use `hermes toolsRuns commands inside a Docker container with security hardening (all capabilities dropped, no privilege escalation, PID limits).-**Single persistent container, shared across Hermes processes.** Hermes starts ONE long-lived container on first use and routes every terminal, file, and `execute_code` call through `docker exec` into that same container — across sessions, `/new`, `/reset`, and `delegate_task` subagents. Working-directory changes, installed packages, files in `/workspace`, and **background processes** all carry over from one tool call to the next, and from one Hermes process to the next. When you close a TUI session, run `/quit`, or start a new `hermes` invocation, the container keeps running and the next Hermes process reuses it via a labeled lookup. See **Container lifecycle** below for the exact teardown rules.+**Persistent containers, shared across Hermes processes.** With `container_persistent: true` and `docker_mount_cwd_to_workspace: false` (the defaults), sessions in the same profile share its original sandbox. Selecting a working directory in Desktop does not create a separate workspace sandbox in this mode, so CLI and Desktop keep access to the same files. With host-workspace mounting enabled, persistent containers are instead keyed by profile and selected workspace: sessions in the same workspace share a container, while different workspaces stay separate. `delegate_task` subagents use their parent's container.++Terminal, file, and `execute_code` calls use `docker exec` in the selected container. Installed packages, files in `/workspace`, and **background processes** carry over between calls and Hermes processes using that container. Closing a TUI session, running `/quit`, or starting a new `hermes` invocation does not itself remove it; the next process can reuse it through its labels. See **Container lifecycle** below for the exact teardown rules.**Per-session isolation mode (`container_persistent: false`).** Setting `container_persistent: false` on the Docker backend switches to one container **per session**: every chat (desktop app session, gateway conversation, TUI session) gets its own fresh sandbox, created on its first terminal/file call and removed when the session closes or goes idle past `lifetime_seconds`. Nothing carries over between sessions — no filesystem state, no mounts, no background processes. With `docker_mount_cwd_to_workspace: true`, only the workspace **attached to that session** is mounted at `/workspace`; a fresh session with no attached directory gets an empty workspace instead of inheriting the previous session's mount. `delegate_task` subagents still share their parent session's container. Use this mode when the sandbox is a security boundary between conversations; keep the default `true` when you want the long-lived shared container described above.