Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(sdk): Windows VM support + parallel server probe (#1262)
ddupont0e2e4040b4e1
diff --git a/.github/workflows/cd-py-computer-server.yml b/.github/workflows/cd-py-computer-server.ymlindex 474a7fc776..40060bd609 100644--- a/.github/workflows/cd-py-computer-server.yml+++ b/.github/workflows/cd-py-computer-server.yml@@ -80,10 +80,12 @@ jobs:include:- os: ubuntu-latestartifact_name: cua-computer-server-linux-x86_64- binary_name: cua-computer-server+ zip_name: cua-computer-server-linux-x86_64.tar.gz+ dir_name: cua-computer-server- os: windows-latest- artifact_name: cua-computer-server-windows-x86_64.exe- binary_name: cua-computer-server.exe+ artifact_name: cua-computer-server-windows-x86_64+ zip_name: cua-computer-server-windows-x86_64.zip+ dir_name: cua-computer-serverruns-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4@@ -98,16 +100,28 @@ jobs:pip install pyinstallerpip install -e libs/python/computer-server- - name: Build binary with PyInstaller+ - name: Build binary with PyInstaller (onedir — fast startup)run: |cd libs/python/computer-server- pyinstaller --onefile --name "${{ matrix.binary_name }}" run_server.py+ pyinstaller --onedir --name "${{ matrix.dir_name }}" --console --noconfirm --clean --collect-all computer_server --hidden-import uvicorn.logging --hidden-import uvicorn.protocols.http --hidden-import uvicorn.protocols.http.auto --hidden-import uvicorn.protocols.http.h11_impl --hidden-import uvicorn.protocols.websockets --hidden-import uvicorn.protocols.websockets.auto --hidden-import uvicorn.lifespan --hidden-import uvicorn.lifespan.on --hidden-import PIL._tkinter_finder run_server.py++ - name: Create archive (Linux)+ if: runner.os == 'Linux'+ run: |+ cd libs/python/computer-server/dist+ tar czf "${{ matrix.zip_name }}" "${{ matrix.dir_name }}"/++ - name: Create archive (Windows)+ if: runner.os == 'Windows'+ run: |+ cd libs/python/computer-server/dist+ 7z a "${{ matrix.zip_name }}" "${{ matrix.dir_name }}/"- name: Upload artifactuses: actions/upload-artifact@v4with:name: ${{ matrix.artifact_name }}- path: libs/python/computer-server/dist/${{ matrix.binary_name }}+ path: libs/python/computer-server/dist/${{ matrix.zip_name }}set-env-variables:needs: [prepare, publish]diff --git a/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py b/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.pyindex e9e66d5c95..1485bcdb84 100644--- a/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py+++ b/libs/python/cua-sandbox/cua_sandbox/builder/windows_unattend.py@@ -31,6 +31,63 @@ def download_file(url: str, dest: Path, description: str = "") -> Path:return dest+def _resolve_server_eval_url(server_version: str, culture: str = "en-us", country: str = "US") -> str:+ """Resolve Windows Server evaluation ISO download URL from Microsoft's eval center.++ Adapted from quickemu/quickget's download_windows_server() which is itself+ adapted from the Mido project (https://github.com/ElliotKillick/Mido).++ Args:+ server_version: e.g. "windows-server-2022", "windows-server-2025"+ culture: Language culture code, e.g. "en-us"+ country: Country code, e.g. "US"++ Returns:+ Direct download URL for the ISO.+ """+ import re+ import urllib.request++ eval_url = f"https://www.microsoft.com/en-us/evalcenter/download-{server_version}"+ logger.info(f"Parsing Microsoft Eval Center: {eval_url}")++ headers = {+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0",+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ "Accept-Language": "en-US,en;q=0.5",+ }+ req = urllib.request.Request(eval_url, headers=headers)+ with urllib.request.urlopen(req, timeout=30) as resp:+ html = resp.read().decode("utf-8", errors="replace")++ # Extract go.microsoft.com/fwlink links with the matching culture+ pattern = rf"https://go\.microsoft\.com/fwlink/p/\?LinkID=\d+&clcid=0x[0-9a-f]+&culture={re.escape(culture)}&country={re.escape(country)}"+ links = re.findall(pattern, html)++ if not links:+ # Fallback: try any English link+ pattern_fallback = r"https://go\.microsoft\.com/fwlink/p/\?LinkID=\d+&clcid=0x[0-9a-f]+&culture=en-us&country=US"+ links = re.findall(pattern_fallback, html)++ if not links:+ raise RuntimeError(+ f"Could not find download link on {eval_url}. "+ f"Microsoft may have changed the page layout."+ )++ # First link is typically the x64 ISO+ download_link = links[0]+ logger.info(f"Resolved download link: {download_link}")++ # Follow redirect to get the actual ISO URL+ req2 = urllib.request.Request(download_link, method="HEAD", headers=headers)+ with urllib.request.urlopen(req2, timeout=30) as resp2:+ final_url = resp2.url++ logger.info(f"Final ISO URL: {final_url}")+ return final_url++def download_windows_iso(version: str = "11",dest: Optional[Path] = None,@@ -55,9 +112,32 @@ def download_windows_iso(url = "https://go.microsoft.com/fwlink/?linkid=2334167&clcid=0x409"elif version == "10":url = "https://go.microsoft.com/fwlink/?LinkId=691209"+ elif version in ("server-2022", "2022"):+ version = "server-2022"+ iso_file = dest_dir / f"windows-{version}.iso"+ if iso_file.exists():+ logger.info(f"Using cached ISO: {iso_file}")+ return iso_file+ url = _resolve_server_eval_url("windows-server-2022")+ elif version in ("server-2025", "2025"):+ version = "server-2025"+ iso_file = dest_dir / f"windows-{version}.iso"+ if iso_file.exists():+ logger.info(f"Using cached ISO: {iso_file}")+ return iso_file+ url = _resolve_server_eval_url("windows-server-2025")+ elif version in ("server-2019", "2019"):+ version = "server-2019"+ iso_file = dest_dir / f"windows-{version}.iso"+ if iso_file.exists():+ logger.info(f"Using cached ISO: {iso_file}")+ return iso_file+ url = _resolve_server_eval_url("windows-server-2019")else:raise ValueError(- f"Cannot auto-download Windows {version}. " f"Provide --iso-path to use your own ISO."+ f"Cannot auto-download Windows {version}. "+ f"Supported: 10, 11, server-2022, server-2025, server-2019. "+ f"Or provide --iso-path to use your own ISO.")logger.info(f"Downloading Windows {version} Enterprise Evaluation ISO...")@@ -72,24 +152,59 @@ def generate_autounattend_xml(product_key: Optional[str] = None,*,include_virtio_drivers: bool = True,+ version: str = "11",) -> str:- """Generate a Windows 11 Autounattend.xml for unattended installation.+ """Generate a Windows Autounattend.xml for unattended installation.Args:- product_key: Windows product key. Defaults to Win11 Pro generic key.+ product_key: Windows product key. If None, uses generic key for edition.include_virtio_drivers: Include VirtIO driver paths in WinPE pass.Set False for Hyper-V (has enlightened drivers built-in).+ version: Windows version - "11", "10", "server-2022", "server-2025", etc."""+ is_server = version.startswith("server-")++ # KMS Generic Volume License Keys (GVLKs) for Server editions+ # https://learn.microsoft.com/en-us/windows-server/get-started/kms-client-activation-keys+ _server_gvlks = {+ "server-2025": "TVRH6-WHNXV-R9WG3-9XRFY-MY832", # Standard+ "server-2022": "VDYBN-27WPP-V4HQT-9VMD4-VMK7H", # Standard+ "server-2019": "N69G4-B89J2-4G8F4-WWYCC-J464C", # Standard+ }+key_section = ""if product_key:key_section = f"""<ProductKey><Key>{product_key}</Key></ProductKey>"""+ elif is_server:+ # Server eval ISOs: omit product key entirely. The eval ISO has its own+ # built-in eval key. GVLKs are for volume license media only.+ # Users with SPLA can inject their GVLK via the product_key parameter.+ passelse:key_section = """<ProductKey><Key>VK7JG-NPHTM-C97JM-9MPGT-3V66T</Key></ProductKey>"""+ # Image selection: use /IMAGE/NAME for reliability (index varies by ISO).+ # For server eval ISOs, standard pattern is:+ # "Windows Server 2022 Standard Evaluation (Desktop Experience)"+ # For desktop: /IMAGE/INDEX = 1 (single-edition ISOs)+ _server_image_names = {+ "server-2022": "Windows Server 2022 Standard Evaluation (Desktop Experience)",+ "server-2025": "Windows Server 2025 Standard Evaluation (Desktop Experience)",+ "server-2019": "Windows Server 2019 SERVERDATACENTEREVAL",+ }+ if is_server:+ image_name = _server_image_names.get(version)+ # Use /IMAGE/NAME for server (more reliable than index)+ image_select_key = "/IMAGE/NAME"+ image_select_value = image_name or f"Windows Server {version.split('-')[1]} Standard Evaluation (Desktop Experience)"+ else:+ image_select_key = "/IMAGE/INDEX"+ image_select_value = "1"+virtio_section = ""if include_virtio_drivers:virtio_section = """@@ -177,6 +292,12 @@ def generate_autounattend_xml(<DiskID>0</DiskID><PartitionID>3</PartitionID></InstallTo>+ <InstallFrom>+ <MetaData wcm:action="add">+ <Key>{image_select_key}</Key>+ <Value>{image_select_value}</Value>+ </MetaData>+ </InstallFrom><InstallToAvailablePartition>false</InstallToAvailablePartition></OSImage></ImageInstall>@@ -314,19 +435,23 @@ def create_unattend_iso(*,include_virtio_drivers: bool = True,include_startup_nsh: bool = True,+ version: str = "11",) -> Path:"""Create a small data-only ISO containing Autounattend.xml + setup script.Args:include_virtio_drivers: Include VirtIO driver paths (QEMU needs them, Hyper-V doesn't).include_startup_nsh: Include UEFI shell startup.nsh (QEMU/OVMF needs it, Hyper-V doesn't).+ version: Windows version for autounattend generation."""unattend_iso = work_dir / "unattend.iso"if unattend_iso.exists():logger.info(f"Using cached unattend ISO: {unattend_iso}")return unattend_iso- xml = generate_autounattend_xml(product_key, include_virtio_drivers=include_virtio_drivers)+ xml = generate_autounattend_xml(+ product_key, include_virtio_drivers=include_virtio_drivers, version=version+ )xml_path = work_dir / "Autounattend.xml"xml_path.write_text(xml, encoding="utf-8")diff --git a/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py b/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.pyindex 9affc0f044..9015038f6e 100644--- a/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py+++ b/libs/python/cua-sandbox/cua_sandbox/registry/qemu_builder.py@@ -51,13 +51,14 @@ class QEMUImageConfig:"""VM configuration stored as the OCI config blob."""guest_os: str = "windows"- version: str = "11"+ version: str = "11" # "11", "10", "server-2022", "server-2025"cpu: int = 4ram_mb: int = 8192disk_size_gb: int = 64disk_format: str = "qcow2"tpm: bool = Truearchitecture: str = "x86_64"+ qemu_bin: Optional[str] = None # Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)display: dict = field(default_factory=lambda: {"width": 1920, "height": 1080})@@ -285,6 +286,7 @@ def _build_image_wsl2(# ── Full build ──────────────────────────────────────────────────────────────+def build_image(config: Optional[QEMUImageConfig] = None,*,@@ -314,7 +316,7 @@ def build_image(# Create a small data-only ISO with Autounattend.xml + setup script.# Windows Setup searches all drives for Autounattend.xml automatically,# so we keep the original Windows ISO unchanged (it's UEFI-bootable).- unattend_iso = create_unattend_iso(work_dir, product_key)+ unattend_iso = create_unattend_iso(work_dir, product_key, version=config.version)# Step 2: Create diskcreate_qcow2(disk_path, config.disk_size_gb)@@ -325,9 +327,11 @@ def build_image(import platform as _plat- from cua_sandbox.runtime.qemu_installer import qemu_bin-- qemu = qemu_bin(config.architecture)+ if config.qemu_bin:+ qemu = config.qemu_bin+ else:+ from cua_sandbox.runtime.qemu_installer import qemu_bin+ qemu = qemu_bin(config.architecture)qemu_dir = Path(qemu).parent# Locate OVMF UEFI firmware (required for Windows 10/11)@@ -774,7 +778,7 @@ def main():# buildbuild_p = sub.add_parser("build", help="Build a Windows VM image")- build_p.add_argument("--windows-version", default="11", help="Windows version (10 or 11)")+ build_p.add_argument("--windows-version", default="11", help="Windows version (10, 11, server-2022, server-2025)")build_p.add_argument("--iso-path", help="Path to Windows ISO (skip download)")build_p.add_argument("--disk-size", type=int, default=64, help="Disk size in GB")build_p.add_argument("--ram", type=int, default=8192, help="RAM in MB")@@ -785,6 +789,7 @@ def main():build_p.add_argument("--wsl2", action="store_true", help="Run QEMU inside WSL2 with KVM acceleration")+ build_p.add_argument("--qemu-bin", help="Custom QEMU binary path (e.g. /opt/incus/bin/qemu-system-x86_64)")# pushpush_p = sub.add_parser("push", help="Push a qcow2 disk as OCI image")@@ -826,6 +831,7 @@ def main():ram_mb=args.ram,disk_size_gb=args.disk_size,tpm=not args.no_tpm,+ qemu_bin=getattr(args, "qemu_bin", None),)disk = build_image(cfg,diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.pyindex 2db8e167f4..97214de4dc 100644--- a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py+++ b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py@@ -18,7 +18,7 @@ from cua_sandbox.transport.http import HTTPTransportlogger = logging.getLogger(__name__)-_POLL_INTERVAL = 2.0 # seconds between status polls+_POLL_INTERVAL = 0.5 # seconds between status polls_POLL_TIMEOUT = 600.0 # max seconds to wait for VM to be running@@ -84,47 +84,116 @@ class CloudTransport(Transport):self._name = vm_info["name"]logger.debug("[cloud] created VM %r", self._name)- # Poll until running- logger.debug(- "[cloud] waiting for VM %r to be running (status=%r)", self._name, vm_info.get("status")- )- vm_info = await self._wait_for_running(vm_info)- logger.debug("[cloud] VM %r is running", self._name)-- # Resolve computer-server endpoint — auth with CUA API key + container name.- # In local-dev mode the API initially returns .cua.sh placeholder URLs and- # replaces them with direct IPs once the container IP is known, so we poll- # until we get a non-.cua.sh address. On prod the reverse-proxy .cua.sh URL- # is the real endpoint, so we skip this loop entirely.- cs_url = self._resolve_endpoint(vm_info)_is_local_dev = not self._base_url.rstrip("/").endswith("cua.sh") and ("localhost" in self._base_urlor "127.0.0.1" in self._base_urlor "0.0.0.0" in self._base_url)- poll_elapsed = 0.0- while _is_local_dev and (cs_url.endswith(".cua.sh") or ".cua.sh:" in cs_url):- if poll_elapsed >= 120:- break # Fall through — _wait_for_server_ready will handle the error- await asyncio.sleep(3)- poll_elapsed += 3- vm_info = await self._get_vm(self._name)- cs_url = self._resolve_endpoint(vm_info)- logger.debug("[cloud] re-resolving endpoint: %s (%.0fs)", cs_url, poll_elapsed)+ # ── Parallel path: resolve endpoint + probe server while waiting for "running" ──+ # The VM is booting; we can start probing its CUA server as soon as the+ # API gives us an IP-based endpoint, without waiting for the full CRD+ # status to transition to "running".++ async def _poll_until_running_and_resolved() -> tuple[dict, str]:+ """Poll VM status AND resolve a usable endpoint URL in one loop."""+ nonlocal vm_info+ elapsed = 0.0+ cs_url = ""+ is_running = vm_info.get("status") in ("running", "ready")++ while elapsed < _POLL_TIMEOUT:+ # Try to extract a direct-IP endpoint from current vm_info+ try:+ url = self._resolve_endpoint(vm_info)+ if not (_is_local_dev and (".cua.sh" in url)):+ cs_url = url+ except (ValueError, KeyError):+ pass++ if is_running and cs_url:+ return vm_info, cs_url++ await asyncio.sleep(_POLL_INTERVAL)+ elapsed += _POLL_INTERVAL+ vm_info = await self._get_vm(self._name)+ is_running = vm_info.get("status") in ("running", "ready")++ if not is_running:+ raise TimeoutError(+ f"VM {self._name!r} did not become running within {_POLL_TIMEOUT}s "+ f"(last status: {vm_info.get('status')})"+ )+ if not cs_url:+ cs_url = self._resolve_endpoint(vm_info)+ return vm_info, cs_url++ async def _connect_and_wait_ready(cs_url: str, api_key: str) -> None:+ """Create inner HTTPTransport and wait for server readiness."""+ # Forks inherit the source container's credentials from the+ # snapshot, so auth must use the source instance name.+ snap_source = getattr(self._image, "_snapshot_source", None) if self._image else None+ auth_name = snap_source["instance"] if snap_source else self._name+ self._inner = HTTPTransport(cs_url, api_key=api_key, container_name=auth_name)+ await self._inner.connect()+ await self._wait_for_server_ready()++ # Run VM status polling, endpoint resolution, and server probe in+ # parallel. As soon as the API returns a direct-IP endpoint (even+ # while CRD status is still "creating"), start TCP-probing the CUA+ # server. This overlaps the kopf handler's credential injection+ # and DNS setup with the CUA server boot.++ server_ready: asyncio.Event = asyncio.Event()+ probe_task: Optional[asyncio.Task] = None+ resolved_url: Optional[str] = None++ async def _poll_and_probe() -> tuple[dict, str]:+ """Poll VM status; start TCP/HTTP probe as soon as we have a direct IP."""+ nonlocal vm_info, probe_task, resolved_url+ elapsed = 0.0+ is_running = vm_info.get("status") in ("running", "ready")++ while elapsed < _POLL_TIMEOUT:+ # Try to extract a direct-IP endpoint+ try:+ url = self._resolve_endpoint(vm_info)+ if not (_is_local_dev and ".cua.sh" in url):+ # Got a direct IP — start probing if not already+ if probe_task is None:+ resolved_url = url+ logger.debug("[cloud] early endpoint: %s at %.1fs — starting probe", url, elapsed)+ probe_task = asyncio.create_task(+ _connect_and_wait_ready(url, api_key)+ )+ except (ValueError, KeyError):+ pass++ if is_running and resolved_url:+ return vm_info, resolved_url++ await asyncio.sleep(_POLL_INTERVAL)+ elapsed += _POLL_INTERVAL+ vm_info = await self._get_vm(self._name)+ is_running = vm_info.get("status") in ("running", "ready")++ if not is_running:+ raise TimeoutError(+ f"VM {self._name!r} did not become running within {_POLL_TIMEOUT}s "+ f"(last status: {vm_info.get('status')})"+ )+ url = resolved_url or self._resolve_endpoint(vm_info)+ return vm_info, url++ vm_info, cs_url = await _poll_and_probe()logger.debug("[cloud] resolved endpoint: %s", cs_url)- # For forks, the computer-server inside still has the source container's- # credentials (baked into the snapshot). Use the source name for auth.- snap_source = getattr(self._image, "_snapshot_source", None) if self._image else None- auth_name = snap_source["instance"] if snap_source else self._name- self._inner = HTTPTransport(cs_url, api_key=api_key, container_name=auth_name)- logger.debug("[cloud] connecting inner HTTPTransport")- await self._inner.connect()- logger.debug("[cloud] HTTPTransport connected")-- # Wait for computer-server to be reachable (it may lag behind VM "running" status)- logger.debug("[cloud] waiting for computer-server to be ready")- await self._wait_for_server_ready()++ # If probe was started early, wait for it; otherwise start now+ if probe_task is not None:+ await probe_task+ else:+ await _connect_and_wait_ready(cs_url, api_key)+logger.debug("[cloud] computer-server ready")# Apply env vars and image layers (e.g. APK installs) after server is ready@@ -321,17 +390,49 @@ class CloudTransport(Transport):return vm_infoasync def _wait_for_server_ready(self) -> None:- """Poll the computer-server until it responds (retries on connection/HTTP errors)."""+ """Poll the computer-server until it responds.++ First, quickly check if the HTTP server is accepting connections (any+ response, even 404). Then verify with get_screen_size which needs the+ emulator. This two-phase approach lets the SDK proceed as soon as the+ server process is up, overlapping with emulator boot.+ """assert self._innerelapsed = 0.0last_err: Optional[Exception] = None++ # Phase 1: wait for HTTP port to accept connections (fast — just needs+ # the Python process to start, not the emulator).+ while elapsed < _POLL_TIMEOUT:+ try:+ resp = await self._inner._client.get("/", timeout=2.0)+ # Any response means the server is up+ logger.debug("[cloud] server HTTP up (status=%d) at %.1fs", resp.status_code, elapsed)+ break+ except Exception as e:+ last_err = e+ await asyncio.sleep(_POLL_INTERVAL)+ elapsed += _POLL_INTERVAL++ # Check if this is a Windows server (no screen_size endpoint)+ try:+ status_resp = await self._inner._client.get("/status", timeout=5.0)+ if status_resp.status_code == 200:+ status_data = status_resp.json()+ if status_data.get("os_type") == "windows":+ logger.debug("[cloud] Windows server detected, skipping screen_size check")+ return # Windows servers are ready after Phase 1+ except Exception:+ pass # Fall through to Phase 2++ # Phase 2: wait for get_screen_size (needs emulator/display running)while elapsed < _POLL_TIMEOUT:try:await self._inner.get_screen_size()- return # Server is ready+ return # Fully readyexcept httpx.HTTPStatusError as e:if e.response.status_code < 500 and e.response.status_code != 404:- raise # 4xx errors (except 404) are not transient — fail fast+ raiselast_err = elogger.debug("[cloud] _wait_for_server_ready: elapsed=%.0fs err=%r", elapsed, e)await asyncio.sleep(_POLL_INTERVAL)diff --git a/libs/python/cua-sandbox/tests/test_windows_cloud.py b/libs/python/cua-sandbox/tests/test_windows_cloud.pynew file mode 100644index 0000000000..2f8e397816--- /dev/null+++ b/libs/python/cua-sandbox/tests/test_windows_cloud.py@@ -0,0 +1,111 @@+"""Windows Server E2E test using cua-sandbox SDK.++Run:+ CUA_API_KEY=sk-dev-test-key-local-12345 CUA_BASE_URL=http://localhost:8082 \+ uv run pytest tests/test_windows_cloud.py -v -s+"""++import os+import time+import sys++import pytest++from cua_sandbox import Image, Sandbox++pytestmark = pytest.mark.asyncio+P = lambda *a, **kw: print(*a, **kw, flush=True)+++def _has_env() -> bool:+ return bool(os.environ.get("CUA_API_KEY"))++[email protected](not _has_env(), reason="CUA_API_KEY not set")+async def test_windows_create_and_snapshot():+ """Image.windows('server-2025') -> Sandbox.ephemeral -> snapshot -> fork."""++ t0 = time.monotonic()++ P(f"\n Creating Sandbox with Image.windows('server-2025')...")+ async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:+ t_create = time.monotonic() - t0+ P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")++ # Try screenshot+ try:+ screen = await sb.screenshot()+ P(f" Screenshot: {len(screen)} bytes")+ except Exception as e:+ P(f" Screenshot not available: {e}")+ screen = None++ # Snapshot+ t1 = time.monotonic()+ P(f" Taking snapshot...")+ snapshot_img = await sb.snapshot()+ t_snap = time.monotonic() - t1+ P(f" Snapshot: {t_snap:.2f}s")++ # Fork from snapshot+ t2 = time.monotonic()+ P(f" Forking from snapshot...")+ async with Sandbox.ephemeral(snapshot_img, local=False) as fork:+ t_fork = time.monotonic() - t2+ P(f" Fork ready: {t_fork:.1f}s name={fork.name}")++ try:+ fork_screen = await fork.screenshot()+ P(f" Fork screenshot: {len(fork_screen)} bytes")+ except Exception as e:+ P(f" Fork screenshot not available: {e}")+ fork_screen = None++ t_total = time.monotonic() - t0+ P(f"\n === TIMINGS ===")+ P(f" Create+ready: {t_create:.1f}s")+ P(f" Snapshot: {t_snap:.2f}s")+ P(f" Fork+ready: {t_fork:.1f}s")+ P(f" Total: {t_total:.1f}s")++[email protected](not _has_env(), reason="CUA_API_KEY not set")+async def test_windows_stateful_snapshot_fork():+ """Stateful snapshot captures RAM — fork resumes instantly without rebooting."""++ t0 = time.monotonic()++ P(f"\n Creating Sandbox with Image.windows('server-2025')...")+ async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:+ t_create = time.monotonic() - t0+ P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")++ # Verify CUA server is running+ screen = await sb.screenshot()+ P(f" Screenshot: {len(screen)} bytes")++ # Stateful snapshot — captures memory state+ t1 = time.monotonic()+ P(f" Taking stateful snapshot...")+ snapshot_img = await sb.snapshot(stateful=True)+ t_snap = time.monotonic() - t1+ P(f" Stateful snapshot: {t_snap:.2f}s")++ # Fork from stateful snapshot — should resume instantly+ t2 = time.monotonic()+ P(f" Forking from stateful snapshot...")+ async with Sandbox.ephemeral(snapshot_img, local=False) as fork:+ t_fork = time.monotonic() - t2+ P(f" Fork ready: {t_fork:.1f}s name={fork.name}")++ # Fork should have CUA server immediately available (no reboot)+ fork_screen = await fork.screenshot()+ P(f" Fork screenshot: {len(fork_screen)} bytes")+ assert len(fork_screen) > 1000, "Fork screenshot should be non-trivial"++ t_total = time.monotonic() - t0+ P(f"\n === STATEFUL TIMINGS ===")+ P(f" Create+ready: {t_create:.1f}s")+ P(f" Stateful snapshot: {t_snap:.2f}s")+ P(f" Fork+ready: {t_fork:.1f}s (should be <10s with stateful)")+ P(f" Total: {t_total:.1f}s")diff --git a/libs/python/cua-sandbox/tests/test_windows_timing.py b/libs/python/cua-sandbox/tests/test_windows_timing.pynew file mode 100644index 0000000000..bea11dd5f3--- /dev/null+++ b/libs/python/cua-sandbox/tests/test_windows_timing.py@@ -0,0 +1,84 @@+"""Compare Windows VM restore timings: fresh create vs snapshot vs stateful snapshot.++Run:+ CUA_API_KEY=sk-dev-test-key-local-12345 CUA_BASE_URL=http://localhost:8082 \+ uv run pytest tests/test_windows_timing.py -v -s+"""++import os+import time++import pytest++from cua_sandbox import Image, Sandbox++pytestmark = pytest.mark.asyncio+P = lambda *a, **kw: print(*a, **kw, flush=True)+++def _has_env() -> bool:+ return bool(os.environ.get("CUA_API_KEY"))++[email protected](not _has_env(), reason="CUA_API_KEY not set")+async def test_windows_all_restore_modes():+ """Compare: Image.windows() vs snapshot() vs snapshot(stateful=True) fork times."""++ results = {}++ # ── 1. Fresh create from Image.windows("server-2025") ──+ P("\n [1/3] Creating fresh VM from Image.windows('server-2025')...")+ t0 = time.monotonic()+ async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:+ t_create = time.monotonic() - t0+ P(f" Ready in {t_create:.1f}s name={sb.name}")+ results["create"] = t_create++ screen = await sb.screenshot()+ P(f" Screenshot: {len(screen)} bytes")++ # ── 2. Non-stateful snapshot + fork ──+ P("\n [2/3] Taking non-stateful snapshot...")+ t1 = time.monotonic()+ snap_img = await sb.snapshot(stateful=False)+ t_snap = time.monotonic() - t1+ P(f" Snapshot: {t_snap:.2f}s")+ results["snapshot"] = t_snap++ P(" Forking from non-stateful snapshot...")+ t2 = time.monotonic()+ async with Sandbox.ephemeral(snap_img, local=False) as fork1:+ t_fork1 = time.monotonic() - t2+ P(f" Fork ready: {t_fork1:.1f}s name={fork1.name}")+ results["fork_nonstateful"] = t_fork1++ fork1_screen = await fork1.screenshot()+ P(f" Screenshot: {len(fork1_screen)} bytes")++ # ── 3. Stateful snapshot + fork ──+ P("\n [3/3] Taking stateful snapshot...")+ t3 = time.monotonic()+ snap_stateful = await sb.snapshot(stateful=True)+ t_snap_s = time.monotonic() - t3+ P(f" Stateful snapshot: {t_snap_s:.2f}s")+ results["snapshot_stateful"] = t_snap_s++ P(" Forking from stateful snapshot...")+ t4 = time.monotonic()+ async with Sandbox.ephemeral(snap_stateful, local=False) as fork2:+ t_fork2 = time.monotonic() - t4+ P(f" Fork ready: {t_fork2:.1f}s name={fork2.name}")+ results["fork_stateful"] = t_fork2++ fork2_screen = await fork2.screenshot()+ P(f" Screenshot: {len(fork2_screen)} bytes")++ P(f"\n {'='*50}")+ P(f" TIMING COMPARISON")+ P(f" {'='*50}")+ P(f" Image.windows() create: {results['create']:6.1f}s")+ P(f" snapshot(stateful=False): {results['snapshot']:6.2f}s")+ P(f" fork from non-stateful: {results['fork_nonstateful']:6.1f}s")+ P(f" snapshot(stateful=True): {results['snapshot_stateful']:6.2f}s")+ P(f" fork from stateful: {results['fork_stateful']:6.1f}s")+ P(f" {'='*50}")