The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): stop idle per-workspace persistent containers instead of leaving them running
Teknium6b1c09691aa4
diff --git a/tests/gateway/test_docker_session_workspace.py b/tests/gateway/test_docker_session_workspace.pyindex 5882cec313a..af82a8fc6e6 100644--- a/tests/gateway/test_docker_session_workspace.py+++ b/tests/gateway/test_docker_session_workspace.py@@ -186,3 +186,31 @@ def test_deleting_a_session_releases_its_workspace_binding(home, tmp_path):authority = SimpleNamespace(runner=SimpleNamespace(), sessions={}, profile_id='fixture', instance_id='i', epoch=1)retire_live_sessions(authority, ['local-a'])assert terminal_tool.resolve_task_overrides('local-a') == {}+++def test_idle_reaper_stops_workspace_containers_and_keeps_the_profile_one_running(monkeypatch):+ # Review (@kshitijk4poor W4): one RUNNING container per (profile, workspace), never reclaimed.+ import time+ from tools import terminal_tool, terminal_tool_lifecycle+ calls = []++ class Env:+ def __init__(self, name):+ self.name = name++ def cleanup(self):+ calls.append(('cleanup', self.name)) # persist mode: a no-op that leaves it running++ def stop_idle(self):+ calls.append(('stop', self.name))++ monkeypatch.setattr(terminal_tool, '_active_environments', {})+ monkeypatch.setattr(terminal_tool, '_last_activity', {})+ old = time.time() - 3600+ for key in ('default', 'default:ws:aaaa', 'profile:beta:ws:bbbb'):+ terminal_tool._active_environments[key] = Env(key)+ terminal_tool._last_activity[key] = old+ terminal_tool_lifecycle._cleanup_inactive_envs(lifetime_seconds=300)+ assert sorted(calls) == [('cleanup', 'default'), ('stop', 'default:ws:aaaa'),+ ('stop', 'profile:beta:ws:bbbb')]+ assert terminal_tool._active_environments == {}diff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex 4d9105f9129..2be3f39c6c3 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -204,6 +204,8 @@ def reap_orphan_containers(age = (now - finished_at).total_seconds()if age < max_age_seconds:continue+ if _is_idle_workspace_container(docker, cid):+ continue# No -f: a sibling may have restarted the container between the ps snapshot# and now (FinishedAt still reports the previous exit), and the daemon refuses# a plain rm on a running container, which is the atomic recheck this sweep needs.@@ -219,6 +221,18 @@ def reap_orphan_containers(return removed+def _is_idle_workspace_container(docker_exe: str, container_id: str) -> bool:+ """A persistent per-workspace container (task key ``<base>:ws:<digest>``, label ``<base>_ws_<digest>``)+ that the idle reaper STOPPED on purpose (``DockerEnvironment.stop_idle``): it is that workspace's+ sandbox, restarted on next use, not an orphan. Unknown (inspect failed) reads as not one."""+ result = _docker_query(+ [docker_exe, "inspect", "--format", '{{index .Config.Labels "hermes-task-id"}}', container_id], timeout=10,+ fail="orphan reaper docker inspect %s failed: %s", fail_args=(container_id[:12],))+ if result is None or result.returncode != 0:+ return False+ return re.search(r"_ws_[0-9a-f]{16}$", result.stdout.strip()) is not None++def _container_finished_at(docker_exe: str, container_id: str):"""``docker inspect`` FinishedAt as an aware datetime; ``None`` (= don't reap) whenmissing/unparseable or Docker's never-finished zero value ``0001-01-01T00:00:00Z``."""@@ -1304,6 +1318,31 @@ class DockerEnvironment(BaseEnvironment):if not self._persistent:self._remove_bind_dirs()+ def stop_idle(self) -> None:+ """Idle reclaim of a per-workspace persistent container (#140665): ``docker stop``, never+ ``rm``. Its writable layer and ``/root`` sandbox stay, and the next use in that workspace+ re-attaches through :meth:`_attach_existing_container`, which ``docker start``s a stopped+ container. Without this, persistent mode left one RUNNING container per workspace a user+ ever opened (each with its own ``container_memory``) until the process exited."""+ container_id = self._container_id+ if not container_id:+ return+ docker_exe, log_id = self._docker_exe, container_id[:12]++ def _do_stop() -> None:+ try:+ subprocess.run([docker_exe, "stop", "-t", "10", container_id], capture_output=True,+ timeout=30, stdin=subprocess.DEVNULL, check=False)+ except (subprocess.TimeoutExpired, OSError) as e:+ logger.warning("docker stop %s (idle workspace) failed: %s", log_id, e)++ t = threading.Thread(target=_do_stop, daemon=True, name=f"hermes-idle-stop-{log_id}")+ with _TEARDOWN_LOCK:+ _TEARDOWN_THREADS.add(t)+ t.start()+ self._cleanup_thread = t+ self._container_id = None+@staticmethoddef wait_for_all_teardowns(timeout: float = 15.0) -> bool:"""Join every in-flight teardown worker, including those of envs the idle reaper alreadydiff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.pyindex 59d3646f59e..9dfa3c10344 100644--- a/tools/terminal_tool_lifecycle.py+++ b/tools/terminal_tool_lifecycle.py@@ -102,11 +102,14 @@ def _cleanup_env(env: Any, *, force_remove: Optional[bool] = None) -> None:env.terminate()-def _teardown_env(env: Any, task_id: str, *, force_remove: Optional[bool] = None, done_msg: str = "Cleaned up inactive environment for task: %s") -> None:- """``_cleanup_env`` plus outcome logging. A 404/"not found" error means the- sandbox is already gone — logged at info."""+def _teardown_env(env: Any, task_id: str, *, force_remove: Optional[bool] = None, done_msg: str = "Cleaned up inactive environment for task: %s", stop_idle: bool = False) -> None:+ """``_cleanup_env`` (or, with *stop_idle*, the backend's ``stop_idle``) plus outcome logging.+ A 404/"not found" error means the sandbox is already gone — logged at info."""try:- _cleanup_env(env, force_remove=force_remove)+ if stop_idle:+ env.stop_idle()+ else:+ _cleanup_env(env, force_remove=force_remove)logger.info(done_msg, task_id)except Exception as e:error_str = str(e)@@ -154,7 +157,11 @@ def _cleanup_inactive_envs(lifetime_seconds: int = 300):try:from tools.process_registry import process_registryfor task_id in list(_last_activity.keys()):- if process_registry.has_active_processes(task_id):+ # A workspace container is keyed by its digest, not the spawning task id: also keep it+ # while any process it hosts is still running (stopping it would kill that process).+ if process_registry.has_active_processes(task_id) or (+ _is_workspace_key(task_id)+ and process_registry._any_running(lambda s, key=task_id: s.task_id == key)):_last_activity[task_id] = current_timeexcept ImportError:pass@@ -172,7 +179,17 @@ def _cleanup_inactive_envs(lifetime_seconds: int = 300):for task_id, env in envs_to_stop:if env is not None:_clear_file_ops_cache(task_id)- _teardown_env(env, task_id)+ if _is_workspace_key(task_id) and callable(getattr(env, "stop_idle", None)):+ # Persistent per-workspace container: stop it (state kept, restarted on next use)+ # instead of leaving it running forever like the one profile container.+ _teardown_env(env, task_id, stop_idle=True)+ else:+ _teardown_env(env, task_id)+++def _is_workspace_key(key: str) -> bool:+ """A persistent Docker key bound to one session workspace (``<base>:ws:<digest>``)."""+ return ":ws:" in str(key or "")def get_active_env(task_id: str):