move socket path into /tmp/.browser_cli subfolder with registry

This commit is contained in:
2026-04-09 08:46:50 +02:00
parent 50dc2bb5e5
commit 7c2fa9a9ac
3 changed files with 37 additions and 11 deletions
+24 -8
View File
@@ -5,8 +5,8 @@ Used by both the CLI and the public Python API.
Profile selection order:
1. Explicit `profile` argument to send_command()
2. BROWSER_CLI_PROFILE environment variable
3. First entry in /tmp/browser-cli-registry.json
4. Fallback: /tmp/browser-cli-default.sock
3. First entry in /tmp/.browser_cli/registry.json
4. Fallback: /tmp/.browser_cli/default.sock
"""
import json
import os
@@ -16,14 +16,20 @@ import uuid
from pathlib import Path
from typing import Any
REGISTRY_PATH = Path("/tmp/browser-cli-registry.json")
DEFAULT_SOCKET = "/tmp/browser-cli-default.sock"
SOCKET_DIR = Path("/tmp/.browser_cli")
REGISTRY_PATH = SOCKET_DIR / "registry.json"
DEFAULT_SOCKET = str(SOCKET_DIR / "default.sock")
class BrowserNotConnected(Exception):
"""Raised when the native host socket is not available."""
def _active_sockets(reg: dict) -> dict:
"""Return only entries whose socket file exists on disk."""
return {k: v for k, v in reg.items() if Path(v).exists()}
def _resolve_socket(profile: str | None = None) -> str:
"""Return the socket path for the given profile (or auto-detect)."""
target = profile or os.environ.get("BROWSER_CLI_PROFILE")
@@ -37,14 +43,24 @@ def _resolve_socket(profile: str | None = None) -> str:
except Exception:
pass
safe = target.replace(" ", "_").replace("/", "_")
return f"/tmp/browser-cli-{safe}.sock"
return str(SOCKET_DIR / f"{safe}.sock")
# Auto-detect: use first registered entry
# Auto-detect: error when multiple browser instances are active
if REGISTRY_PATH.exists():
try:
reg = json.loads(REGISTRY_PATH.read_text())
if reg:
return next(iter(reg.values()))
active = _active_sockets(reg)
if len(active) > 1:
aliases = list(active.keys())
examples = "\n".join(f" browser-cli --browser {a} ..." for a in aliases)
raise BrowserNotConnected(
f"Multiple browser instances are active: {', '.join(aliases)}\n"
f"Use --browser <alias> to select one:\n{examples}"
)
if active:
return next(iter(active.values()))
except BrowserNotConnected:
raise
except Exception:
pass