Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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-<pid>`, 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
Expand Down
38 changes: 27 additions & 11 deletions openhands-agent-server/openhands/agent_server/api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import os
import shutil
import sys
import tempfile
import traceback
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -348,13 +354,23 @@ 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.
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:
Expand Down
141 changes: 138 additions & 3 deletions tests/agent_server/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()

Expand All @@ -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
Expand Down Expand Up @@ -562,8 +564,141 @@ 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_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
):
"""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:
Expand Down
Loading