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(cua-driver): tolerate fileno-less Python stdio (#2482)

简律纯d041f1a580d4
diff --git a/libs/cua-driver/python/src/cua_driver/wrapper.py b/libs/cua-driver/python/src/cua_driver/wrapper.py
index 193c513635..d3a4e3a693 100644
--- a/libs/cua-driver/python/src/cua_driver/wrapper.py
+++ b/libs/cua-driver/python/src/cua_driver/wrapper.py
@@ -1,10 +1,24 @@
"""Subprocess wrapper for cua-driver binary with stdio passthrough."""
import os
-import sys
import subprocess
+import sys
from pathlib import Path
-from typing import Optional
+from typing import IO, Any, Optional
+
+
+def _stdio_with_fileno(stream: Optional[IO[Any]]) -> Optional[IO[Any]]:
+ """Keep a Python stream only when subprocess can use its descriptor."""
+ if stream is None:
+ return None
+ try:
+ descriptor = stream.fileno()
+ if not isinstance(descriptor, int) or descriptor < 0:
+ return None
+ os.fstat(descriptor)
+ except (AttributeError, OSError, OverflowError, TypeError, ValueError):
+ return None
+ return stream
def get_binary_path() -> Path:
@@ -66,9 +80,9 @@ def run_cua_driver(args: Optional[list[str]] = None) -> int:
# Run with direct stdio inheritance - no buffering, no capturing
result = subprocess.run(
[str(binary_path), *args],
- stdin=sys.stdin,
- stdout=sys.stdout,
- stderr=sys.stderr,
+ stdin=_stdio_with_fileno(sys.stdin),
+ stdout=_stdio_with_fileno(sys.stdout),
+ stderr=_stdio_with_fileno(sys.stderr),
env=child_env,
)
return result.returncode
diff --git a/libs/cua-driver/python/tests/test_wrapper.py b/libs/cua-driver/python/tests/test_wrapper.py
index f40d15d080..27ccc324d5 100644
--- a/libs/cua-driver/python/tests/test_wrapper.py
+++ b/libs/cua-driver/python/tests/test_wrapper.py
@@ -1,14 +1,27 @@
"""Tests for the cua-driver Python wrapper."""
+import importlib.util
+import io
import os
import subprocess
import sys
from pathlib import Path
+from typing import Any
from unittest.mock import Mock, patch
import pytest
+def load_wrapper_module() -> Any:
+ module_path = Path(__file__).resolve().parents[1] / "src/cua_driver/wrapper.py"
+ spec = importlib.util.spec_from_file_location("cua_driver_wrapper", module_path)
+ assert spec is not None
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
def test_get_binary_path():
"""Test that get_binary_path returns a valid path."""
from cua_driver.wrapper import get_binary_path
@@ -26,7 +39,7 @@ def test_get_binary_path():
def test_run_cua_driver_version(monkeypatch):
"""Test running cua-driver --version through the wrapper."""
- from cua_driver.wrapper import run_cua_driver, get_binary_path
+ from cua_driver.wrapper import get_binary_path, run_cua_driver
try:
binary_path = get_binary_path()
@@ -40,7 +53,7 @@ def test_run_cua_driver_version(monkeypatch):
def test_wrapper_preserves_exit_code():
"""Test that the wrapper preserves the binary's exit code."""
- from cua_driver.wrapper import run_cua_driver, get_binary_path
+ from cua_driver.wrapper import get_binary_path, run_cua_driver
try:
binary_path = get_binary_path()
@@ -52,32 +65,87 @@ def test_wrapper_preserves_exit_code():
assert exit_code != 0
-@patch("cua_driver.wrapper.subprocess.run")
-@patch("cua_driver.wrapper.get_binary_path")
-def test_subprocess_args(mock_get_binary, mock_run):
+def test_subprocess_args(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""Test that subprocess is called with correct arguments."""
- from cua_driver.wrapper import run_cua_driver
-
+ wrapper = load_wrapper_module()
mock_binary = Path("/fake/path/cua-driver")
- mock_get_binary.return_value = mock_binary
- mock_run.return_value = Mock(returncode=0)
-
- run_cua_driver(["mcp", "--help"])
-
- mock_run.assert_called_once()
- call_args = mock_run.call_args
- assert call_args[0][0] == [str(mock_binary), "mcp", "--help"]
- assert call_args[1]["stdin"] == sys.stdin
- assert call_args[1]["stdout"] == sys.stdout
- assert call_args[1]["stderr"] == sys.stderr
- assert call_args[1]["env"]["CUA_DRIVER_INSTALL_CHANNEL"] == "python_package"
+ mock_run = Mock(return_value=Mock(returncode=0))
+ monkeypatch.setattr(wrapper, "get_binary_path", Mock(return_value=mock_binary))
+ monkeypatch.setattr(wrapper.subprocess, "run", mock_run)
+
+ stdin_path = tmp_path / "stdin"
+ stdin_path.write_text("")
+ with (
+ stdin_path.open() as stdin,
+ (tmp_path / "stdout").open("w") as stdout,
+ (tmp_path / "stderr").open("w") as stderr,
+ ):
+ monkeypatch.setattr(sys, "stdin", stdin)
+ monkeypatch.setattr(sys, "stdout", stdout)
+ monkeypatch.setattr(sys, "stderr", stderr)
+
+ wrapper.run_cua_driver(["mcp", "--help"])
+
+ mock_run.assert_called_once()
+ call_args = mock_run.call_args
+ assert call_args[0][0] == [str(mock_binary), "mcp", "--help"]
+ assert call_args[1]["stdin"] is stdin
+ assert call_args[1]["stdout"] is stdout
+ assert call_args[1]["stderr"] is stderr
+ assert call_args[1]["env"]["CUA_DRIVER_INSTALL_CHANNEL"] == "python_package"
+
+
[email protected]("stream_name", ["stdin", "stdout", "stderr"])
+def test_subprocess_falls_back_for_fileno_less_stdio(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, stream_name: str
+) -> None:
+ """A captured stream falls back without changing usable descriptors."""
+ wrapper = load_wrapper_module()
+ monkeypatch.setattr(wrapper, "get_binary_path", Mock(return_value=Path(sys.executable)))
+
+ stdin_path = tmp_path / "stdin"
+ stdin_path.write_text("")
+ with (
+ stdin_path.open() as stdin,
+ (tmp_path / "stdout").open("w") as stdout,
+ (tmp_path / "stderr").open("w") as stderr,
+ ):
+ streams = {"stdin": stdin, "stdout": stdout, "stderr": stderr}
+ streams[stream_name] = io.StringIO()
+ for name, stream in streams.items():
+ monkeypatch.setattr(sys, name, stream)
+
+ exit_code = wrapper.run_cua_driver(["-c", "pass"])
+
+ assert exit_code == 0
+
+
[email protected]("descriptor", [None, -1, "1"])
+def test_stdio_falls_back_for_invalid_fileno(descriptor: object) -> None:
+ """A non-descriptor fileno result is not forwarded to subprocess."""
+ wrapper = load_wrapper_module()
+ stream = Mock()
+ stream.fileno.return_value = descriptor
+
+ assert wrapper._stdio_with_fileno(stream) is None
+
+
+def test_subprocess_preserves_exact_exit_code(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The stdio fallback does not change the child's exit-code contract."""
+ wrapper = load_wrapper_module()
+ monkeypatch.setattr(
+ wrapper, "get_binary_path", Mock(return_value=Path("/fake/path/cua-driver"))
+ )
+ monkeypatch.setattr(wrapper.subprocess, "run", Mock(return_value=Mock(returncode=42)))
+
+ assert wrapper.run_cua_driver(["--version"]) == 42
@patch("cua_driver.wrapper.subprocess.run")
@patch("cua_driver.wrapper.get_binary_path")
-def test_subprocess_preserves_explicit_install_channel(
- mock_get_binary, mock_run, monkeypatch
-):
+def test_subprocess_preserves_explicit_install_channel(mock_get_binary, mock_run, monkeypatch):
"""An update/install caller's bounded channel takes precedence."""
from cua_driver.wrapper import run_cua_driver