Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

Re-organize PostHog client methods

James Murdza8dc084a32d53
diff --git a/libs/python/core/core/telemetry/posthog.py b/libs/python/core/core/telemetry/posthog.py
index 7343bd6f09..a6c361e5f6 100644
--- a/libs/python/core/core/telemetry/posthog.py
+++ b/libs/python/core/core/telemetry/posthog.py
@@ -23,6 +23,9 @@ PUBLIC_POSTHOG_HOST = "https://eu.i.posthog.com"
class PostHogTelemetryClient:
"""Collects and reports telemetry data via PostHog."""
+ # Global singleton (class-managed)
+ _singleton: Optional["PostHogTelemetryClient"] = None
+
def __init__(self):
"""Initialize PostHog telemetry client."""
self.installation_id = self._get_or_create_installation_id()
@@ -30,31 +33,66 @@ class PostHogTelemetryClient:
self.queued_events: List[Dict[str, Any]] = []
# Log telemetry status on startup
- if not self._telemetry_disabled():
- logger.info(f"Telemetry enabled")
+ if self.is_telemetry_enabled():
+ logger.info("Telemetry enabled")
# Initialize PostHog client if config is available
self._initialize_posthog()
else:
logger.info("Telemetry disabled")
- @staticmethod
- def _telemetry_disabled() -> bool:
- """Return ``True`` when telemetry is explicitly disabled via environment variables."""
+ @classmethod
+ def is_telemetry_enabled(cls) -> bool:
+ """True if telemetry is currently active for this process."""
return (
- os.environ.get("CUA_TELEMETRY", "").lower() == "off"
- or os.environ.get("CUA_TELEMETRY_ENABLED", "true").lower()
- not in {"1", "true", "yes", "on"}
+ # Legacy opt-out flag
+ os.environ.get("CUA_TELEMETRY", "").lower() != "off"
+ # Opt-in flag (defaults to enabled)
+ and os.environ.get("CUA_TELEMETRY_ENABLED", "true").lower() in { "1", "true", "yes", "on" }
)
+ def _get_or_create_installation_id(self) -> str:
+ """Get or create a unique installation ID that persists across runs.
- # ------------------------------------------------------------------
- # Public helpers
- # ------------------------------------------------------------------
+ The ID is always stored within the core library directory itself,
+ ensuring it persists regardless of how the library is used.
- @classmethod
- def is_telemetry_enabled(cls) -> bool:
- """True if telemetry is currently active for this process."""
- return not cls._telemetry_disabled()
+ This ID is not tied to any personal information.
+ """
+ # Get the core library directory (where this file is located)
+ try:
+ # Find the core module directory using this file's location
+ core_module_dir = Path(
+ __file__
+ ).parent.parent # core/telemetry/posthog_client.py -> core/telemetry -> core
+ storage_dir = core_module_dir / ".storage"
+ storage_dir.mkdir(exist_ok=True)
+
+ id_file = storage_dir / "installation_id"
+
+ # Try to read existing ID
+ if id_file.exists():
+ try:
+ stored_id = id_file.read_text().strip()
+ if stored_id: # Make sure it's not empty
+ logger.debug(f"Using existing installation ID: {stored_id}")
+ return stored_id
+ except Exception as e:
+ logger.debug(f"Error reading installation ID file: {e}")
+
+ # Create new ID
+ new_id = str(uuid.uuid4())
+ try:
+ id_file.write_text(new_id)
+ logger.debug(f"Created new installation ID: {new_id}")
+ return new_id
+ except Exception as e:
+ logger.warning(f"Could not write installation ID: {e}")
+ except Exception as e:
+ logger.warning(f"Error accessing core module directory: {e}")
+
+ # Last resort: Create a new in-memory ID
+ logger.warning("Using random installation ID (will not persist across runs)")
+ return str(uuid.uuid4())
def _initialize_posthog(self) -> bool:
"""Initialize the PostHog client with configuration.
@@ -100,11 +138,7 @@ class PostHogTelemetryClient:
return False
def _identify(self) -> None:
- """Set up user properties for the current installation with PostHog.
-
- Note: The Python PostHog SDK doesn't have an identify() method like the web SDK.
- Instead, we capture an identification event with user properties.
- """
+ """Set up user properties for the current installation with PostHog."""
try:
properties = {
"version": __version__,
@@ -128,50 +162,6 @@ class PostHogTelemetryClient:
except Exception as e:
logger.warning(f"Failed to set up PostHog user properties: {e}")
- def _get_or_create_installation_id(self) -> str:
- """Get or create a unique installation ID that persists across runs.
-
- The ID is always stored within the core library directory itself,
- ensuring it persists regardless of how the library is used.
-
- This ID is not tied to any personal information.
- """
- # Get the core library directory (where this file is located)
- try:
- # Find the core module directory using this file's location
- core_module_dir = Path(
- __file__
- ).parent.parent # core/telemetry/posthog_client.py -> core/telemetry -> core
- storage_dir = core_module_dir / ".storage"
- storage_dir.mkdir(exist_ok=True)
-
- id_file = storage_dir / "installation_id"
-
- # Try to read existing ID
- if id_file.exists():
- try:
- stored_id = id_file.read_text().strip()
- if stored_id: # Make sure it's not empty
- logger.debug(f"Using existing installation ID: {stored_id}")
- return stored_id
- except Exception as e:
- logger.debug(f"Error reading installation ID file: {e}")
-
- # Create new ID
- new_id = str(uuid.uuid4())
- try:
- id_file.write_text(new_id)
- logger.debug(f"Created new installation ID: {new_id}")
- return new_id
- except Exception as e:
- logger.warning(f"Could not write installation ID: {e}")
- except Exception as e:
- logger.warning(f"Error accessing core module directory: {e}")
-
- # Last resort: Create a new in-memory ID
- logger.warning("Using random installation ID (will not persist across runs)")
- return str(uuid.uuid4())
-
def record_event(self, event_name: str, properties: Optional[Dict[str, Any]] = None) -> None:
"""Record an event with optional properties.
@@ -180,7 +170,7 @@ class PostHogTelemetryClient:
properties: Event properties (must not contain sensitive data)
"""
# Respect runtime telemetry opt-out.
- if self._telemetry_disabled():
+ if not self.is_telemetry_enabled():
logger.debug("Telemetry disabled; event not recorded.")
return
@@ -222,8 +212,6 @@ class PostHogTelemetryClient:
logger.debug(f"Failed to flush PostHog events: {e}")
return False
- _singleton: Optional["PostHogTelemetryClient"] = None
-
@classmethod
def get_client(cls) -> "PostHogTelemetryClient":
"""Return the global PostHogTelemetryClient instance, creating it if needed."""