From eae3515108967ade8a6a2a2266a7ab874d8e26b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 02:23:30 +0000 Subject: [PATCH 1/2] fix(agent-server): remove the per-server TMUX_TMPDIR on shutdown When TMUX_TMPDIR is unset (or too long for a tmux socket path), the server creates /openhands-agent-server- for itself, but the lifespan shutdown only restored the environment variable, so every such start left a directory behind. Remove that directory at shutdown when this process created it; a user-provided TMUX_TMPDIR is never touched. Drops the known-bug marker from the F31.tmux-dir-cleanup map bullet. Fixes #5932 Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_014MKndVj7XWvRQmvW9w2bDg --- .../feature-map/F31-persistence-and-limits.md | 12 ++-- .../openhands/agent_server/api.py | 31 ++++++--- tests/agent_server/test_api.py | 67 ++++++++++++++++++- 3 files changed, 90 insertions(+), 20 deletions(-) diff --git a/.agents/skills/verify-agent-server/references/feature-map/F31-persistence-and-limits.md b/.agents/skills/verify-agent-server/references/feature-map/F31-persistence-and-limits.md index 6bb35771601..0c6d4fecbf7 100644 --- a/.agents/skills/verify-agent-server/references/feature-map/F31-persistence-and-limits.md +++ b/.agents/skills/verify-agent-server/references/feature-map/F31-persistence-and-limits.md @@ -661,7 +661,7 @@ Preconditions: file stops startup with pydantic's `literal_error`, as a non-numeric integer variable does (`F31.config-invalid-fails-fast`): only the environment parser is lenient for booleans and choices. -- **Per-process tmux directory removed on stop (`F31.tmux-dir-cleanup`), known bug.** +- **Per-process tmux directory removed on stop (`F31.tmux-dir-cleanup`).** A second run whose `TMUX_TMPDIR` is empty, so the server picks its own. ```sh B=$(control-agent-server launch --new --name f31-tmux --env TMUX_TMPDIR= --print-run) @@ -672,17 +672,17 @@ Preconditions: test -d "$TD" control-agent-server stop --run "$B" | jq -e '.server == "terminated"' trap 'rm -rf -- "$TD" || true' EXIT - control-agent-server assert --value "$([ -e "$TD" ] && echo true || echo false)" --check . eq false # bug: value eq true + control-agent-server assert --value "$([ -e "$TD" ] && echo true || echo false)" --check . eq false trap - EXIT ``` Expected: the directory is gone after a graceful stop (`stop` reports `terminated`, not `killed`, so the lifespan shutdown ran). The log line and the directory existing while `B` runs are the positive controls. - Today the server logs `TMUX_TMPDIR not set; defaulting to per-server tmux + The server logs `TMUX_TMPDIR not set; defaulting to per-server tmux directory /tmp/openhands-agent-server-`, creates it, and at shutdown - only removes the variable from its environment (`api_lifespan`), so every - such start leaves a directory in the temp dir and the `assert` fails. The - `trap` removes the leftover after the assertion. + (`api_lifespan`) restores the variable and removes that directory. A + `TMUX_TMPDIR` the user provided is kept and never removed. The `trap` + removes a leftover if the assertion fails. - **Storage retention and disk budget (`F31.storage-retention`), blocked.** Needs a Docker daemon and the `conversation_image` pulled (`control-agent-server capabilities` reports `docker`): the storage diff --git a/openhands-agent-server/openhands/agent_server/api.py b/openhands-agent-server/openhands/agent_server/api.py index 247b7fdfbe3..3d5d28d3081 100644 --- a/openhands-agent-server/openhands/agent_server/api.py +++ b/openhands-agent-server/openhands/agent_server/api.py @@ -1,5 +1,6 @@ import asyncio import os +import shutil import sys import tempfile import traceback @@ -140,12 +141,15 @@ def _default_server_tmux_tmpdir() -> Path: return _SHORT_TMUX_TMPDIR_ROOT / name -def _ensure_server_tmux_tmpdir() -> tuple[Path, bool]: +def _ensure_server_tmux_tmpdir() -> tuple[Path, bool, bool]: + """Return the tmux directory, whether it was defaulted, and whether this + call created it (only then is it removed at shutdown).""" existing = os.getenv("TMUX_TMPDIR") if existing and _fits_tmux_socket(Path(existing)): - return Path(existing), False + return Path(existing), False, False tmux_tmpdir = _default_server_tmux_tmpdir() + created = not tmux_tmpdir.exists() tmux_tmpdir.mkdir(parents=True, exist_ok=True) os.environ["TMUX_TMPDIR"] = str(tmux_tmpdir) if existing: @@ -160,7 +164,7 @@ def _ensure_server_tmux_tmpdir() -> tuple[Path, bool]: "TMUX_TMPDIR not set; defaulting to per-server tmux directory %s", tmux_tmpdir, ) - return tmux_tmpdir, True + return tmux_tmpdir, True, created def _cleanup_stale_tmux_sessions() -> None: @@ -189,7 +193,9 @@ def _cleanup_stale_tmux_sessions() -> None: @asynccontextmanager async def api_lifespan(api: FastAPI) -> AsyncIterator[None]: original_tmux_tmpdir = os.environ.get("TMUX_TMPDIR") - tmux_tmpdir, tmux_tmpdir_was_defaulted = _ensure_server_tmux_tmpdir() + tmux_tmpdir, tmux_tmpdir_was_defaulted, tmux_tmpdir_was_created = ( + _ensure_server_tmux_tmpdir() + ) secret_resolution: local_secret_resolution | None = None try: # Clean up stale tmux sessions from previous server runs @@ -348,13 +354,16 @@ async def stop_tool_preload_service(): emit_server_stopped() await shutdown_telemetry_sink() - if tmux_tmpdir_was_defaulted and os.environ.get("TMUX_TMPDIR") == str( - tmux_tmpdir - ): - if original_tmux_tmpdir is None: - os.environ.pop("TMUX_TMPDIR", None) - else: - os.environ["TMUX_TMPDIR"] = original_tmux_tmpdir + if tmux_tmpdir_was_defaulted: + if os.environ.get("TMUX_TMPDIR") == str(tmux_tmpdir): + if original_tmux_tmpdir is None: + os.environ.pop("TMUX_TMPDIR", None) + else: + os.environ["TMUX_TMPDIR"] = original_tmux_tmpdir + if tmux_tmpdir_was_created: + # Only the per-server directory this process created; a + # user-provided TMUX_TMPDIR is never removed. + shutil.rmtree(tmux_tmpdir, ignore_errors=True) def _emit_request_failed(request: Request, exc: Exception, error_id: str) -> None: diff --git a/tests/agent_server/test_api.py b/tests/agent_server/test_api.py index 4e24a27a585..832fbda0676 100644 --- a/tests/agent_server/test_api.py +++ b/tests/agent_server/test_api.py @@ -112,9 +112,10 @@ def test_ensure_server_tmux_tmpdir_creates_default_dir(short_tmp_path, monkeypat "openhands.agent_server.api._default_server_tmux_tmpdir", lambda: expected ) - tmux_tmpdir, was_defaulted = _ensure_server_tmux_tmpdir() + tmux_tmpdir, was_defaulted, created = _ensure_server_tmux_tmpdir() assert was_defaulted is True + assert created is True assert tmux_tmpdir == expected assert tmux_tmpdir.is_dir() assert os.environ["TMUX_TMPDIR"] == str(tmux_tmpdir) @@ -124,9 +125,10 @@ def test_ensure_server_tmux_tmpdir_respects_existing_env(short_tmp_path, monkeyp existing = short_tmp_path / "custom-tmux" monkeypatch.setenv("TMUX_TMPDIR", str(existing)) - tmux_tmpdir, was_defaulted = _ensure_server_tmux_tmpdir() + tmux_tmpdir, was_defaulted, created = _ensure_server_tmux_tmpdir() assert was_defaulted is False + assert created is False assert tmux_tmpdir == existing assert not existing.exists() @@ -142,7 +144,7 @@ def test_ensure_server_tmux_tmpdir_replaces_too_deep_env( "openhands.agent_server.api._default_server_tmux_tmpdir", lambda: expected ) - tmux_tmpdir, was_defaulted = _ensure_server_tmux_tmpdir() + tmux_tmpdir, was_defaulted, created = _ensure_server_tmux_tmpdir() assert was_defaulted is True assert tmux_tmpdir == expected @@ -562,8 +564,67 @@ async def test_lifespan_defaults_and_restores_tmux_tmpdir( mock_app.state = SimpleNamespace(config=Config()) async with api_lifespan(mock_app): assert os.environ["TMUX_TMPDIR"] == str(expected_tmux_tmpdir) + assert expected_tmux_tmpdir.is_dir() assert "TMUX_TMPDIR" not in os.environ + assert not expected_tmux_tmpdir.exists() + + async def test_lifespan_keeps_user_provided_tmux_tmpdir( + self, short_tmp_path, monkeypatch + ): + """A TMUX_TMPDIR the user set is never removed at shutdown.""" + user_tmux_tmpdir = short_tmp_path / "user-tmux" + user_tmux_tmpdir.mkdir() + monkeypatch.setenv("TMUX_TMPDIR", str(user_tmux_tmpdir)) + mock_conversation_service = AsyncMock() + + with ( + patch( + "openhands.agent_server.api.get_default_conversation_service", + return_value=mock_conversation_service, + ), + patch("openhands.agent_server.api.get_vscode_service", return_value=None), + patch( + "openhands.agent_server.api.get_tool_preload_service", return_value=None + ), + ): + mock_app = AsyncMock() + mock_app.state = SimpleNamespace(config=Config()) + async with api_lifespan(mock_app): + assert os.environ["TMUX_TMPDIR"] == str(user_tmux_tmpdir) + + assert os.environ["TMUX_TMPDIR"] == str(user_tmux_tmpdir) + assert user_tmux_tmpdir.is_dir() + + async def test_lifespan_keeps_preexisting_default_tmux_tmpdir( + self, short_tmp_path, monkeypatch + ): + """A default directory that existed before startup is not removed.""" + expected_tmux_tmpdir = short_tmp_path / "tmux" + expected_tmux_tmpdir.mkdir() + monkeypatch.setattr( + "openhands.agent_server.api._default_server_tmux_tmpdir", + lambda: expected_tmux_tmpdir, + ) + mock_conversation_service = AsyncMock() + + with ( + patch( + "openhands.agent_server.api.get_default_conversation_service", + return_value=mock_conversation_service, + ), + patch("openhands.agent_server.api.get_vscode_service", return_value=None), + patch( + "openhands.agent_server.api.get_tool_preload_service", return_value=None + ), + ): + mock_app = AsyncMock() + mock_app.state = SimpleNamespace(config=Config()) + async with api_lifespan(mock_app): + assert os.environ["TMUX_TMPDIR"] == str(expected_tmux_tmpdir) + + assert "TMUX_TMPDIR" not in os.environ + assert expected_tmux_tmpdir.is_dir() class TestRootPath: From 4cecf3a490f0435be85a25ab2786ab536e529952 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 02:51:16 +0000 Subject: [PATCH 2/2] fix(agent-server): log a failed tmux directory removal at shutdown Address the issue triage: removal stays best-effort but a failure is now logged instead of silently ignored, and tests cover the too-long TMUX_TMPDIR fallback (user value restored and kept, substitute removed) and the failure path. Fixes #5932 Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_014MKndVj7XWvRQmvW9w2bDg --- .../openhands/agent_server/api.py | 9 ++- tests/agent_server/test_api.py | 74 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/openhands-agent-server/openhands/agent_server/api.py b/openhands-agent-server/openhands/agent_server/api.py index 3d5d28d3081..d8ee2d7625d 100644 --- a/openhands-agent-server/openhands/agent_server/api.py +++ b/openhands-agent-server/openhands/agent_server/api.py @@ -363,7 +363,14 @@ async def stop_tool_preload_service(): if tmux_tmpdir_was_created: # Only the per-server directory this process created; a # user-provided TMUX_TMPDIR is never removed. - shutil.rmtree(tmux_tmpdir, ignore_errors=True) + try: + shutil.rmtree(tmux_tmpdir) + except OSError as e: + logger.warning( + "Failed to remove per-server tmux directory %s: %s", + tmux_tmpdir, + e, + ) def _emit_request_failed(request: Request, exc: Exception, error_id: str) -> None: diff --git a/tests/agent_server/test_api.py b/tests/agent_server/test_api.py index 832fbda0676..ecda9231272 100644 --- a/tests/agent_server/test_api.py +++ b/tests/agent_server/test_api.py @@ -596,6 +596,80 @@ async def test_lifespan_keeps_user_provided_tmux_tmpdir( assert os.environ["TMUX_TMPDIR"] == str(user_tmux_tmpdir) assert user_tmux_tmpdir.is_dir() + async def test_lifespan_removes_substitute_for_too_deep_tmux_tmpdir( + self, deep_tmp_path, short_tmp_path, monkeypatch + ): + """A too-long TMUX_TMPDIR is restored and kept; the substitute removed.""" + monkeypatch.setenv("TMUX_TMPDIR", str(deep_tmp_path)) + substitute = short_tmp_path / "tmux" + monkeypatch.setattr( + "openhands.agent_server.api._default_server_tmux_tmpdir", + lambda: substitute, + ) + monkeypatch.setattr( + "openhands.agent_server.api._fits_tmux_socket", + lambda path: path == substitute, + ) + mock_conversation_service = AsyncMock() + + with ( + patch( + "openhands.agent_server.api.get_default_conversation_service", + return_value=mock_conversation_service, + ), + patch("openhands.agent_server.api.get_vscode_service", return_value=None), + patch( + "openhands.agent_server.api.get_tool_preload_service", return_value=None + ), + ): + mock_app = AsyncMock() + mock_app.state = SimpleNamespace(config=Config()) + async with api_lifespan(mock_app): + assert os.environ["TMUX_TMPDIR"] == str(substitute) + + assert os.environ["TMUX_TMPDIR"] == str(deep_tmp_path) + assert deep_tmp_path.is_dir() + assert not substitute.exists() + + async def test_lifespan_logs_and_continues_when_tmux_tmpdir_removal_fails( + self, short_tmp_path, monkeypatch, caplog + ): + """A failed removal is logged and does not abort shutdown.""" + expected_tmux_tmpdir = short_tmp_path / "tmux" + monkeypatch.setattr( + "openhands.agent_server.api._default_server_tmux_tmpdir", + lambda: expected_tmux_tmpdir, + ) + + def fail_rmtree(path): + raise PermissionError("denied") + + # Replace the module's shutil, not shutil.rmtree itself, so fixture + # teardown can still remove the directory. + monkeypatch.setattr( + "openhands.agent_server.api.shutil", SimpleNamespace(rmtree=fail_rmtree) + ) + mock_conversation_service = AsyncMock() + + with ( + patch( + "openhands.agent_server.api.get_default_conversation_service", + return_value=mock_conversation_service, + ), + patch("openhands.agent_server.api.get_vscode_service", return_value=None), + patch( + "openhands.agent_server.api.get_tool_preload_service", return_value=None + ), + ): + mock_app = AsyncMock() + mock_app.state = SimpleNamespace(config=Config()) + with caplog.at_level("WARNING"): + async with api_lifespan(mock_app): + pass + + assert "TMUX_TMPDIR" not in os.environ + assert "Failed to remove per-server tmux directory" in caplog.text + async def test_lifespan_keeps_preexisting_default_tmux_tmpdir( self, short_tmp_path, monkeypatch ):