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(sandbox): add pwa2apk as default PWA APK builder (#1247)

ddupont98428c84c22f
diff --git a/examples/sandboxes/test_android_local_gym_pwa.py b/examples/sandboxes/test_android_local_gym_pwa.py
index d12aee182b..e3f6fd24fa 100644
--- a/examples/sandboxes/test_android_local_gym_pwa.py
+++ b/examples/sandboxes/test_android_local_gym_pwa.py
@@ -101,6 +101,7 @@ async def test_android_local_gym_pwa():
TWA_MANIFEST_URL,
package_name=TWA_PACKAGE,
keystore=str(GYM_KEYSTORE),
+ builder="bubblewrap", # needs Chrome TWA for DevTools Protocol
),
local=True,
) as sb:
@@ -222,6 +223,7 @@ async def main():
TWA_MANIFEST_URL,
package_name=TWA_PACKAGE,
keystore=str(GYM_KEYSTORE),
+ builder="bubblewrap", # needs Chrome TWA for DevTools Protocol
),
local=True,
) as sb:
diff --git a/libs/python/cua-sandbox/cua_sandbox/image.py b/libs/python/cua-sandbox/cua_sandbox/image.py
index 130407c95e..18bf84048e 100644
--- a/libs/python/cua-sandbox/cua_sandbox/image.py
+++ b/libs/python/cua-sandbox/cua_sandbox/image.py
@@ -291,31 +291,39 @@ class Image:
keystore: Optional[str] = None,
keystore_alias: str = "android",
keystore_password: str = "android",
+ builder: str = "pwa2apk",
) -> "Image":
- """Build an APK from a PWA manifest URL via Bubblewrap and install it (Android only).
+ """Build an APK from a PWA manifest URL and install it (Android only).
- Bubblewrap reads the Web App Manifest at *manifest_url*, generates a
- Trusted Web Activity (TWA) APK signed with *keystore*, and installs it
- via adb. The keystore's SHA-256 fingerprint must match what the server
- serves from ``/.well-known/assetlinks.json`` so Chrome trusts the TWA
- and skips the browser UI entirely.
+ Two builder backends are supported:
+
+ * ``"pwa2apk"`` (default) — generates a lightweight WebView-based APK.
+ No Chrome dependency, no "Running in Chrome" banner, no Digital Asset
+ Links needed. ~10 KB APK.
+ * ``"bubblewrap"`` — generates a Chrome Trusted Web Activity (TWA) APK.
+ Requires Chrome on the device and a matching
+ ``/.well-known/assetlinks.json`` on the server. Shows a mandatory
+ "Running in Chrome" privacy disclosure on every launch.
Args:
- manifest_url: Full URL to the PWA's ``manifest.json``.
+ manifest_url: Full URL to the PWA's ``manifest.json`` or
+ ``manifest.webmanifest``.
Example: ``"http://10.0.2.2:3000/manifest.json"``
package_name: Android package ID. Defaults to a reversed-hostname
derivation (e.g. ``"com.example.app"``).
keystore: Path to a ``*.keystore`` / ``*.jks`` file. When
- omitted a fresh keystore is generated and cached under
- ``~/.cua/cua-sandbox/pwa-cache/``. Pass the keystore
- bundled with your PWA repo so the fingerprint is
- deterministic and pre-loaded into ``assetlinks.json``.
+ omitted a fresh keystore is generated and cached.
+ Pass the keystore bundled with your PWA repo so the
+ fingerprint is deterministic.
keystore_alias: Key alias inside the keystore (default ``"android"``).
keystore_password: Password for both the store and the key
(default ``"android"``).
+ builder: ``"pwa2apk"`` (default) or ``"bubblewrap"``.
"""
+ if builder not in ("pwa2apk", "bubblewrap"):
+ raise ValueError(f"builder must be 'pwa2apk' or 'bubblewrap', got {builder!r}")
self._check_os("pwa_install")
- layer: dict = {"type": "pwa_install", "manifest_url": manifest_url}
+ layer: dict = {"type": "pwa_install", "manifest_url": manifest_url, "builder": builder}
if package_name:
layer["package_name"] = package_name
if keystore:
@@ -404,14 +412,22 @@ class Image:
lines.append(f"adb install {apk}")
elif lt == "pwa_install":
manifest_url = layer["manifest_url"]
- lines.append(
- # Install bubblewrap CLI (once), init a TWA project from the
- # manifest URL, build a debug APK, then install it via adb.
- f"npm install -g @bubblewrap/cli 2>/dev/null || true\n"
- f"_BWW_DIR=$(mktemp -d)\n"
- f"(cd \"$_BWW_DIR\" && bubblewrap init --manifest '{manifest_url}' --directory . --skipPwaValidation && bubblewrap build --skipSigning)\n"
- f'adb install "$_BWW_DIR/app-release-unsigned.apk"'
- )
+ builder = layer.get("builder", "pwa2apk")
+ if builder == "pwa2apk":
+ lines.append(
+ f"# pwa2apk: WebView APK (no Chrome dependency)\n"
+ f"if [ ! -d /tmp/pwa2apk ]; then git clone https://github.com/trycua/pwa2apk.git /tmp/pwa2apk; fi\n"
+ f"node /tmp/pwa2apk/src/cli.js '{manifest_url}' --output /tmp/pwa.apk\n"
+ f"adb install /tmp/pwa.apk"
+ )
+ else:
+ lines.append(
+ f"# bubblewrap: Chrome TWA APK\n"
+ f"npm install -g @bubblewrap/cli 2>/dev/null || true\n"
+ f"_BWW_DIR=$(mktemp -d)\n"
+ f"(cd \"$_BWW_DIR\" && bubblewrap init --manifest '{manifest_url}' --directory . --skipPwaValidation && bubblewrap build --skipSigning)\n"
+ f'adb install "$_BWW_DIR/app-release-unsigned.apk"'
+ )
elif lt == "run":
lines.append(layer["command"])
return "\n".join(lines) + "\n"
diff --git a/libs/python/cua-sandbox/cua_sandbox/runtime/_bw_init.js b/libs/python/cua-sandbox/cua_sandbox/runtime/_bw_init.js
index 12c4e44b8c..8287cafe68 100644
--- a/libs/python/cua-sandbox/cua_sandbox/runtime/_bw_init.js
+++ b/libs/python/cua-sandbox/cua_sandbox/runtime/_bw_init.js
@@ -67,6 +67,35 @@ const resolvedFetchUrl =
twa.manifestUrl = manifestUrl;
twa.signingKey = { path: KEYSTORE, alias: KEYSTORE_ALIAS };
+ // If the maskable icon is a PNG that 404s but an SVG variant exists,
+ // fall back to the SVG so bubblewrap update doesn't fail on missing icons.
+ if (twa.maskableIconUrl && twa.maskableIconUrl.endsWith('.png')) {
+ try {
+ const { execFileSync } = require('child_process');
+ const status = execFileSync(
+ 'curl', ['-s', '-o', '/dev/null', '-w', '%{http_code}', '--', twa.maskableIconUrl],
+ { timeout: 10000 }
+ )
+ .toString()
+ .trim();
+ if (status === '404') {
+ const svgUrl = twa.maskableIconUrl.replace(/\.png$/, '.svg');
+ const svgStatus = execFileSync(
+ 'curl', ['-s', '-o', '/dev/null', '-w', '%{http_code}', '--', svgUrl],
+ { timeout: 10000 }
+ )
+ .toString()
+ .trim();
+ if (svgStatus === '200') {
+ console.log(`Maskable icon PNG 404d, falling back to SVG: ${svgUrl}`);
+ twa.maskableIconUrl = svgUrl;
+ }
+ }
+ } catch (_) {
+ // best-effort — ignore curl failures
+ }
+ }
+
const outFile = path.join(outputDir, 'twa-manifest.json');
const json = twa.toJson();
json.signingKey = {
diff --git a/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py b/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
index 4d26b062bc..1d4638bf44 100644
--- a/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
+++ b/libs/python/cua-sandbox/cua_sandbox/runtime/android_emulator.py
@@ -412,13 +412,23 @@ class AndroidEmulatorRuntime(Runtime):
ks = Path(layer["keystore"]) if layer.get("keystore") else None
ks_alias = layer.get("keystore_alias", "android")
ks_pass = layer.get("keystore_password", "android")
- apk_path, fingerprint = await self._build_pwa_apk(
- manifest_url, pkg, ks, ks_alias, ks_pass
- )
+ builder = layer.get("builder", "pwa2apk")
+
+ if builder == "pwa2apk":
+ # Import cloud transport's pwa2apk builder (works without a sandbox)
+ from cua_sandbox.transport.cloud import CloudTransport
+
+ apk_path, fingerprint = await CloudTransport._build_pwa2apk(
+ manifest_url, pkg, ks, ks_alias, ks_pass
+ )
+ else:
+ apk_path, fingerprint = await self._build_pwa_apk(
+ manifest_url, pkg, ks, ks_alias, ks_pass
+ )
+
logger.info(
- f"PWA APK signing fingerprint (SHA-256): {fingerprint}\n"
- " → Set TWA_SHA256_FINGERPRINT env var on your server to this value\n"
- f" so /.well-known/assetlinks.json is trusted by Chrome."
+ f"PWA APK built ({builder}): {apk_path}\n"
+ f" SHA-256 fingerprint: {fingerprint}"
)
logger.info(f"Installing PWA APK: {apk_path}")
result = subprocess.run(
@@ -432,21 +442,26 @@ class AndroidEmulatorRuntime(Runtime):
logger.warning(f"PWA APK install failed: {result.stderr}")
else:
logger.info(f"PWA APK installed: {result.stdout.strip()}")
- # Suppress Chrome first-run wizard so the TWA opens immediately.
- # set-debug-app makes Chrome honour the chrome-command-line file.
- for cmd in [
- "am set-debug-app --persistent com.android.chrome",
- "mkdir -p /data/local/tmp && "
- "echo 'chrome --no-first-run --disable-fre "
- "--no-default-browser-check' "
- "> /data/local/tmp/chrome-command-line",
- ]:
- subprocess.run(
- [adb, "-s", serial, "shell", cmd],
- capture_output=True,
- env=env,
- timeout=10,
- )
+
+ # For bubblewrap TWA, set Chrome flags. pwa2apk doesn't need this.
+ if builder == "bubblewrap":
+ from urllib.parse import urlparse
+
+ origin = f"{urlparse(manifest_url).scheme}://{urlparse(manifest_url).netloc}"
+ for cmd in [
+ "am set-debug-app --persistent com.android.chrome",
+ "mkdir -p /data/local/tmp && "
+ "echo 'chrome --no-first-run --disable-fre "
+ "--no-default-browser-check "
+ f"--disable-digital-asset-link-verification-for-url=\"{origin}\"' "
+ "> /data/local/tmp/chrome-command-line",
+ ]:
+ subprocess.run(
+ [adb, "-s", serial, "shell", cmd],
+ capture_output=True,
+ env=env,
+ timeout=10,
+ )
elif lt == "run":
cmd = layer["command"]
logger.info(f"Running: {cmd}")
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
index 384b52670b..55c8717cc4 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
@@ -408,33 +408,39 @@ class CloudTransport(Transport):
)
async def _install_pwa(self, layer: dict) -> None:
- """Build PWA APK on the host using bubblewrap, then push and install.
+ """Build PWA APK on the host, then push and install.
- Auto-installs Android SDK and bubblewrap if not present (same as local runtime).
+ Supports two builders:
+ - "pwa2apk" (default): WebView-based APK, no Chrome dependency or banners.
+ - "bubblewrap": Chrome TWA APK, requires asset links and shows Chrome disclosure.
"""
import base64
from pathlib import Path
- from cua_sandbox.runtime.android_emulator import (
- AndroidEmulatorRuntime,
- _ensure_sdk,
- )
-
- # Ensure Android SDK is available (auto-installs if missing)
- _ensure_sdk()
-
+ builder = layer.get("builder", "pwa2apk")
manifest_url = layer["manifest_url"]
pkg = layer.get("package_name")
ks = Path(layer["keystore"]) if layer.get("keystore") else None
ks_alias = layer.get("keystore_alias", "android")
ks_pass = layer.get("keystore_password", "android")
- # Build APK on host (auto-installs bubblewrap via npm if missing)
- runtime = AndroidEmulatorRuntime.__new__(AndroidEmulatorRuntime)
- apk_path, fingerprint = await runtime._build_pwa_apk(
- manifest_url, pkg, ks, ks_alias, ks_pass
- )
- logger.info(f"[cloud] PWA APK built: {apk_path} (fingerprint: {fingerprint})")
+ if builder == "pwa2apk":
+ apk_path, fingerprint = await self._build_pwa2apk(
+ manifest_url, pkg, ks, ks_alias, ks_pass
+ )
+ else:
+ from cua_sandbox.runtime.android_emulator import (
+ AndroidEmulatorRuntime,
+ _ensure_sdk,
+ )
+
+ _ensure_sdk()
+ runtime = AndroidEmulatorRuntime.__new__(AndroidEmulatorRuntime)
+ apk_path, fingerprint = await runtime._build_pwa_apk(
+ manifest_url, pkg, ks, ks_alias, ks_pass
+ )
+
+ logger.info(f"[cloud] PWA APK built ({builder}): {apk_path} (fingerprint: {fingerprint})")
apk_bytes = Path(apk_path).read_bytes()
dest = "/data/local/tmp/cua_pwa.apk"
@@ -448,14 +454,150 @@ class CloudTransport(Transport):
command=f"pm install -r {dest} 2>&1; true",
timeout=120,
)
- # Suppress Chrome first-run wizard for TWA
- for cmd in [
- "am set-debug-app --persistent com.android.chrome",
- "mkdir -p /data/local/tmp && "
- "echo 'chrome --no-first-run --disable-fre --no-default-browser-check' "
- "> /data/local/tmp/chrome-command-line",
+
+ # For bubblewrap TWA, suppress Chrome first-run and set asset link bypass.
+ # For pwa2apk WebView, none of this is needed.
+ if builder == "bubblewrap":
+ from urllib.parse import urlparse
+
+ origin = f"{urlparse(manifest_url).scheme}://{urlparse(manifest_url).netloc}"
+ for cmd in [
+ "am set-debug-app --persistent com.android.chrome",
+ "mkdir -p /data/local/tmp && "
+ "echo 'chrome --no-first-run --disable-fre --no-default-browser-check "
+ f"--disable-digital-asset-link-verification-for-url=\"{origin}\"' "
+ "> /data/local/tmp/chrome-command-line",
+ ]:
+ await self._inner.send("run_command", command=cmd, timeout=10)
+
+ @staticmethod
+ async def _build_pwa2apk(
+ manifest_url: str,
+ package_name: str | None = None,
+ keystore_path: "Path | None" = None,
+ keystore_alias: str = "android",
+ keystore_password: str = "android",
+ ) -> tuple:
+ """Build a WebView-based APK using pwa2apk (no Chrome dependency)."""
+ import shutil
+ import subprocess
+
+ node = shutil.which("node")
+ if not node:
+ raise RuntimeError("node not found on PATH; required for pwa2apk")
+
+ # Find pwa2apk — check common locations
+ pwa2apk_cli = None
+ for candidate in [
+ shutil.which("pwa2apk"),
+ # npm global
+ *([] if not shutil.which("npm") else []),
]:
- await self._inner.send("run_command", command=cmd, timeout=10)
+ if candidate:
+ pwa2apk_cli = candidate
+ break
+
+ # Fall back to requiring it as a node module
+ if not pwa2apk_cli:
+ # Try npx
+ npx = shutil.which("npx")
+ if npx:
+ pwa2apk_cli = npx
+
+ # Build via the pwa2apk Node API directly
+ import hashlib
+ import json
+ from pathlib import Path
+
+ # Check if pwa2apk is installed globally or locally
+ pwa2apk_dir = None
+ for p in [
+ Path.home() / ".cua" / "pwa2apk",
+ Path("/tmp/pwa2apk"),
+ ]:
+ if (p / "src" / "index.js").exists():
+ pwa2apk_dir = p
+ break
+
+ if not pwa2apk_dir:
+ # Auto-clone pwa2apk
+ logger.info("Cloning pwa2apk...")
+ pwa2apk_dir = Path.home() / ".cua" / "pwa2apk"
+ pwa2apk_dir.mkdir(parents=True, exist_ok=True)
+ clone_result = subprocess.run(
+ ["git", "clone", "https://github.com/trycua/pwa2apk.git", str(pwa2apk_dir)],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ if clone_result.returncode != 0:
+ raise RuntimeError(
+ f"Failed to clone pwa2apk: {clone_result.stderr}"
+ )
+
+ # Build the args for the CLI
+ import os
+
+ cache_key = hashlib.sha256(
+ f"{manifest_url}|{package_name or ''}".encode()
+ ).hexdigest()[:12]
+ output_apk = Path.home() / ".cua" / "pwa2apk-cache" / f"{cache_key}.apk"
+ output_apk.parent.mkdir(parents=True, exist_ok=True)
+
+ cmd = [
+ node,
+ str(pwa2apk_dir / "src" / "cli.js"),
+ manifest_url,
+ "--output", str(output_apk),
+ ]
+ if package_name:
+ cmd.extend(["--package", package_name])
+ if keystore_path:
+ cmd.extend(["--keystore", str(keystore_path)])
+ cmd.extend(["--keystore-alias", keystore_alias])
+ cmd.extend(["--keystore-password", keystore_password])
+
+ env = {**os.environ}
+ if "JAVA_HOME" not in env:
+ for jdk in [
+ # Linux
+ "/usr/lib/jvm/java-17-openjdk-amd64",
+ "/usr/lib/jvm/java-21-openjdk-amd64",
+ # macOS (Homebrew ARM)
+ "/opt/homebrew/opt/openjdk/libexec/openjdk.jdk/Contents/Home",
+ "/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home",
+ # macOS (Homebrew Intel)
+ "/usr/local/opt/openjdk/libexec/openjdk.jdk/Contents/Home",
+ "/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home",
+ ]:
+ if Path(jdk).exists():
+ env["JAVA_HOME"] = jdk
+ break
+
+ logger.info(f"Building APK with pwa2apk: {manifest_url}")
+ result = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=300,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(
+ f"pwa2apk build failed:\nstdout: {result.stdout}\nstderr: {result.stderr}"
+ )
+
+ # Extract fingerprint from output
+ fingerprint = ""
+ for line in result.stdout.splitlines():
+ if "SHA-256:" in line:
+ fingerprint = line.split("SHA-256:", 1)[1].strip()
+ break
+
+ if not output_apk.exists():
+ raise RuntimeError(f"pwa2apk did not produce APK at {output_apk}")
+
+ return output_apk, fingerprint
@staticmethod
def _resolve_endpoint(vm_info: dict) -> str:
diff --git a/libs/python/cua-sandbox/uv.lock b/libs/python/cua-sandbox/uv.lock
index 1fcf42ddfb..8358b604e8 100644
--- a/libs/python/cua-sandbox/uv.lock
+++ b/libs/python/cua-sandbox/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 2
+revision = 3
requires-python = ">=3.11, <3.14"
[[package]]
@@ -531,7 +531,7 @@ dev = [{ name = "pytest", specifier = ">=8.3.5" }]
[[package]]
name = "cua-sandbox"
-version = "0.1.2"
+version = "0.1.3"
source = { editable = "." }
dependencies = [
{ name = "cua-auto" },