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.

fix(computer-server): accept SDK-supplied timeout in run_command (#1343)

r33drichardsf550490294e3
diff --git a/libs/python/computer-server/computer_server/handlers/android.py b/libs/python/computer-server/computer_server/handlers/android.py
index 33e1d3b68d..7cb24ccac1 100644
--- a/libs/python/computer-server/computer_server/handlers/android.py
+++ b/libs/python/computer-server/computer_server/handlers/android.py
@@ -687,8 +687,21 @@ class AndroidAutomationHandler(BaseAutomationHandler):
success, output = await adb_exec.run("shell", script, decode=True)
return {"success": success, "output": output}
- async def run_command(self, command: str) -> Dict[str, Any]:
- """Run a shell command inside the Android emulator via adb shell."""
+ async def run_command(
+ self, command: str, timeout: Optional[float] = None
+ ) -> Dict[str, Any]:
+ """Run a shell command inside the Android emulator via adb shell.
+
+ Args:
+ command: The shell command to run (inside the emulator, via adb).
+ timeout: Optional timeout in seconds. When ``None`` (default),
+ waits indefinitely. SDK callers propagate their
+ ``sb.shell.run(cmd, timeout=...)`` value here so long-running
+ Android commands (e.g. ``uiautomator dump`` on a heavy PWA
+ under concurrent emulator CPU contention) can be given a
+ realistic budget instead of being cut off by a server-side
+ hardcoded default.
+ """
process = await asyncio.create_subprocess_exec(
"adb",
"-s",
@@ -698,7 +711,21 @@ class AndroidAutomationHandler(BaseAutomationHandler):
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
- stdout, stderr = await process.communicate()
+ try:
+ if timeout is None:
+ stdout, stderr = await process.communicate()
+ else:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(), timeout=timeout
+ )
+ except asyncio.TimeoutError:
+ process.kill()
+ return {
+ "success": False,
+ "stdout": "",
+ "stderr": f"Command timed out after {timeout}s",
+ "return_code": -1,
+ }
return {
"success": process.returncode == 0,
"stdout": stdout.decode() if stdout else "",
diff --git a/libs/python/computer-server/computer_server/handlers/base.py b/libs/python/computer-server/computer_server/handlers/base.py
index a555e0e528..f9880e3112 100644
--- a/libs/python/computer-server/computer_server/handlers/base.py
+++ b/libs/python/computer-server/computer_server/handlers/base.py
@@ -377,11 +377,23 @@ class BaseAutomationHandler(ABC):
return {"success": False, "error": str(e)}
# Command Execution
- async def run_command(self, command: str) -> Dict[str, Any]:
+ async def run_command(
+ self, command: str, timeout: Optional[float] = None
+ ) -> Dict[str, Any]:
"""Run a shell command locally and return its output.
When IS_CUA_ANDROID env var is set, routes the command through
``adb shell`` so execution runs inside the Android emulator.
+
+ Args:
+ command: The shell command to run.
+ timeout: Optional timeout in seconds. When ``None`` (default),
+ the command runs until completion with no upper bound. SDK
+ callers set this via ``sb.shell.run(cmd, timeout=...)``
+ (see ``cua_sandbox.interfaces.shell.Shell.run``). On
+ expiry the subprocess is killed and the result is
+ ``{"success": False, "stderr": "Command timed out after <t>s",
+ "return_code": -1}``.
"""
import os
@@ -398,7 +410,21 @@ class BaseAutomationHandler(ABC):
process = await asyncio.create_subprocess_shell(
command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
- stdout, stderr = await process.communicate()
+ try:
+ if timeout is None:
+ stdout, stderr = await process.communicate()
+ else:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(), timeout=timeout
+ )
+ except asyncio.TimeoutError:
+ process.kill()
+ return {
+ "success": False,
+ "stdout": "",
+ "stderr": f"Command timed out after {timeout}s",
+ "return_code": -1,
+ }
return {
"success": True,
"stdout": stdout.decode() if stdout else "",
diff --git a/libs/python/computer-server/computer_server/handlers/windows.py b/libs/python/computer-server/computer_server/handlers/windows.py
index f42749f1a9..e8e77e4603 100644
--- a/libs/python/computer-server/computer_server/handlers/windows.py
+++ b/libs/python/computer-server/computer_server/handlers/windows.py
@@ -709,11 +709,16 @@ class WindowsAutomationHandler(BaseAutomationHandler):
# Clipboard inherited from BaseAutomationHandler
# Command Execution (Windows override for multi-encoding support)
- async def run_command(self, command: str) -> Dict[str, Any]:
+ async def run_command(
+ self, command: str, timeout: Optional[float] = None
+ ) -> Dict[str, Any]:
"""Execute a shell command asynchronously.
Args:
command (str): The shell command to execute.
+ timeout (Optional[float]): Optional timeout in seconds. When
+ ``None`` (default), waits indefinitely. SDK callers set
+ this via ``sb.shell.run(cmd, timeout=...)``.
Returns:
Dict[str, Any]: A dictionary containing the success status and either
@@ -746,7 +751,21 @@ class WindowsAutomationHandler(BaseAutomationHandler):
process = await asyncio.create_subprocess_shell(
command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
- stdout, stderr = await process.communicate()
+ try:
+ if timeout is None:
+ stdout, stderr = await process.communicate()
+ else:
+ stdout, stderr = await asyncio.wait_for(
+ process.communicate(), timeout=timeout
+ )
+ except asyncio.TimeoutError:
+ process.kill()
+ return {
+ "success": False,
+ "stdout": "",
+ "stderr": f"Command timed out after {timeout}s",
+ "return_code": -1,
+ }
return {
"success": True,
"stdout": decode_output(stdout),
diff --git a/libs/python/computer-server/tests/test_run_command_timeout.py b/libs/python/computer-server/tests/test_run_command_timeout.py
new file mode 100644
index 0000000000..e84a24499b
--- /dev/null
+++ b/libs/python/computer-server/tests/test_run_command_timeout.py
@@ -0,0 +1,80 @@
+"""Tests for SDK-configurable ``run_command`` timeout propagation.
+
+The SDK's ``cua_sandbox.interfaces.shell.Shell.run(cmd, timeout=...)`` sends
+the timeout as a ``/cmd`` param; ``computer_server.main``'s dispatcher
+filters kwargs by the handler signature before forwarding. These tests
+cover the handler-side contract:
+
+* handler accepts ``timeout`` as a float keyword
+* ``timeout=None`` → waits indefinitely
+* ``timeout=<float>`` → times out at expiry with a ``success=False`` result
+ containing the standardised ``Command timed out after <t>s`` stderr and
+ ``return_code=-1``
+
+The Android / Windows variants share the same shape; the base handler is
+exercised here because it exposes a POSIX subprocess without adb/emulator
+state being required for a focused unit test.
+"""
+
+import asyncio
+
+import pytest
+from computer_server.handlers.base import BaseAutomationHandler
+
+
+class _MinimalHandler(BaseAutomationHandler):
+ """Concrete BaseAutomationHandler for exercising ``run_command`` only.
+
+ We clear ``__abstractmethods__`` AFTER class creation (below) instead
+ of stubbing every abstract method — the set changes as the interface
+ grows and keeping a mirror of the full abstract surface here is pure
+ maintenance overhead for a test that only touches ``run_command``.
+
+ Note: setting ``__abstractmethods__ = frozenset()`` inside the class
+ body does NOT work — Python's ``ABCMeta`` overwrites it during class
+ creation. The override must happen after the class statement.
+ """
+
+ pass
+
+
+# Bypass ABC enforcement — ABCMeta.__call__ checks this at instantiation time.
+_MinimalHandler.__abstractmethods__ = frozenset()
+
+
+class TestRunCommandTimeout:
+ @pytest.mark.asyncio
+ async def test_no_timeout_defaults_to_indefinite_wait(self, monkeypatch):
+ # Ensure we hit the subprocess_shell branch (not the android adb branch).
+ monkeypatch.delenv("IS_CUA_ANDROID", raising=False)
+ h = _MinimalHandler()
+
+ result = await h.run_command("echo hello")
+ assert result["success"] is True
+ assert result["stdout"].strip() == "hello"
+ assert result["return_code"] == 0
+
+ @pytest.mark.asyncio
+ async def test_timeout_honoured_when_passed(self, monkeypatch):
+ monkeypatch.delenv("IS_CUA_ANDROID", raising=False)
+ h = _MinimalHandler()
+
+ # sleep 5, cap at 0.2 — should time out
+ start = asyncio.get_event_loop().time()
+ result = await h.run_command("sleep 5", timeout=0.2)
+ elapsed = asyncio.get_event_loop().time() - start
+
+ assert result["success"] is False
+ assert "timed out" in result["stderr"].lower()
+ assert result["return_code"] == -1
+ # Must have returned within a small factor of the requested timeout.
+ assert elapsed < 2.0, f"expected quick timeout, took {elapsed:.2f}s"
+
+ @pytest.mark.asyncio
+ async def test_fast_command_under_timeout_succeeds(self, monkeypatch):
+ monkeypatch.delenv("IS_CUA_ANDROID", raising=False)
+ h = _MinimalHandler()
+
+ result = await h.run_command("echo done", timeout=10.0)
+ assert result["success"] is True
+ assert result["stdout"].strip() == "done"