The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(browser): a served profile's harness socket fits macOS sun_path for any session name
Tekniumf1273978cfed
diff --git a/tests/tools/test_browser_profile_scope_edges.py b/tests/tools/test_browser_profile_scope_edges.pyindex 438f7b4543a..8dcb9a6bc64 100644--- a/tests/tools/test_browser_profile_scope_edges.py+++ b/tests/tools/test_browser_profile_scope_edges.py@@ -3,6 +3,7 @@A multiplexed gateway serves every profile from one process; a live ``/browser connect`` endpoint,a harness daemon's runtime and tmp dirs, and a browser session belong to ONE profile."""+import contextlibimport threadingimport pytest@@ -49,3 +50,86 @@ def test_single_profile_bare_thread_keeps_the_process_override(profiles):bt_cdp.set_live_cdp_override("http://127.0.0.1:9402")assert _in_bare_thread(bt_cdp.live_cdp_override) == "http://127.0.0.1:9402"assert hermes_home_key() in bt_cdp._live_overrides+++# --- macOS AF_UNIX budget for a served profile's harness sockets -------------------------------------++_LONGEST_NAME = "n" * 64 # browser_harness/_ipc.py _NAME_RE: [A-Za-z0-9_-]{1,64}+++def _sock_len(runtime_dir: str) -> int:+ """browser_harness/_ipc.py ``_sock_path``: ``<resolved BH_RUNTIME_DIR>/bu-<NAME>.sock`` when+ ``BH_RUNTIME_DIR_SHARED=1`` (pinned against the installed package by the test below)."""+ return len(f"{runtime_dir}/bu-{_LONGEST_NAME}.sock".encode())+++def test_installed_harness_names_a_shared_dir_socket_bu_name_sock(tmp_path):+ """The length rule rests on the installed harness's stem: resolved dir + ``bu-<NAME>.sock``."""+ import os+ import subprocess+ import sys+ rt = tmp_path / "rt"+ env = {**os.environ, "BH_RUNTIME_DIR": str(rt), "BH_RUNTIME_DIR_SHARED": "1",+ "BH_TMP_DIR": str(tmp_path / "tmp"), "BH_HOME": str(tmp_path / "home")}+ out = subprocess.run([sys.executable, "-c",+ f"from browser_harness import _ipc; print(_ipc._sock_path({_LONGEST_NAME!r}))"],+ env=env, capture_output=True, text=True, check=True).stdout.strip()+ assert out == f"{rt.resolve()}/bu-{_LONGEST_NAME}.sock"+++def test_a_served_profiles_harness_socket_fits_macos_sun_path_on_a_default_home(profiles, monkeypatch):+ """macOS ``sun_path`` is 104 bytes (103 + NUL). Under ``~/.config/browser-harness/runtime/p-<hash>``+ a served profile's socket left room for only ~31-character session names on a 9-letter account."""+ import os+ import sys+ from tools import browser_use_cli as bu_cli+ a, _b = profiles+ real = os.path.realpath+ # os-marker: ok — computed length on a fixed macOS-shaped HOME; the real branch runs in the macOS test below+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.setattr(os.path, "realpath", # no-tmp: ok — macOS resolves the /tmp alias+ lambda p, *args, **kw: "/private/tmp" if p == "/tmp" else real(p, *args, **kw))+ claimed = []+ monkeypatch.setattr(bu_cli, "_claim_private_dir", lambda path: claimed.append(path) or True, raising=False)+ env = {"HOME": "/Users/alexander"}+ with _profile_runtime_scope(a, hydrate_secrets=False):+ bu_cli._namespace_harness_daemons(env)+ assert env["BH_RUNTIME_DIR_SHARED"] == "1"+ assert _sock_len(env["BH_RUNTIME_DIR"]) <= 103, env["BH_RUNTIME_DIR"]+ assert claimed == [env["BH_RUNTIME_DIR"]]++[email protected]("macos")+def test_on_macos_a_served_profile_binds_a_64_char_session_socket(profiles, tmp_path):+ """Real branch: the dir is claimed under the real short root and a 64-character name binds."""+ import os+ import socket+ from tools import browser_use_cli as bu_cli+ a, _b = profiles+ env = {"HOME": str(tmp_path / ("u" * 40))}+ with _profile_runtime_scope(a, hydrate_secrets=False):+ bu_cli._namespace_harness_daemons(env)+ path = f"{os.path.realpath(env['BH_RUNTIME_DIR'])}/bu-{_LONGEST_NAME}.sock"+ assert len(path.encode()) <= 103+ s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ try:+ s.bind(path)+ finally:+ s.close()+ with contextlib.suppress(OSError):+ os.unlink(path)+++def test_the_short_socket_dir_is_claimed_only_when_private_and_ours(tmp_path):+ """The short dir sits in a world-writable root: a symlink or another user's/open dir is refused."""+ from tools import browser_use_cli as bu_cli+ fresh = tmp_path / "hbh-fresh"+ assert bu_cli._claim_private_dir(str(fresh)) and (fresh.stat().st_mode & 0o777) == 0o700+ assert bu_cli._claim_private_dir(str(fresh)) # ours, 0700: reused+ open_dir = tmp_path / "hbh-open"+ open_dir.mkdir(mode=0o755)+ open_dir.chmod(0o755)+ assert not bu_cli._claim_private_dir(str(open_dir))+ link = tmp_path / "hbh-link"+ link.symlink_to(fresh)+ assert not bu_cli._claim_private_dir(str(link))diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 9d36bc0316e..3a3ee5aeece 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -197,10 +197,52 @@ def _namespace_harness_daemons(env: dict) -> None:root = str(Path(xdg) / "browser-harness") if xdg else str(Path(env.get("HOME") or Path.home()) / ".config" / "browser-harness")base = str(Path(root).expanduser() / "runtime")- env["BH_RUNTIME_DIR"] = str(Path(base) / f"p-{hashlib.sha256(tag.encode()).hexdigest()[:12]}")+ runtime = str(Path(base) / f"p-{hashlib.sha256(tag.encode()).hexdigest()[:12]}")+ env["BH_RUNTIME_DIR"] = _socket_fit_runtime_dir(runtime, base, tag)env["BH_RUNTIME_DIR_SHARED"] = "1" # several BU_NAMEs share the dir: keep bu-<name> stems+# browser_harness/_ipc.py: a shared runtime dir names a daemon socket ``<dir>/bu-<BU_NAME>.sock`` and+# BU_NAME may be 64 characters, so the dir gets the macOS sun_path (104 bytes with the NUL) minus 72.+_MACOS_SOCKET_DIR_BUDGET = 103 - len("/bu-.sock") - 64+++def _socket_fit_runtime_dir(runtime: str, base: str, tag: str) -> str:+ """``runtime`` unless it is too long for a 64-character session's socket on macOS, where+ ``~/.config/browser-harness/runtime`` alone already exceeds the budget. There the served profile+ gets a private dir under the short temp root (``/private/tmp/hbh-<12 hex>``, 29 bytes), keyed by+ uid, root and profile; if it can't be claimed safely the long path stays (shorter names only)."""+ if sys.platform != "darwin" or len(runtime.encode()) <= _MACOS_SOCKET_DIR_BUDGET:+ return runtime+ from hermes_constants import socket_safe_tmpdir+ getuid = getattr(os, "getuid", lambda: 0)+ digest = hashlib.sha256(f"{getuid()}\0{base}\0{tag}".encode()).hexdigest()[:12]+ short = os.path.join(os.path.realpath(socket_safe_tmpdir()), f"hbh-{digest}")+ if len(short.encode()) <= _MACOS_SOCKET_DIR_BUDGET and _claim_private_dir(short):+ return short+ return runtime+++def _claim_private_dir(path: str) -> bool:+ """Create ``path`` 0700, or accept an existing one only when it is a real directory (not a+ symlink) owned by this uid and closed to group/other: the temp root is world-writable, and the+ harness resolves symlinks and only chmods a dir it created itself."""+ import stat+ try:+ os.mkdir(path, 0o700)+ return True+ except FileExistsError:+ pass+ except OSError:+ return False+ try:+ st = os.lstat(path)+ except OSError:+ return False+ return (stat.S_ISDIR(st.st_mode) and st.st_uid == getattr(os, "getuid", lambda: -1)()+ and not st.st_mode & 0o077)++def _floor_subprocess_path(path: str) -> str:"""Keep system commands reachable from profile workers with a minimal PATH.