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.

feat: add helper utilities to execute commands and get OS type

[email protected]0a14a5225ba8
diff --git a/libs/python/computer-server/computer_server/handlers/factory.py b/libs/python/computer-server/computer_server/handlers/factory.py
index 56cfe6c21a..26a0792d5f 100644
--- a/libs/python/computer-server/computer_server/handlers/factory.py
+++ b/libs/python/computer-server/computer_server/handlers/factory.py
@@ -1,9 +1,8 @@
-import platform
-import subprocess
-from typing import Tuple, Type
+from typing import Tuple
from computer_server.diorama.base import BaseDioramaHandler
+from ..utils.helpers import get_current_os
from .base import (
BaseAccessibilityHandler,
BaseAutomationHandler,
@@ -12,15 +11,23 @@ from .base import (
BaseWindowHandler,
)
-# Conditionally import platform-specific handlers
-system = platform.system().lower()
-if system == "darwin":
+OS_TYPE = get_current_os()
+
+if OS_TYPE == "android":
+ from .android import (
+ AndroidAccessibilityHandler,
+ AndroidAutomationHandler,
+ AndroidDesktopHandler,
+ AndroidFileHandler,
+ AndroidWindowHandler,
+ )
+elif OS_TYPE == "darwin":
from computer_server.diorama.macos import MacOSDioramaHandler
from .macos import MacOSAccessibilityHandler, MacOSAutomationHandler
-elif system == "linux":
+elif OS_TYPE == "linux":
from .linux import LinuxAccessibilityHandler, LinuxAutomationHandler
-elif system == "windows":
+elif OS_TYPE == "windows":
from .windows import WindowsAccessibilityHandler, WindowsAutomationHandler
from .generic import GenericDesktopHandler, GenericFileHandler, GenericWindowHandler
@@ -29,31 +36,6 @@ from .generic import GenericDesktopHandler, GenericFileHandler, GenericWindowHan
class HandlerFactory:
"""Factory for creating OS-specific handlers."""
- @staticmethod
- def _get_current_os() -> str:
- """Determine the current OS.
-
- Returns:
- str: The OS type ('darwin' for macOS, 'linux' for Linux, or 'windows' for Windows)
-
- Raises:
- RuntimeError: If unable to determine the current OS
- """
- try:
- # Use platform.system() as primary method
- system = platform.system().lower()
- if system in ["darwin", "linux", "windows"]:
- return system
-
- # Fallback to uname if platform.system() doesn't return expected values (Unix-like systems only)
- result = subprocess.run(["uname", "-s"], capture_output=True, text=True)
- if result.returncode == 0:
- return result.stdout.strip().lower()
-
- raise RuntimeError(f"Unsupported OS: {system}")
- except Exception as e:
- raise RuntimeError(f"Failed to determine current OS: {str(e)}")
-
@staticmethod
def create_handlers() -> Tuple[
BaseAccessibilityHandler,
@@ -73,9 +55,16 @@ class HandlerFactory:
NotImplementedError: If the current OS is not supported
RuntimeError: If unable to determine the current OS
"""
- os_type = HandlerFactory._get_current_os()
-
- if os_type == "darwin":
+ if OS_TYPE == "android":
+ return (
+ AndroidAccessibilityHandler(),
+ AndroidAutomationHandler(),
+ BaseDioramaHandler(),
+ AndroidFileHandler(),
+ AndroidDesktopHandler(),
+ AndroidWindowHandler(),
+ )
+ elif OS_TYPE == "darwin":
return (
MacOSAccessibilityHandler(),
MacOSAutomationHandler(),
@@ -84,7 +73,7 @@ class HandlerFactory:
GenericDesktopHandler(),
GenericWindowHandler(),
)
- elif os_type == "linux":
+ elif OS_TYPE == "linux":
return (
LinuxAccessibilityHandler(),
LinuxAutomationHandler(),
@@ -93,7 +82,7 @@ class HandlerFactory:
GenericDesktopHandler(),
GenericWindowHandler(),
)
- elif os_type == "windows":
+ elif OS_TYPE == "windows":
return (
WindowsAccessibilityHandler(),
WindowsAutomationHandler(),
@@ -103,4 +92,4 @@ class HandlerFactory:
GenericWindowHandler(),
)
else:
- raise NotImplementedError(f"OS '{os_type}' is not supported")
+ raise NotImplementedError(f"OS '{OS_TYPE}' is not supported")
diff --git a/libs/python/computer-server/computer_server/main.py b/libs/python/computer-server/computer_server/main.py
index 3ae97ebc7c..f29ed94e5c 100644
--- a/libs/python/computer-server/computer_server/main.py
+++ b/libs/python/computer-server/computer_server/main.py
@@ -24,7 +24,7 @@ from fastapi import (
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
-from .handlers.factory import HandlerFactory
+from .handlers.factory import OS_TYPE, HandlerFactory
# Authentication session TTL (in seconds). Override via env var CUA_AUTH_TTL_SECONDS. Default: 60s
AUTH_SESSION_TTL_SECONDS: int = int(os.environ.get("CUA_AUTH_TTL_SECONDS", "60"))
@@ -261,19 +261,11 @@ auth_manager = AuthenticationManager()
@app.get("/status")
async def status():
- sys = platform.system().lower()
- # get os type
- if "darwin" in sys or sys == "macos" or sys == "mac":
- os_type = "macos"
- elif "windows" in sys:
- os_type = "windows"
- else:
- os_type = "linux"
# get computer-server features
features = []
if HAS_AGENT:
features.append("agent")
- return {"status": "ok", "os_type": os_type, "features": features}
+ return {"status": "ok", "os_type": OS_TYPE, "features": features}
@app.websocket("/ws", name="websocket_endpoint")
diff --git a/libs/python/computer-server/computer_server/utils/__init__.py b/libs/python/computer-server/computer_server/utils/__init__.py
index 995e1f6012..3cf2481da3 100644
--- a/libs/python/computer-server/computer_server/utils/__init__.py
+++ b/libs/python/computer-server/computer_server/utils/__init__.py
@@ -1,3 +1,3 @@
-from . import wallpaper
+from . import helpers, wallpaper
-__all__ = ["wallpaper"]
+__all__ = ["helpers", "wallpaper"]
diff --git a/libs/python/computer-server/computer_server/utils/helpers.py b/libs/python/computer-server/computer_server/utils/helpers.py
new file mode 100644
index 0000000000..64c80a0e12
--- /dev/null
+++ b/libs/python/computer-server/computer_server/utils/helpers.py
@@ -0,0 +1,81 @@
+import asyncio
+import os
+import platform
+import subprocess
+from typing import overload
+
+
+def get_current_os() -> str:
+ """Determine the current OS.
+
+ Returns:
+ str: The OS type ('android', 'darwin' for macOS, 'linux' for Linux, or 'windows' for Windows)
+
+ Raises:
+ RuntimeError: If unable to determine the current OS
+ """
+ try:
+ if os.environ.get("IS_CUA_ANDROID") == "true":
+ # Verify emulator is actually running by checking adb devices
+ try:
+ result = subprocess.run(
+ ["adb", "devices"], capture_output=True, text=True, timeout=5
+ )
+ if result.returncode == 0 and "emulator-5554" in result.stdout:
+ return "android"
+ else:
+ raise RuntimeError(
+ "IS_CUA_ANDROID is set but no emulator found. "
+ "Ensure Android emulator is running and accessible via adb."
+ )
+ except subprocess.TimeoutExpired:
+ raise RuntimeError(
+ "IS_CUA_ANDROID is set but adb command timed out. "
+ "Emulator may be starting up or unresponsive."
+ )
+
+ system = platform.system().lower()
+ if system in ["darwin", "linux", "windows"]:
+ return system
+
+ # Fallback to uname if platform.system() doesn't return expected values (Unix-like systems only)
+ result = subprocess.run(["uname", "-s"], capture_output=True, text=True)
+ if result.returncode == 0:
+ return result.stdout.strip().lower()
+
+ raise RuntimeError(f"Unsupported OS: {system}")
+ except Exception as e:
+ raise RuntimeError(f"Failed to determine current OS: {str(e)}")
+
+
+class CommandExecuctor:
+ def __init__(self, *base_cmd: str) -> None:
+ """Initialize with a base command.
+
+ Args:
+ base_cmd: The base command and its initial arguments.
+ """
+ self.__base_cmd = list(base_cmd)
+
+ @overload
+ async def run(self, *args: str, timeout: int = 10) -> tuple[bool, bytes]: ...
+ @overload
+ async def run(self, *args: str, decode: bool = True, timeout: int = 10) -> tuple[bool, str]: ...
+
+ async def run(
+ self, *args: str, decode: bool = False, timeout: int = 10
+ ) -> tuple[bool, bytes | str]:
+ cmd = self.__base_cmd + list(args)
+ try:
+ result = await asyncio.create_subprocess_exec(
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
+ )
+ stdout, stderr = await asyncio.wait_for(result.communicate(), timeout=timeout)
+ output = stdout or stderr
+ if decode:
+ output = output.decode("utf-8")
+ return result.returncode == 0, output
+ except asyncio.TimeoutError:
+ return False, f"Command timed out after {timeout}s".encode("utf-8")
+ except Exception as e:
+ return False, str(e).encode("utf-8")