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
27 changes: 23 additions & 4 deletions openhands-tools/openhands/tools/terminal/terminal/tmux_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import logging
import os
import sys
import time
import uuid
from collections.abc import Iterator, Mapping
Expand Down Expand Up @@ -75,7 +76,7 @@ def _install_libtmux_redaction_filter() -> None:


@contextmanager
def _socket_creation_lock() -> Iterator[None]:
def _socket_creation_lock(socket_dir: Path | None = None) -> Iterator[None]:
"""Serialize socket creation with the agent-server's startup cleanup.

A tmux socket exists between ``new-session`` and the recording of its owner
Expand All @@ -85,7 +86,8 @@ def _socket_creation_lock() -> Iterator[None]:
directory, which is the one path every process sharing ``TMUX_TMPDIR``
agrees on even while tmux has not created any socket yet.
"""
socket_dir = Path(os.environ.get("TMUX_TMPDIR", "/tmp")) / f"tmux-{os.getuid()}"
if socket_dir is None:
socket_dir = Path(os.environ.get("TMUX_TMPDIR", "/tmp")) / f"tmux-{os.getuid()}"
# tmux refuses a socket directory that is group/world accessible, and
# FileLock would create it with the umask default, so create it 0700 first.
socket_dir.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -124,9 +126,26 @@ def _new_owned_session(
lock. Startup cleanup in another process takes the same lock, so it can
never observe the socket before its owner is published.
"""
with _socket_creation_lock():
socket_name = f"{TMUX_SOCKET_NAME}-{uuid.uuid4().hex}"
socket_dir = Path(os.environ.get("TMUX_TMPDIR", "/tmp")) / f"tmux-{os.getuid()}"
socket_path = socket_dir / socket_name
# sun_path includes a NUL byte; limits are 108 on Linux and 104 on macOS/BSD.
max_socket_path = 107 if sys.platform.startswith("linux") else 103
fallback = (
os.name == "posix"
and len(os.fsencode(os.path.realpath(socket_path))) > max_socket_path
)
if fallback:
socket_dir = Path("/tmp") / f"tmux-{os.getuid()}"
# libtmux resolves socket_name using the process-wide TMUX_TMPDIR, so
# use an explicit path without changing other sessions' environment.
logger.warning("tmux socket path is too long; using %s", socket_dir)

with _socket_creation_lock(socket_dir):
server = libtmux.Server(
socket_name=f"{TMUX_SOCKET_NAME}-{uuid.uuid4().hex}", environment=dict(env)
socket_name=None if fallback else socket_name,
socket_path=str(socket_dir / socket_name) if fallback else None,
environment=dict(env),
)
session = server.new_session(
session_name=session_name,
Expand Down
8 changes: 6 additions & 2 deletions tests/agent_server/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,9 @@ def test_cleanup_stale_tmux_sessions_spares_live_sibling_socket(monkeypatch):
silently destroying the terminals of every other running agent-server.
A socket whose owner is gone must still be reclaimed.
"""
with tempfile.TemporaryDirectory(prefix="oh-shared-tmux-") as socket_dir:
with tempfile.TemporaryDirectory(
prefix="oh-shared-tmux-", dir="/tmp"
) as socket_dir:
monkeypatch.setenv("TMUX_TMPDIR", socket_dir)

# Conversation A: a live pool whose long-running command must survive.
Expand Down Expand Up @@ -295,7 +297,9 @@ def test_cleanup_stale_tmux_sessions_serializes_with_socket_creation(monkeypatch
if "mark_socket_owner(" in line
)

with tempfile.TemporaryDirectory(prefix="oh-concurrent-init-") as socket_dir:
with tempfile.TemporaryDirectory(
prefix="oh-concurrent-init-", dir="/tmp"
) as socket_dir:
monkeypatch.setenv("TMUX_TMPDIR", socket_dir)
env = {**os.environ, "TMUX_TMPDIR": socket_dir}
child = subprocess.Popen(
Expand Down
24 changes: 24 additions & 0 deletions tests/tools/terminal/test_tmux_pane_pool.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"""Tests for TmuxPanePool."""

import os
import tempfile
import threading
import time
from pathlib import Path

import pytest

Expand Down Expand Up @@ -258,6 +260,28 @@ def test_checkin_foreign_pane_is_ignored(pool):
pool.checkin(fake) # should log warning, not crash


@pytest.mark.skipif(os.name != "posix", reason="tmux requires Unix sockets")
@pytest.mark.parametrize("terminal_type", [TmuxTerminal, TmuxPanePool])
def test_overlong_tmux_tmpdir_uses_short_socket_path(
tmp_path, monkeypatch, terminal_type
):
socket_dir = tmp_path / ("deep-" + "x" * 80)
socket_dir.mkdir()
monkeypatch.setenv("TMUX_TMPDIR", str(socket_dir))
terminal = terminal_type(str(tmp_path))
try:
terminal.initialize()
server = (
terminal._server if isinstance(terminal, TmuxPanePool) else terminal.server
)
assert server is not None
assert server.socket_path is not None
assert Path(server.socket_path).is_relative_to("/tmp")
assert os.environ["TMUX_TMPDIR"] == str(socket_dir)
finally:
terminal.close()


@pytest.mark.parametrize("pooled", [True, False])
@pytest.mark.parametrize("operation", ["read", "write", "close"])
def test_stale_terminal_cannot_access_restarted_server(
Expand Down
Loading