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
test(cua-driver): add canonical perception capture-loop E2E rows (#4192)
Francesco Bonacci5a3994be1ddf
diff --git a/libs/cua-driver/docs/test-harnesses-guide.md b/libs/cua-driver/docs/test-harnesses-guide.mdindex 94d79f39cd..b748a23797 100644--- a/libs/cua-driver/docs/test-harnesses-guide.md+++ b/libs/cua-driver/docs/test-harnesses-guide.md@@ -629,7 +629,7 @@ Scripts and their tests live next to their owner:harness apps, not a test directory. The fixture build scripts `cd` into it,so its tracked README and `.gitignore` must stay.-Perception tests have three owners, and each tests different code:+Perception tests have four owners, and each tests different code:| Directory | Owns | Run by || --- | --- | --- |@@ -637,5 +637,6 @@ Perception tests have three owners, and each tests different code:| `libs/cua-driver/rust/crates/cua-perception/scripts/tests/` | Model artifact tooling and quality measurement scripts | `ci-cua-perception-release.yml` || `libs/cua-driver/tests/perception-demo/` | Visual demo evidence sanitizing, caching, and envelopes | `ci-test-scripts.yml` || `.github/scripts/tests/test_cua_perception_*.py`, `test_perception_release.py` | Perception release, review-trigger, and review-pipeline workflows and `.github/scripts` helpers | `ci-test-scripts.yml`, `ci-cua-perception-release.yml` |+| `libs/cua-driver/rust/crates/cua-driver-e2e/tests/perception_capture_loop_test.rs` | Driver's desktop capture, parse, capture-bound click, and reobserve loop with a deterministic developer-only worker | Capture lane of the canonical macOS, Windows, and Linux X11 desktop E2E |Add a perception test to the directory that owns the code it exercises.diff --git a/libs/cua-driver/docs/test-matrix.md b/libs/cua-driver/docs/test-matrix.mdindex 89f7669d11..5b3f4cba21 100644--- a/libs/cua-driver/docs/test-matrix.md+++ b/libs/cua-driver/docs/test-matrix.md@@ -100,6 +100,26 @@ Canonical reporting rejects skips and enforces the complete shared catalogsize for unfiltered runs. Diagnostic filters are allowed, but matching zerocells is always an error.+## Harness E2E: Optional Perception Loop++`perception_capture_loop_test.rs` runs the documented capture-bound loop+against the shared web harness in Electron in the capture lane of the macOS,+Windows, and Linux X11 runners:++| Cell | Coverage |+| --- | --- |+| `<os>-electron-parse-visual-regions-not-installed-not-applicable-not-applicable` | A retained window capture parses to the typed `not_installed` refusal when no extension is installed |+| `<os>-electron-perception-capture-click-px-foreground` | `get_window_state` capture, `parse_visual_regions` on that capture, one foreground `click` with the same `capture_id` at the parsed region center, fixture-journal delivery oracle, `capture_not_found` refusal for the consumed capture, then a fresh capture and reparse |++The installed extension is a developer-only unsigned worker compiled from+`tests/support/perception_swatch_worker.rs`. It speaks the real worker+protocol inside Driver's containment, echoes the retained PNG digest, and finds+the harness's solid `#drag-source` and `#drop-target` swatches in the captured+pixels, so the row needs no published artifact or model. macOS runs a second+instance of the installed app with an isolated extension home and socket.+Wayland lanes record a coverage limitation instead of running the row. Model+quality belongs to the `cua-perception` crate and its artifact-gated lanes.+## Harness E2E: Native WindowsWindows native harnesses are repo-local applications built from source:diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex 5fdbc68038..1141e17db3 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -1306,6 +1306,7 @@ dependencies = ["cua-driver-sdk","cua-driver-testkit","cursor-overlay",+ "flate2","futures-util","image","jsonschema",@@ -1315,6 +1316,7 @@ dependencies = ["serde","serde_json","sha2",+ "tar","tempfile","tokio","tokio-tungstenite",diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.tomlindex 168be52523..c3beb702f3 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml@@ -35,6 +35,8 @@ serde_json = { workspace = true }sha2 = { workspace = true }image = { workspace = true }base64 = { workspace = true }+flate2 = "1"+tar = { version = "0.4", default-features = false }tokio = { workspace = true, features = ["full"] }jsonschema = { version = "0.46", default-features = false }tempfile = "3"diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/README.md b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/README.mdindex c7c8640b97..4eb35942b7 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/README.md+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/README.md@@ -29,6 +29,7 @@ action, addressing mode, delivery mode, or OS-specific window-system case.| `cross_platform_behavior_test.rs` | Shared Electron/Tauri/WKWebView action matrix || `desktop_scope_<os>_test.rs` | Platform window/desktop scope contract || `installed_app_*_test.rs`, `standalone_browser_behavior_test.rs` | Installed apps and browsers |+| `perception_capture_loop_test.rs` | Optional perception capture, parse, capture-bound click, and reobserve loop || `*_<os>_test.rs`, `hyprland_*_test.rs`, `wayland_*_test.rs` | Platform- or compositor-specific desktop rows |## Harness Requirementsdiff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/perception_capture_loop_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/perception_capture_loop_test.rsnew file mode 100644index 0000000000..78b94b396c--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/perception_capture_loop_test.rs@@ -0,0 +1,985 @@+//! Canonical desktop rows for the optional perception loop.+//!+//! The documented loop is `get_window_state` (retain `capture_id`) ->+//! `parse_visual_regions` -> one capture-bound `click` with the same+//! `capture_id` -> reobserve. These rows drive it against the shared web+//! harness in Electron, which every supported desktop runner builds.+//!+//! No published artifact or model is required. The installed extension is a+//! deterministic, developer-only unsigned worker compiled from+//! `support/perception_swatch_worker.rs`. It speaks the real framed worker+//! protocol, runs inside Driver's normal worker containment, receives the exact+//! PNG Driver retained for the capture, and derives regions from those pixels by+//! finding the harness's solid color swatches. Model quality is covered by the+//! cua-perception crate; these rows certify Driver's capture, parse, action+//! binding, and single-use refusal contract on each desktop.+//!+//! The fixture's loopback journal is the delivery oracle, independent of the+//! Driver response. macOS runs a dedicated instance of the installed,+//! TCC-authorized app with an isolated extension home, so the shared daemon's+//! state is never changed.+//!+//! ```text+//! cargo test -p cua-driver-e2e --test perception_capture_loop_test -- \+//! --ignored --nocapture --test-threads=1+//! ```++#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]++use std::fs;+use std::io::Cursor;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::thread;+use std::time::{Duration, Instant};++use cua_driver_testkit::e2e::{+ execute_case, native_readonly_case, recording_evidence, shared_web_route, CaseSpec, Delivery,+ DisplayServer, DriverRoute, Evidence, Observation, OracleKind, Platform, Scope, Targeting,+};+use cua_driver_testkit::{+ driver_binary, ensure_driver_binary, harness_app, spawn_in_job, Driver, FixtureJournal,+ McpDriver, ToolResponse,+};+use flate2::{write::GzEncoder, Compression};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};++const WORKER_SOURCE: &str = include_str!("support/perception_swatch_worker.rs");+const EXTENSION_VERSION: &str = "0.0.0-e2e-swatch";+const TARGET_REGION: &str = "swatch-drag-source";+const FIXTURE_TITLE: &str = "CuaTestHarness Electron";++// ---------------------------------------------------------------- extension++fn current_target() -> String {+ let suffix = if cfg!(target_os = "macos") {+ "apple-darwin"+ } else if cfg!(all(target_os = "windows", target_env = "msvc")) {+ "pc-windows-msvc"+ } else if cfg!(all(target_os = "linux", target_env = "musl")) {+ "unknown-linux-musl"+ } else if cfg!(all(target_os = "linux", target_env = "gnu")) {+ "unknown-linux-gnu"+ } else {+ panic!("unsupported perception E2E target")+ };+ format!("{}-{suffix}", std::env::consts::ARCH)+}++fn sha256(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+}++fn worker_file_name() -> &'static str {+ if cfg!(windows) {+ "cua-perception.exe"+ } else {+ "cua-perception"+ }+}++/// Compile the swatch worker with plain `rustc`. Linux containment cannot+/// expose a host dynamic loader to an installed worker, and release Windows+/// builds link the C runtime statically, so both link it statically here.+fn compile_worker(directory: &Path) -> PathBuf {+ let source = directory.join("perception_swatch_worker.rs");+ fs::write(&source, WORKER_SOURCE).expect("write swatch worker source");+ let worker = directory.join(worker_file_name());+ let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());+ let mut command = Command::new(rustc);+ command.arg(&source).args(["--edition=2021", "-O"]);+ if cfg!(any(target_os = "linux", target_os = "windows")) {+ command.args(["-C", "target-feature=+crt-static"]);+ }+ if cfg!(target_os = "linux") {+ if let Some(path) = std::env::var_os("CUA_TEST_GLIBC_STATIC_LIB") {+ let mut native_path = std::ffi::OsString::from("native=");+ native_path.push(path);+ command.arg("-L").arg(native_path);+ }+ }+ let output = command+ .arg("-o")+ .arg(&worker)+ .output()+ .expect("run rustc for the swatch worker");+ assert!(+ output.status.success(),+ "swatch worker compilation failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ worker+}++fn append(builder: &mut tar::Builder<GzEncoder<fs::File>>, path: &str, bytes: &[u8]) {+ let mut header = tar::Header::new_gnu();+ header.set_size(bytes.len() as u64);+ header.set_mode(0o755);+ header.set_cksum();+ builder+ .append_data(&mut header, path, Cursor::new(bytes))+ .expect("append extension archive entry");+}++/// Assemble the developer-only archive accepted by+/// `cua-driver extension install --archive <tar.gz> --allow-unsigned-local`.+/// The model, runtime, and dictionary entries are inert placeholders that+/// satisfy the runtime contract; the swatch worker never loads them.+fn swatch_extension_archive(directory: &Path) -> PathBuf {+ let worker = fs::read(compile_worker(directory)).expect("read compiled swatch worker");+ let entrypoint = format!("bin/{}", worker_file_name());+ let runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let runtime = b"e2e placeholder runtime; never loaded".to_vec();+ let model = b"e2e placeholder model; never loaded".to_vec();+ let dictionary = b"e2e placeholder dictionary".to_vec();+ let model_manifest = b"{}".to_vec();+ let contract = serde_json::to_vec_pretty(&json!({+ "$schema": "runtime-contract.schema.json",+ "schemaVersion": 1,+ "target": current_target(),+ "protocolVersion": 1,+ "worker": {"name": worker_file_name(), "sha256": sha256(&worker)},+ "runtime": {"name": runtime_name, "sha256": sha256(&runtime)},+ "modelManifest": {"name": "model-manifest.json", "sha256": sha256(&model_manifest)},+ "models": [+ {"name": "icon.onnx", "role": "icon-detect", "sha256": sha256(&model)},+ {"name": "ocr-det.onnx", "role": "ocr-detect", "sha256": sha256(&model)},+ {"name": "ocr-rec.onnx", "role": "ocr-recognize", "sha256": sha256(&model)}+ ],+ "dictionary": {"name": "dictionary.txt", "role": "ocr-dictionary", "sha256": sha256(&dictionary)},+ "rejectMismatch": true+ }))+ .unwrap();+ let files = vec![+ (entrypoint.clone(), worker, true),+ (+ "models/model-manifest.json".to_owned(),+ model_manifest,+ false,+ ),+ (format!("runtime/{runtime_name}"), runtime, false),+ ("models/icon.onnx".to_owned(), model.clone(), false),+ ("models/ocr-det.onnx".to_owned(), model.clone(), false),+ ("models/ocr-rec.onnx".to_owned(), model, false),+ ("models/dictionary.txt".to_owned(), dictionary, false),+ ("metadata/runtime-contract.json".to_owned(), contract, false),+ (+ "LICENSES/NOTICE.txt".to_owned(),+ b"Cua E2E swatch worker; test support only.\n".to_vec(),+ false,+ ),+ (+ "LICENSES/model.txt".to_owned(),+ b"No model is distributed with the E2E swatch worker.\n".to_vec(),+ false,+ ),+ (+ "SOURCE/swatch-worker.rs".to_owned(),+ WORKER_SOURCE.as_bytes().to_vec(),+ false,+ ),+ ];+ let hash_of = |path: &str| {+ files+ .iter()+ .find(|(candidate, _, _)| candidate == path)+ .map(|(_, bytes, _)| sha256(bytes))+ .expect("archive file is declared")+ };+ let manifest = serde_json::to_vec_pretty(&json!({+ "schema_version": 1,+ "id": "cua-perception",+ "version": EXTENSION_VERSION,+ "driver_version": format!("={}", env!("CARGO_PKG_VERSION")),+ "protocol_version": 1,+ "target": current_target(),+ "entrypoint": entrypoint,+ "files": files.iter().map(|(path, bytes, executable)| {+ json!({"path": path, "sha256": sha256(bytes), "executable": executable})+ }).collect::<Vec<_>>(),+ "models": [{+ "path": "models/icon.onnx",+ "revision": "e2e-swatch-v1",+ "original_sha256": hash_of("models/icon.onnx"),+ "conversion_sha256": hash_of("models/icon.onnx"),+ "license_file": {"path": "LICENSES/model.txt", "sha256": hash_of("LICENSES/model.txt")}+ }],+ "components": [{+ "name": "cua-perception-e2e-swatch-worker",+ "version": EXTENSION_VERSION,+ "license": "MIT",+ "notice": "Cua E2E swatch worker; test support only",+ "source_uri": "https://github.com/trycua/cua",+ "source_revision": "e2e-swatch",+ "notice_file": {"path": "LICENSES/NOTICE.txt", "sha256": hash_of("LICENSES/NOTICE.txt")}+ }],+ "corresponding_source_file": {+ "path": "SOURCE/swatch-worker.rs",+ "sha256": hash_of("SOURCE/swatch-worker.rs")+ },+ "license": "MIT",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": "https://github.com/trycua/cua",+ "corresponding_source_revision": "e2e-swatch",+ "provenance": "cua-driver-e2e deterministic swatch worker",+ "health_args": [],+ "self_test_args": []+ }))+ .unwrap();++ let archive = directory.join("cua-perception-e2e-swatch.tar.gz");+ let encoder = GzEncoder::new(+ fs::File::create(&archive).expect("create extension archive"),+ Compression::default(),+ );+ let mut builder = tar::Builder::new(encoder);+ append(&mut builder, "extension.json", &manifest);+ for (path, bytes, _) in &files {+ append(&mut builder, path, bytes);+ }+ builder+ .into_inner()+ .and_then(|encoder| encoder.finish())+ .expect("finish extension archive");+ archive+}++/// Driver binary that owns the extension lifecycle for the daemon under test.+/// macOS certifies the installed app; other desktops run the source build.+fn lifecycle_binary() -> PathBuf {+ #[cfg(target_os = "macos")]+ {+ installed_macos_binary()+ }+ #[cfg(not(target_os = "macos"))]+ {+ driver_binary()+ }+}++fn run_extension_command(binary: &Path, home: &Path, args: &[&str]) -> std::process::Output {+ Command::new(binary)+ .args(args)+ .env("CUA_DRIVER_RS_HOME", home)+ .env("CUA_DRIVER_CLI_TELEMETRY_CHILD", "1")+ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "false")+ .stdin(Stdio::null())+ .output()+ .expect("run cua-driver extension command")+}++fn install_swatch_extension(binary: &Path, home: &Path, scratch: &Path) {+ let archive = swatch_extension_archive(scratch);+ let archive = archive.to_str().expect("UTF-8 archive path");+ let install = run_extension_command(+ binary,+ home,+ &[+ "extension",+ "install",+ "cua-perception",+ "--archive",+ archive,+ "--allow-unsigned-local",+ ],+ );+ assert!(+ install.status.success(),+ "developer-unsigned extension install failed: stdout={} stderr={}",+ String::from_utf8_lossy(&install.stdout),+ String::from_utf8_lossy(&install.stderr)+ );+ let status = run_extension_command(+ binary,+ home,+ &["extension", "status", "cua-perception", "--json"],+ );+ assert!(+ status.status.success(),+ "extension status failed: {}",+ String::from_utf8_lossy(&status.stderr)+ );+ let status: Value = serde_json::from_slice(&status.stdout).expect("extension status JSON");+ assert_eq!(status["installed"], true, "extension status: {status}");+ assert_eq!(+ status["trust"], "developer-unsigned-local",+ "the E2E worker must never be represented as publisher-verified: {status}"+ );+ assert_eq!(status["active_version"], EXTENSION_VERSION);+}++/// Fresh private directory used as `CUA_DRIVER_RS_HOME` for one row. Windows+/// uses a real child of the user profile, like the reviewed extension lanes,+/// so worker containment never sees a short-name temporary path.+fn extension_home() -> tempfile::TempDir {+ let builder = {+ let mut builder = tempfile::Builder::new();+ builder.prefix("cua-perception-e2e-home-");+ builder+ };+ #[cfg(target_os = "windows")]+ let home = builder+ .tempdir_in(std::env::var_os("USERPROFILE").expect("USERPROFILE is required on Windows"));+ #[cfg(not(target_os = "windows"))]+ let home = builder.tempdir();+ home.expect("create isolated extension home")+}++// ---------------------------------------------------------------- driver++/// One MCP connection to a Driver whose extension root is `home`.+struct PerceptionDriver {+ driver: McpDriver,+ #[cfg(target_os = "macos")]+ _daemon: MacosDaemon,+}++impl PerceptionDriver {+ fn start(label: &str, home: &Path) -> Self {+ #[cfg(target_os = "macos")]+ {+ let daemon = MacosDaemon::start(home);+ let driver = McpDriver::spawn_daemon_proxy_named(&daemon.socket, label)+ .expect("connect to the dedicated installed Driver daemon");+ Self {+ driver,+ _daemon: daemon,+ }+ }+ #[cfg(not(target_os = "macos"))]+ {+ let home = home.to_str().expect("UTF-8 extension home");+ let driver = McpDriver::spawn_named_with_env(label, &[("CUA_DRIVER_RS_HOME", home)])+ .expect("start the source-built Driver with an isolated extension home");+ Self { driver }+ }+ }+}++#[cfg(target_os = "macos")]+fn installed_macos_binary() -> PathBuf {+ let binary = PathBuf::from(+ std::env::var_os("CUA_E2E_INSTALLED_DRIVER_BIN")+ .expect("CUA_E2E_INSTALLED_DRIVER_BIN must identify the installed, TCC-authorized app"),+ );+ assert!(binary.is_file(), "installed Driver is missing: {binary:?}");+ binary+}++/// A second instance of the installed app, sharing its TCC grants but not its+/// extension home, socket, or PID file. The canonical shared daemon is left+/// untouched; this instance is stopped when the row ends.+#[cfg(target_os = "macos")]+struct MacosDaemon {+ binary: PathBuf,+ socket: String,+ _socket_dir: tempfile::TempDir,+}++#[cfg(target_os = "macos")]+impl MacosDaemon {+ fn start(home: &Path) -> Self {+ let binary = installed_macos_binary();+ let app = binary+ .ancestors()+ .nth(3)+ .filter(|path| path.extension().is_some_and(|ext| ext == "app"))+ .unwrap_or_else(|| panic!("installed Driver is not inside an app bundle: {binary:?}"))+ .to_path_buf();+ // Unix socket paths are short on macOS.+ let socket_dir = tempfile::Builder::new()+ .prefix("cua-p-")+ .tempdir_in("/tmp")+ .expect("create daemon socket directory");+ let socket = socket_dir.path().join("d.sock").display().to_string();+ let pid_file = socket_dir.path().join("d.pid").display().to_string();+ let log = home.join("daemon.log");+ let status = Command::new("open")+ .args(["-n", "-g"])+ .arg("--env")+ .arg(format!("CUA_DRIVER_RS_HOME={}", home.display()))+ .args(["--env", "CUA_DRIVER_RS_TELEMETRY_ENABLED=false"])+ .arg("--stderr")+ .arg(&log)+ .arg(&app)+ .args(["--args", "--socket", &socket, "--pid-file", &pid_file])+ .args([+ "serve",+ "--permission-mode",+ "unrestricted",+ "--dangerously-bypass-approvals",+ "--no-permissions-gate",+ "--no-overlay",+ ])+ .status()+ .expect("launch dedicated installed Driver instance");+ assert!(status.success(), "open failed for {app:?}: {status}");+ let daemon = Self {+ binary,+ socket,+ _socket_dir: socket_dir,+ };+ let deadline = Instant::now() + Duration::from_secs(45);+ loop {+ let output = Command::new(&daemon.binary)+ .args(["--socket", &daemon.socket, "status"])+ .stdin(Stdio::null())+ .output();+ if output.as_ref().is_ok_and(|output| {+ output.status.success()+ && String::from_utf8_lossy(&output.stdout)+ .contains("permission mode: unrestricted")+ }) {+ return daemon;+ }+ if Instant::now() >= deadline {+ panic!(+ "dedicated installed Driver did not become ready: status={:?} log={}",+ output.map(|output| String::from_utf8_lossy(&output.stdout).into_owned()),+ fs::read_to_string(&log).unwrap_or_default()+ );+ }+ thread::sleep(Duration::from_millis(250));+ }+ }+}++#[cfg(target_os = "macos")]+impl Drop for MacosDaemon {+ fn drop(&mut self) {+ let _ = Command::new(&self.binary)+ .args(["--socket", &self.socket, "stop"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ }+}++// ---------------------------------------------------------------- fixture++struct Fixture {+ pid: u32,+ window_id: u64,+ journal: FixtureJournal,+}++fn electron_command() -> Command {+ #[cfg(target_os = "windows")]+ let (path, args) = (+ harness_app("harness-electron", "CuaTestHarness.Electron.exe"),+ vec![+ "--no-sandbox",+ "--disable-gpu",+ "--force-renderer-accessibility",+ ],+ );+ #[cfg(target_os = "macos")]+ let (path, args) = (+ harness_app(+ "harness-electron",+ "CuaTestHarness.Electron.app/Contents/MacOS/Electron",+ ),+ vec!["--force-renderer-accessibility"],+ );+ #[cfg(target_os = "linux")]+ let (path, args) = (+ harness_app("harness-electron", "CuaTestHarness.Electron"),+ vec![+ "--no-sandbox",+ "--disable-gpu",+ "--force-renderer-accessibility",+ ],+ );+ assert!(+ path.exists(),+ "the Electron harness is required but was not staged at {path:?}"+ );+ let mut command = Command::new(path);+ command+ .args(args)+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit());+ command+}++fn launch_electron(driver: &mut McpDriver) -> Fixture {+ let journal = FixtureJournal::start();+ let cdp_port = std::net::TcpListener::bind(("127.0.0.1", 0))+ .and_then(|listener| listener.local_addr())+ .expect("allocate a loopback CDP port")+ .port();+ let window_ids = |driver: &mut McpDriver| {+ driver.call("list_windows", json!({})).structured()["windows"]+ .as_array()+ .map(|windows| {+ windows+ .iter()+ .filter_map(|window| window["window_id"].as_u64())+ .collect::<std::collections::HashSet<_>>()+ })+ .unwrap_or_default()+ };+ let before = window_ids(driver);+ let mut command = electron_command();+ command+ .env("CUA_E2E_FIXTURE_JOURNAL_URL", journal.url())+ .env("CUA_ELECTRON_CDP_PORT", cdp_port.to_string());+ let child = spawn_in_job(&mut command).expect("launch the Electron harness");+ driver.reaper().push(child);++ let deadline = Instant::now() + Duration::from_secs(30);+ while Instant::now() < deadline {+ let windows = driver.call("list_windows", json!({}));+ let found = windows.structured()["windows"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|window| {+ window["window_id"]+ .as_u64()+ .is_some_and(|id| !before.contains(&id))+ && window["title"]+ .as_str()+ .is_some_and(|title| title.contains(FIXTURE_TITLE))+ })+ .and_then(|window| {+ Some((+ window["pid"].as_u64()? as u32,+ window["window_id"].as_u64()?,+ ))+ });+ if let Some((pid, window_id)) = found {+ driver.reaper().track_pid(pid);+ // The page publishes its DOM state only after it has loaded.+ while Instant::now() < deadline {+ if journal.text("drag-status").as_deref() == Some("drag_status=idle") {+ return Fixture {+ pid,+ window_id,+ journal,+ };+ }+ thread::sleep(Duration::from_millis(100));+ }+ panic!("Electron harness page never published its initial state");+ }+ thread::sleep(Duration::from_millis(250));+ }+ panic!("Electron harness window did not appear");+}++fn capture_window(driver: &mut McpDriver, fixture: &Fixture) -> (ToolResponse, String) {+ let state = driver.call(+ "get_window_state",+ json!({"pid": fixture.pid as i64, "window_id": fixture.window_id}),+ );+ assert!(+ !state.is_error(),+ "get_window_state failed: {}",+ state.text()+ );+ let capture_id = state.structured()["capture_id"]+ .as_str()+ .unwrap_or_else(|| panic!("window observation omitted capture_id: {}", state.text()))+ .to_owned();+ (state, capture_id)+}++fn parse_regions(driver: &mut McpDriver, capture_id: &str) -> ToolResponse {+ driver.call(+ "parse_visual_regions",+ json!({+ "capture_id": capture_id,+ "options": {"kinds": ["icon"], "min_confidence": 0.5, "max_regions": 16}+ }),+ )+}++/// Validate one parse result against the retained capture and return the+/// target swatch's screenshot-pixel center.+fn target_point(parsed: &ToolResponse, fixture: &Fixture, capture_id: &str) -> (f64, f64) {+ assert!(+ !parsed.is_error(),+ "parse_visual_regions failed: {}; structured={}",+ parsed.text(),+ parsed.structured()+ );+ let result = parsed.structured();+ assert_eq!(result["schema"], "cua.visual_regions_v1");+ assert_eq!(result["capture"]["capture_id"], capture_id);+ assert_eq!(result["capture"]["source"]["kind"], "window");+ assert_eq!(result["capture"]["source"]["pid"], fixture.pid);+ assert_eq!(result["capture"]["source"]["window_id"], fixture.window_id);+ assert_eq!(result["parser"]["extension_version"], EXTENSION_VERSION);+ assert_eq!(result["parser"]["backend"], "deterministic_fixture");+ let width = result["capture"]["screenshot"]["width"]+ .as_u64()+ .expect("screenshot width");+ let height = result["capture"]["screenshot"]["height"]+ .as_u64()+ .expect("screenshot height");+ let region = result["regions"]+ .as_array()+ .into_iter()+ .flatten()+ .find(|region| region["id"] == TARGET_REGION)+ .unwrap_or_else(|| panic!("the swatch worker found no {TARGET_REGION}: {result}"));+ let bounds = ®ion["bounds"];+ let (x, y, w, h) = (+ bounds["x"].as_u64().unwrap(),+ bounds["y"].as_u64().unwrap(),+ bounds["width"].as_u64().unwrap(),+ bounds["height"].as_u64().unwrap(),+ );+ assert!(+ w > 0 && h > 0 && x + w <= width && y + h <= height,+ "region lies outside its {width}x{height} capture: {region}"+ );+ eprintln!(+ "[perception] capture={capture_id} {width}x{height} {TARGET_REGION}=({x},{y}) {w}x{h} space={}",+ result["capture"]["action_coordinate_space"]+ );+ (x as f64 + w as f64 / 2.0, y as f64 + h as f64 / 2.0)+}++fn wait_for_drag_status_change(journal: &FixtureJournal) -> String {+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let status = journal.text("drag-status").unwrap_or_default();+ if status != "drag_status=idle" && !status.is_empty() {+ return status;+ }+ assert!(+ Instant::now() < deadline,+ "the capture-bound click never reached the parsed swatch: {}",+ journal.snapshot()+ );+ thread::sleep(Duration::from_millis(50));+ }+}++// ---------------------------------------------------------------- rows++/// A default installation has no extension. Parsing a real, retained window+/// capture returns the typed `not_installed` refusal and never installs,+/// downloads, or launches a worker.+#[test]+#[ignore]+fn parse_visual_regions_without_extension_returns_not_installed() {+ let case = native_readonly_case(+ "electron",+ "parse_visual_regions_not_installed",+ Targeting::NotApplicable,+ DriverRoute::WindowState,+ vec![OracleKind::Protocol],+ );+ let cell_id = case.cell_id.clone();+ execute_case(case, |evidence| {+ let home = extension_home();+ let mut session = PerceptionDriver::start(&cell_id, home.path());+ let driver = &mut session.driver;+ *evidence = recording_evidence(driver.recording_dir());+ let fixture = launch_electron(driver);+ driver.start_behavior_recording();++ let (_, capture_id) = capture_window(driver, &fixture);+ let parsed = parse_regions(driver, &capture_id);+ assert!(parsed.is_error(), "parse without an extension succeeded");+ assert_eq!(+ parsed.structured()["code"],+ "not_installed",+ "unexpected refusal: {}",+ parsed.structured()+ );+ assert!(+ !home.path().join("extensions").exists(),+ "parsing must never install the extension"+ );+ Observation::delivered(vec![OracleKind::Protocol], Evidence::default())+ });+}++/// With the extension installed: parse a fresh window capture, click the+/// parsed swatch once with the same `capture_id`, verify the fixture state,+/// prove the consumed capture is refused, then reobserve and reparse.+#[test]+#[ignore]+fn capture_bound_click_from_parsed_region_is_state_verified_and_single_use() {+ let route = shared_web_route(+ Platform::current(),+ DisplayServer::current(),+ "left_click",+ Targeting::Px,+ Delivery::Foreground,+ )+ .expect("foreground pixel click route");+ let case = CaseSpec::delivered(+ format!(+ "{}-electron-perception-capture-click-px-foreground",+ std::env::consts::OS+ ),+ "electron",+ "electron",+ "perception_capture_click",+ Targeting::Px,+ Delivery::Foreground,+ Scope::Window,+ route,+ vec![OracleKind::FixtureState, OracleKind::Protocol],+ );+ let cell_id = case.cell_id.clone();+ execute_case(case, |evidence| {+ let home = extension_home();+ let scratch = tempfile::tempdir().expect("create extension scratch directory");+ install_swatch_extension(&lifecycle_binary(), home.path(), scratch.path());++ let mut session = PerceptionDriver::start(&cell_id, home.path());+ let driver = &mut session.driver;+ *evidence = recording_evidence(driver.recording_dir());+ let fixture = launch_electron(driver);+ let raised = driver.call(+ "bring_to_front",+ json!({"pid": fixture.pid as i64, "window_id": fixture.window_id}),+ );+ eprintln!("[perception] bring_to_front: {}", raised.text());+ thread::sleep(Duration::from_millis(500));+ driver.start_behavior_recording();++ // 1. Observe and retain the native capture.+ let (_, capture_id) = capture_window(driver, &fixture);+ // 2. Parse that exact capture.+ let parsed = parse_regions(driver, &capture_id);+ let (x, y) = target_point(&parsed, &fixture, &capture_id);+ assert_eq!(+ fixture.journal.text("drag-status").as_deref(),+ Some("drag_status=idle"),+ "parsing must not change fixture state"+ );++ // 3. One capture-bound click derived from the parsed region.+ let click_args = json!({+ "pid": fixture.pid as i64,+ "window_id": fixture.window_id,+ "x": x,+ "y": y,+ "capture_id": capture_id,+ "delivery_mode": "foreground"+ });+ let click = driver.call("click", click_args.clone());+ assert!(+ !click.is_error(),+ "capture-bound click failed: {}; structured={}",+ click.text(),+ click.structured()+ );+ let delivered = wait_for_drag_status_change(&fixture.journal);+ eprintln!(+ "[perception] click route={:?} effect={:?} fixture={delivered}",+ click.action_route(),+ click.action_effect()+ );++ // 4. The capture is single-use: the same capture_id is refused.+ let reused = driver.call("click", click_args);+ assert!(+ reused.is_error(),+ "a consumed capture authorized a second click: {}",+ reused.text()+ );+ assert_eq!(+ reused.structured()["code"],+ "capture_not_found",+ "consumed capture used an unexpected refusal: {}",+ reused.structured()+ );+ assert_eq!(reused.structured()["effect"], "refused");++ // 5. Reobserve: a fresh capture parses under its own identity.+ let (_, fresh_capture_id) = capture_window(driver, &fixture);+ assert_ne!(fresh_capture_id, capture_id);+ let reparsed = parse_regions(driver, &fresh_capture_id);+ target_point(&reparsed, &fixture, &fresh_capture_id);+ Observation::delivered(+ vec![OracleKind::FixtureState, OracleKind::Protocol],+ Evidence::default(),+ )+ });+}++// ---------------------------------------------------------------- hermetic++fn png_bytes(image: image::RgbaImage) -> Vec<u8> {+ let mut bytes = Vec::new();+ image::DynamicImage::ImageRgba8(image)+ .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)+ .unwrap();+ bytes+}++fn worker_exchange(worker: &Path, png: &[u8]) -> Vec<Value> {+ use base64::Engine as _;+ use std::io::Write as _;+ let frame = |value: Value| {+ let bytes = serde_json::to_vec(&value).unwrap();+ let mut framed = (bytes.len() as u32).to_be_bytes().to_vec();+ framed.extend(bytes);+ framed+ };+ let mut input = frame(json!({+ "protocol": "cua-perception/1", "request_id": "health-1", "method": "health", "params": {}+ }));+ input.extend(frame(json!({+ "protocol": "cua-perception/1", "request_id": "parse-1", "method": "parse",+ "params": {"capture_id": "capture_e2e_1", "image": {+ "media_type": "image/png", "width": 1, "height": 1, "byte_length": png.len(),+ "data_base64": base64::engine::general_purpose::STANDARD.encode(png)+ }}+ })));+ let mut child = Command::new(worker)+ .args([+ "--extension-id",+ "cua-perception",+ "--extension-version",+ EXTENSION_VERSION,+ ])+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .spawn()+ .expect("run swatch worker");+ child.stdin.take().unwrap().write_all(&input).unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success());+ let mut frames = Vec::new();+ let mut rest = output.stdout.as_slice();+ while rest.len() >= 4 {+ let length = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize;+ frames.push(serde_json::from_slice(&rest[4..4 + length]).unwrap());+ rest = &rest[4 + length..];+ }+ frames+}++/// The swatch worker's PNG decoder and detector locate the harness swatches in+/// pixels, ignore thin same-color decoys, and echo the exact PNG digest.+#[test]+fn swatch_worker_detects_harness_swatches_from_png_pixels() {+ let scratch = tempfile::tempdir().unwrap();+ let worker = compile_worker(scratch.path());+ let image = image::RgbaImage::from_fn(640, 400, |x, y| {+ let pixel = if (100..320).contains(&x) && (50..146).contains(&y) {+ [0x12, 0x68, 0xd6]+ } else if (340..560).contains(&x) && (50..146).contains(&y) {+ [0x17, 0x8a, 0x38]+ } else if y == 200 || x == 20 {+ // A focus-ring-like outline in a near color must not be chosen.+ [0x10, 0x6a, 0xe0]+ } else if y > 300 {+ [+ (x * 7 % 256) as u8,+ (y * 3 % 256) as u8,+ ((x + y) * 5 % 256) as u8,+ ]+ } else {+ [255, 255, 255]+ };+ image::Rgba([pixel[0], pixel[1], pixel[2], 255])+ });+ let png = png_bytes(image);+ let frames = worker_exchange(&worker, &png);+ assert_eq!(frames.len(), 2, "{frames:?}");+ assert_eq!(frames[0]["request_id"], "health-1");+ assert_eq!(frames[0]["result"]["ready"], true);+ assert_eq!(+ frames[0]["result"]["identity"]["extension"]["version"],+ EXTENSION_VERSION+ );+ let result = &frames[1]["result"];+ assert_eq!(frames[1]["status"], "ok", "{}", frames[1]);+ assert_eq!(result["capture_id"], "capture_e2e_1");+ assert_eq!(result["image"]["sha256"], sha256(&png));+ assert_eq!(result["image"]["width"], 640);+ assert_eq!(result["image"]["height"], 400);+ assert_eq!(+ result["regions"],+ json!([+ {"id": "swatch-drag-source", "kind": "icon",+ "bounds": {"x": 100, "y": 50, "width": 220, "height": 96},+ "label": "drag-source swatch", "confidence": 0.99, "interactive": true, "reading_order": 0},+ {"id": "swatch-drop-target", "kind": "icon",+ "bounds": {"x": 340, "y": 50, "width": 220, "height": 96},+ "label": "drop-target swatch", "confidence": 0.99, "interactive": true, "reading_order": 1}+ ])+ );++ let blank = png_bytes(image::RgbaImage::from_pixel(32, 32, image::Rgba([255; 4])));+ let frames = worker_exchange(&worker, &blank);+ assert_eq!(frames[1]["status"], "error");+ assert_eq!(frames[1]["error"]["code"], "inference_failed");+}++/// Driver accepts the developer-only swatch archive and runs the installed+/// worker inside its normal containment. Uses the read-only local-image CLI,+/// so it needs no desktop; skipped when the Driver binary is not built.+#[test]+fn swatch_extension_installs_and_parses_through_driver_containment() {+ let binary = driver_binary();+ if !ensure_driver_binary(&binary) {+ return;+ }+ let home = extension_home();+ let scratch = tempfile::tempdir().unwrap();+ install_swatch_extension(&binary, home.path(), scratch.path());++ let image = image::RgbaImage::from_fn(300, 200, |x, y| {+ if (40..150).contains(&x) && (60..108).contains(&y) {+ image::Rgba([0x12, 0x68, 0xd6, 255])+ } else {+ image::Rgba([250, 250, 250, 255])+ }+ });+ let image_path = scratch.path().join("window.png");+ fs::write(&image_path, png_bytes(image)).unwrap();+ let capture_path = scratch.path().join("capture.json");+ fs::write(+ &capture_path,+ br#"{"source":{"kind":"window","pid":123,"window_id":456}}"#,+ )+ .unwrap();+ let output = run_extension_command(+ &binary,+ home.path(),+ &[+ "perception",+ "parse",+ "--image",+ image_path.to_str().unwrap(),+ "--capture",+ capture_path.to_str().unwrap(),+ "--json",+ ],+ );+ let result: Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|error| {+ panic!(+ "perception parse output is not JSON ({error}): stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ });+ assert!(output.status.success(), "perception parse failed: {result}");+ assert_eq!(result["parser"]["backend"], "deterministic_fixture");+ assert_eq!(result["parser"]["extension_version"], EXTENSION_VERSION);+ assert_eq!(result["local_input"]["action_eligible"], false);+ assert_eq!(result["regions"][0]["id"], TARGET_REGION);+ assert_eq!(+ result["regions"][0]["bounds"],+ json!({"x": 40, "y": 60, "width": 110, "height": 48})+ );+}diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/support/perception_swatch_worker.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/support/perception_swatch_worker.rsnew file mode 100644index 0000000000..089e0e724c--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/support/perception_swatch_worker.rs@@ -0,0 +1,675 @@+//! Deterministic, model-free stand-in for the `cua-perception` worker.+//!+//! The canonical desktop E2E installs this program as a developer-only+//! unsigned extension so Driver's real capture -> parse -> capture-bound action+//! loop runs without a published artifact or model weights. It speaks the+//! same framed `cua-perception/1` protocol as the shipped worker, receives the+//! exact PNG retained by Driver, and derives regions from those pixels: it+//! decodes the PNG, finds the solid color swatches painted by the shared web+//! harness (`#drag-source` and `#drop-target`), and reports each swatch as one+//! icon region in source-image pixels. It also echoes the PNG SHA-256 so+//! Driver proves the worker saw the retained capture bytes.+//!+//! The test compiles this single file with `rustc` and no external crates,+//! because the contained worker may execute only its own statically linked+//! image on Linux. It is test support only and is never shipped.++use std::io::{self, Read, Write};++const PROTOCOL: &str = "cua-perception/1";+/// Stable identity of this detector specification. Driver requires a+/// SHA-256-shaped fixture identity for the `deterministic_fixture` backend.+const DETECTOR_ID_SHA256: &str = "5c0a7c4e3b1f6d2a9e8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f";++struct Swatch {+ name: &'static str,+ rgb: [u8; 3],+}++/// Solid backgrounds from `libs/cua-driver/tests/fixtures/shared/web/index.html`.+const SWATCHES: &[Swatch] = &[+ Swatch {+ name: "drag-source",+ rgb: [0x12, 0x68, 0xd6],+ },+ Swatch {+ name: "drop-target",+ rgb: [0x17, 0x8a, 0x38],+ },+];+/// Per-channel tolerance for display color management and compositing.+const TOLERANCE: i32 = 40;+/// Smallest accepted swatch, in pixels. The fixture swatch is 110x48 CSS px.+const MIN_PIXELS: usize = 600;+/// A swatch is a filled rectangle; focus rings and anti-aliased edges are not.+const MIN_FILL: f64 = 0.80;++fn main() {+ let args = std::env::args().collect::<Vec<_>>();+ let argument = |name: &str| -> String {+ args.iter()+ .position(|value| value == name)+ .and_then(|index| args.get(index + 1))+ .cloned()+ .unwrap_or_else(|| {+ eprintln!("perception swatch worker requires {name}");+ std::process::exit(2);+ })+ };+ let identity = format!(+ r#"{{"extension":{{"id":"{}","version":"{}"}},"backend":"deterministic_fixture","fixture_sha256":"{DETECTOR_ID_SHA256}"}}"#,+ json_escape(&argument("--extension-id")),+ json_escape(&argument("--extension-version")),+ );++ while let Some(payload) = read_frame() {+ let request_id = string_field(&payload, "request_id").unwrap_or_default();+ let response = match string_field(&payload, "method").as_deref() {+ Some("health") => format!(+ r#"{{"protocol":"{PROTOCOL}","request_id":"{}","status":"ok","result":{{"ready":true,"protocol":"{PROTOCOL}","identity":{identity}}}}}"#,+ json_escape(&request_id)+ ),+ Some("parse") => match parse(&payload) {+ Ok(result) => format!(+ r#"{{"protocol":"{PROTOCOL}","request_id":"{}","status":"ok","result":{{"runtime":"fixture_only","identity":{identity},{result}}}}}"#,+ json_escape(&request_id)+ ),+ Err((code, message)) => error_frame(&request_id, code, &message),+ },+ _ => error_frame(&request_id, "invalid_request", "unsupported method"),+ };+ write_frame(&response);+ }+}++fn error_frame(request_id: &str, code: &str, message: &str) -> String {+ format!(+ r#"{{"protocol":"{PROTOCOL}","request_id":"{}","status":"error","error":{{"code":"{code}","message":"{}"}}}}"#,+ json_escape(request_id),+ json_escape(message)+ )+}++fn parse(payload: &str) -> Result<String, (&'static str, String)> {+ let invalid = |message: String| ("invalid_image", message);+ let capture_id = string_field(payload, "capture_id")+ .ok_or_else(|| ("invalid_request", "parse omitted capture_id".to_owned()))?;+ let encoded = string_field(payload, "data_base64")+ .ok_or_else(|| ("invalid_request", "parse omitted image data".to_owned()))?;+ let png = base64_decode(&encoded).map_err(invalid)?;+ let image = decode_png(&png).map_err(invalid)?;++ let mut regions = Vec::new();+ let mut diagnostics = Vec::new();+ for swatch in SWATCHES {+ match find_swatch(&image, swatch.rgb) {+ Ok(bounds) => regions.push((swatch.name, bounds)),+ Err(diagnostic) => diagnostics.push(format!("{}: {diagnostic}", swatch.name)),+ }+ }+ if regions.is_empty() {+ return Err((+ "inference_failed",+ format!(+ "no harness swatch in {}x{} capture; {}",+ image.width,+ image.height,+ diagnostics.join("; ")+ ),+ ));+ }+ let regions = regions+ .iter()+ .enumerate()+ .map(|(order, (name, (x, y, width, height)))| {+ format!(+ r#"{{"id":"swatch-{name}","kind":"icon","bounds":{{"x":{x},"y":{y},"width":{width},"height":{height}}},"label":"{name} swatch","confidence":0.99,"interactive":true,"reading_order":{order}}}"#+ )+ })+ .collect::<Vec<_>>()+ .join(",");+ Ok(format!(+ r#""capture_id":"{}","image":{{"sha256":"{}","width":{},"height":{}}},"coordinate_space":"image_pixels","regions":[{regions}]"#,+ json_escape(&capture_id),+ sha256_hex(&png),+ image.width,+ image.height+ ))+}++// ---------------------------------------------------------------- framing++fn read_frame() -> Option<String> {+ let mut stdin = io::stdin().lock();+ let mut length = [0_u8; 4];+ stdin.read_exact(&mut length).ok()?;+ let mut payload = vec![0_u8; u32::from_be_bytes(length) as usize];+ stdin.read_exact(&mut payload).ok()?;+ String::from_utf8(payload).ok()+}++fn write_frame(payload: &str) {+ let bytes = payload.as_bytes();+ let mut stdout = io::stdout().lock();+ stdout+ .write_all(&(bytes.len() as u32).to_be_bytes())+ .and_then(|()| stdout.write_all(bytes))+ .and_then(|()| stdout.flush())+ .unwrap_or_else(|_| std::process::exit(1));+}++/// Extract one JSON string value by key. Driver serializes requests without+/// whitespace, and every key read here is unique in the request.+fn string_field(payload: &str, name: &str) -> Option<String> {+ let marker = format!("\"{name}\":\"");+ let start = payload.find(&marker)? + marker.len();+ let tail = &payload[start..];+ let mut value = String::new();+ let mut chars = tail.chars();+ while let Some(ch) = chars.next() {+ match ch {+ '"' => return Some(value),+ '\\' => match chars.next()? {+ 'n' => value.push('\n'),+ 't' => value.push('\t'),+ 'r' => value.push('\r'),+ other => value.push(other),+ },+ other => value.push(other),+ }+ }+ None+}++fn json_escape(value: &str) -> String {+ let mut escaped = String::with_capacity(value.len());+ for ch in value.chars() {+ match ch {+ '"' => escaped.push_str("\\\""),+ '\\' => escaped.push_str("\\\\"),+ '\n' => escaped.push_str("\\n"),+ '\r' => escaped.push_str("\\r"),+ '\t' => escaped.push_str("\\t"),+ ch if (ch as u32) < 0x20 => escaped.push_str(&format!("\\u{:04x}", ch as u32)),+ ch => escaped.push(ch),+ }+ }+ escaped+}++// ---------------------------------------------------------------- detection++struct Rgb {+ width: usize,+ height: usize,+ pixels: Vec<[u8; 3]>,+}++type Bounds = (usize, usize, usize, usize);++/// Largest filled 4-connected component near `target`, as `(x, y, w, h)`.+fn find_swatch(image: &Rgb, target: [u8; 3]) -> Result<Bounds, String> {+ let matches = |pixel: &[u8; 3]| {+ pixel+ .iter()+ .zip(target.iter())+ .all(|(actual, wanted)| (*actual as i32 - *wanted as i32).abs() <= TOLERANCE)+ };+ let mut visited = vec![false; image.pixels.len()];+ let mut best: Option<(usize, Bounds)> = None;+ let mut largest_rejected: Option<(usize, Bounds, f64)> = None;+ let mut stack = Vec::new();+ for start in 0..image.pixels.len() {+ if visited[start] || !matches(&image.pixels[start]) {+ continue;+ }+ visited[start] = true;+ stack.push(start);+ let (mut count, mut min_x, mut min_y, mut max_x, mut max_y) =+ (0_usize, usize::MAX, usize::MAX, 0_usize, 0_usize);+ while let Some(index) = stack.pop() {+ let (x, y) = (index % image.width, index / image.width);+ count += 1;+ min_x = min_x.min(x);+ max_x = max_x.max(x);+ min_y = min_y.min(y);+ max_y = max_y.max(y);+ let mut visit = |neighbor: usize| {+ if !visited[neighbor] && matches(&image.pixels[neighbor]) {+ visited[neighbor] = true;+ stack.push(neighbor);+ }+ };+ if x > 0 {+ visit(index - 1);+ }+ if x + 1 < image.width {+ visit(index + 1);+ }+ if y > 0 {+ visit(index - image.width);+ }+ if y + 1 < image.height {+ visit(index + image.width);+ }+ }+ let bounds = (min_x, min_y, max_x - min_x + 1, max_y - min_y + 1);+ let fill = count as f64 / (bounds.2 * bounds.3) as f64;+ if count >= MIN_PIXELS && fill >= MIN_FILL {+ if best.is_none_or(|(size, _)| count > size) {+ best = Some((count, bounds));+ }+ } else if largest_rejected.is_none_or(|(size, _, _)| count > size) {+ largest_rejected = Some((count, bounds, fill));+ }+ }+ best.map(|(_, bounds)| bounds)+ .ok_or_else(|| match largest_rejected {+ Some((count, (x, y, w, h), fill)) => format!(+ "largest near-color component had {count} px at ({x},{y}) {w}x{h}, fill {fill:.2}"+ ),+ None => "no near-color pixels".to_owned(),+ })+}++// ---------------------------------------------------------------- PNG++fn decode_png(bytes: &[u8]) -> Result<Rgb, String> {+ const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];+ if bytes.len() < 8 || bytes[..8] != SIGNATURE {+ return Err("image is not a PNG".to_owned());+ }+ let mut offset = 8;+ let mut header = None;+ let mut compressed = Vec::new();+ while offset + 8 <= bytes.len() {+ let length = u32::from_be_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize;+ let kind = &bytes[offset + 4..offset + 8];+ let data = bytes+ .get(offset + 8..offset + 8 + length)+ .ok_or("truncated PNG chunk")?;+ match kind {+ b"IHDR" if data.len() == 13 => header = Some(data.to_vec()),+ b"IDAT" => compressed.extend_from_slice(data),+ b"IEND" => break,+ _ => {}+ }+ offset += 12 + length;+ }+ let header = header.ok_or("PNG has no IHDR")?;+ let width = u32::from_be_bytes(header[0..4].try_into().unwrap()) as usize;+ let height = u32::from_be_bytes(header[4..8].try_into().unwrap()) as usize;+ let (depth, color, interlace) = (header[8], header[9], header[12]);+ let channels = match (depth, color, interlace) {+ (8, 2, 0) => 3,+ (8, 6, 0) => 4,+ _ => {+ return Err(format!(+ "unsupported PNG format depth={depth} color={color} interlace={interlace}"+ ))+ }+ };+ if width == 0 || height == 0 || compressed.len() < 2 || compressed[0] & 0x0f != 8 {+ return Err("PNG has no zlib image data".to_owned());+ }+ let raw = inflate(&compressed[2..])?;+ let stride = width * channels;+ if raw.len() < height * (stride + 1) {+ return Err("PNG image data is truncated".to_owned());+ }+ let mut previous = vec![0_u8; stride];+ let mut current = vec![0_u8; stride];+ let mut pixels = Vec::with_capacity(width * height);+ for row in 0..height {+ let line = &raw[row * (stride + 1)..(row + 1) * (stride + 1)];+ let filter = line[0];+ for i in 0..stride {+ let a = if i >= channels {+ current[i - channels]+ } else {+ 0+ };+ let b = previous[i];+ let c = if i >= channels {+ previous[i - channels]+ } else {+ 0+ };+ let predictor = match filter {+ 0 => 0,+ 1 => a,+ 2 => b,+ 3 => ((a as u16 + b as u16) / 2) as u8,+ 4 => paeth(a, b, c),+ other => return Err(format!("unsupported PNG filter {other}")),+ };+ current[i] = line[i + 1].wrapping_add(predictor);+ }+ pixels.extend(+ current+ .chunks_exact(channels)+ .map(|pixel| [pixel[0], pixel[1], pixel[2]]),+ );+ std::mem::swap(&mut previous, &mut current);+ }+ Ok(Rgb {+ width,+ height,+ pixels,+ })+}++fn paeth(a: u8, b: u8, c: u8) -> u8 {+ let p = a as i16 + b as i16 - c as i16;+ let (pa, pb, pc) = (+ (p - a as i16).abs(),+ (p - b as i16).abs(),+ (p - c as i16).abs(),+ );+ if pa <= pb && pa <= pc {+ a+ } else if pb <= pc {+ b+ } else {+ c+ }+}++// ---------------------------------------------------------------- inflate (RFC 1951)++struct BitReader<'a> {+ data: &'a [u8],+ position: usize,+ buffer: u32,+ count: u32,+}++impl BitReader<'_> {+ fn bits(&mut self, need: u32) -> Result<u32, String> {+ while self.count < need {+ let byte = *self+ .data+ .get(self.position)+ .ok_or("deflate stream is truncated")?;+ self.position += 1;+ self.buffer |= (byte as u32) << self.count;+ self.count += 8;+ }+ let value = self.buffer & ((1_u32 << need) - 1);+ self.buffer >>= need;+ self.count -= need;+ Ok(value)+ }++ fn decode(&mut self, table: &Huffman) -> Result<usize, String> {+ let (mut code, mut first, mut index) = (0_i32, 0_i32, 0_i32);+ for length in 1..16 {+ code |= self.bits(1)? as i32;+ let count = table.counts[length] as i32;+ if code - count < first {+ return Ok(table.symbols[(index + code - first) as usize] as usize);+ }+ index += count;+ first = (first + count) << 1;+ code <<= 1;+ }+ Err("invalid deflate Huffman code".to_owned())+ }+}++struct Huffman {+ counts: [u16; 16],+ symbols: Vec<u16>,+}++impl Huffman {+ fn new(lengths: &[u8]) -> Self {+ let mut counts = [0_u16; 16];+ for &length in lengths {+ counts[length as usize] += 1;+ }+ counts[0] = 0;+ let mut offsets = [0_u16; 16];+ for length in 1..15 {+ offsets[length + 1] = offsets[length] + counts[length];+ }+ let mut symbols = vec![0_u16; lengths.len()];+ for (symbol, &length) in lengths.iter().enumerate() {+ if length != 0 {+ symbols[offsets[length as usize] as usize] = symbol as u16;+ offsets[length as usize] += 1;+ }+ }+ Self { counts, symbols }+ }+}++const LENGTH_BASE: [u16; 29] = [+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,+ 163, 195, 227, 258,+];+const LENGTH_EXTRA: [u8; 29] = [+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,+];+const DISTANCE_BASE: [u16; 30] = [+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,+ 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,+];+const DISTANCE_EXTRA: [u8; 30] = [+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,+ 13,+];++fn inflate(data: &[u8]) -> Result<Vec<u8>, String> {+ let mut input = BitReader {+ data,+ position: 0,+ buffer: 0,+ count: 0,+ };+ let mut output = Vec::new();+ loop {+ let last = input.bits(1)? == 1;+ match input.bits(2)? {+ 0 => {+ input.buffer = 0;+ input.count = 0;+ let header = data+ .get(input.position..input.position + 4)+ .ok_or("stored deflate block is truncated")?;+ let length = u16::from_le_bytes([header[0], header[1]]) as usize;+ if length != !u16::from_le_bytes([header[2], header[3]]) as usize {+ return Err("stored deflate block length is corrupt".to_owned());+ }+ input.position += 4;+ let block = data+ .get(input.position..input.position + length)+ .ok_or("stored deflate block is truncated")?;+ output.extend_from_slice(block);+ input.position += length;+ }+ 1 => {+ let mut lengths = [0_u8; 288];+ lengths[..144].fill(8);+ lengths[144..256].fill(9);+ lengths[256..280].fill(7);+ lengths[280..].fill(8);+ let literals = Huffman::new(&lengths);+ let distances = Huffman::new(&[5_u8; 30]);+ inflate_block(&mut input, &mut output, &literals, &distances)?;+ }+ 2 => {+ let (literals, distances) = dynamic_tables(&mut input)?;+ inflate_block(&mut input, &mut output, &literals, &distances)?;+ }+ _ => return Err("invalid deflate block type".to_owned()),+ }+ if last {+ return Ok(output);+ }+ }+}++fn dynamic_tables(input: &mut BitReader<'_>) -> Result<(Huffman, Huffman), String> {+ const ORDER: [usize; 19] = [+ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,+ ];+ let literal_count = input.bits(5)? as usize + 257;+ let distance_count = input.bits(5)? as usize + 1;+ let code_count = input.bits(4)? as usize + 4;+ let mut code_lengths = [0_u8; 19];+ for &position in ORDER.iter().take(code_count) {+ code_lengths[position] = input.bits(3)? as u8;+ }+ let codes = Huffman::new(&code_lengths);+ let mut lengths = vec![0_u8; literal_count + distance_count];+ let mut index = 0;+ while index < lengths.len() {+ let symbol = input.decode(&codes)?;+ let (value, repeat) = match symbol {+ 0..=15 => (symbol as u8, 1),+ 16 => {+ let previous = *lengths+ .get(index.wrapping_sub(1))+ .ok_or("deflate repeat has no previous length")?;+ (previous, 3 + input.bits(2)? as usize)+ }+ 17 => (0, 3 + input.bits(3)? as usize),+ _ => (0, 11 + input.bits(7)? as usize),+ };+ if index + repeat > lengths.len() {+ return Err("deflate code lengths overflow".to_owned());+ }+ lengths[index..index + repeat].fill(value);+ index += repeat;+ }+ Ok((+ Huffman::new(&lengths[..literal_count]),+ Huffman::new(&lengths[literal_count..]),+ ))+}++fn inflate_block(+ input: &mut BitReader<'_>,+ output: &mut Vec<u8>,+ literals: &Huffman,+ distances: &Huffman,+) -> Result<(), String> {+ loop {+ let symbol = input.decode(literals)?;+ match symbol {+ 0..=255 => output.push(symbol as u8),+ 256 => return Ok(()),+ 257..=285 => {+ let code = symbol - 257;+ let length =+ LENGTH_BASE[code] as usize + input.bits(LENGTH_EXTRA[code] as u32)? as usize;+ let code = input.decode(distances)?;+ if code >= 30 {+ return Err("invalid deflate distance code".to_owned());+ }+ let distance = DISTANCE_BASE[code] as usize+ + input.bits(DISTANCE_EXTRA[code] as u32)? as usize;+ if distance > output.len() {+ return Err("deflate distance is too far back".to_owned());+ }+ let start = output.len() - distance;+ for offset in 0..length {+ let byte = output[start + offset];+ output.push(byte);+ }+ }+ _ => return Err("invalid deflate literal/length code".to_owned()),+ }+ }+}++// ---------------------------------------------------------------- base64, SHA-256++fn base64_decode(text: &str) -> Result<Vec<u8>, String> {+ let mut output = Vec::with_capacity(text.len() / 4 * 3);+ let (mut buffer, mut bits) = (0_u32, 0_u32);+ for byte in text.bytes() {+ let value = match byte {+ b'A'..=b'Z' => byte - b'A',+ b'a'..=b'z' => byte - b'a' + 26,+ b'0'..=b'9' => byte - b'0' + 52,+ b'+' => 62,+ b'/' => 63,+ b'=' => break,+ _ => return Err("image data is not base64".to_owned()),+ };+ buffer = (buffer << 6) | value as u32;+ bits += 6;+ if bits >= 8 {+ bits -= 8;+ output.push((buffer >> bits) as u8);+ buffer &= (1 << bits) - 1;+ }+ }+ Ok(output)+}++fn sha256_hex(message: &[u8]) -> String {+ const K: [u32; 64] = [+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,+ 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,+ 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,+ 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,+ 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,+ 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,+ 0xc67178f2,+ ];+ let mut state: [u32; 8] = [+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,+ 0x5be0cd19,+ ];+ let mut padded = message.to_vec();+ padded.push(0x80);+ while padded.len() % 64 != 56 {+ padded.push(0);+ }+ padded.extend_from_slice(&((message.len() as u64) * 8).to_be_bytes());+ for block in padded.chunks_exact(64) {+ let mut w = [0_u32; 64];+ for (i, word) in block.chunks_exact(4).enumerate() {+ w[i] = u32::from_be_bytes(word.try_into().unwrap());+ }+ for i in 16..64 {+ let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);+ let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);+ w[i] = w[i - 16]+ .wrapping_add(s0)+ .wrapping_add(w[i - 7])+ .wrapping_add(s1);+ }+ let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = state;+ for i in 0..64 {+ let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);+ let choice = (e & f) ^ (!e & g);+ let t1 = h+ .wrapping_add(s1)+ .wrapping_add(choice)+ .wrapping_add(K[i])+ .wrapping_add(w[i]);+ let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);+ let majority = (a & b) ^ (a & c) ^ (b & c);+ let t2 = s0.wrapping_add(majority);+ h = g;+ g = f;+ f = e;+ e = d.wrapping_add(t1);+ d = c;+ c = b;+ b = a;+ a = t1.wrapping_add(t2);+ }+ for (slot, value) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {+ *slot = slot.wrapping_add(value);+ }+ }+ state.iter().map(|word| format!("{word:08x}")).collect()+}diff --git a/scripts/ci/linux/run-rust-e2e.sh b/scripts/ci/linux/run-rust-e2e.shindex c7d7212e76..e7be5f1641 100755--- a/scripts/ci/linux/run-rust-e2e.sh+++ b/scripts/ci/linux/run-rust-e2e.sh@@ -363,6 +363,29 @@ if [[ "${SUITE}" == capture || "${SUITE}" == all ]]; thencargo test -p cua-driver-e2e "${CARGO_DRIVER_FEATURE_ARGS[@]}" \--test desktop_scope_linux_test -- \--ignored --nocapture --test-threads=1+ if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then+ run_test perception-capture-loop \+ cargo test -p cua-driver-e2e "${CARGO_DRIVER_FEATURE_ARGS[@]}" \+ --test perception_capture_loop_test -- \+ --ignored --nocapture --test-threads=1+ else+ # The perception loop is certified in the canonical X11 lane. Wayland+ # window capture and pointer routes differ per compositor and are not yet+ # part of this row, so record the coverage gap instead of a vacuous pass.+ limitation="The perception capture-loop row is certified on X11; Wayland compositor lanes do not run it yet."+ jq -n \+ --arg reason "${limitation}" \+ '{+ schema: "cua-e2e-limitation-v1",+ platform: "linux",+ display_server: "wayland",+ harness: "electron",+ test: "perception-capture-loop",+ status: "not_covered",+ reason: $reason+ }' > "${ARTIFACT_DIR}/perception-capture-loop-limitation.json"+ echo "[LIMITATION] perception-capture-loop: ${limitation}"+ fifiif [[ "${SUITE}" == shared || "${SUITE}" == all ]]; thendiff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.shindex 9392cd0199..e4dc7c3ceb 100755--- a/scripts/ci/macos/run-rust-e2e.sh+++ b/scripts/ci/macos/run-rust-e2e.sh@@ -411,6 +411,11 @@ if [[ "${SUITE}" == capture || "${SUITE}" == all ]]; then--ignored --nocapture --test-threads=1run_test desktop-scope cargo test -p cua-driver-e2e --test desktop_scope_macos_test -- \--ignored --nocapture --test-threads=1+ # Runs a dedicated instance of the installed app with an isolated extension+ # home, so the shared daemon never gains the developer-only E2E extension.+ run_test perception-capture-loop cargo test -p cua-driver-e2e \+ --test perception_capture_loop_test -- \+ --ignored --nocapture --test-threads=1fivideo_count=0diff --git a/scripts/ci/windows/run-rust-e2e.ps1 b/scripts/ci/windows/run-rust-e2e.ps1index 52dcfd7b99..36fcc403ba 100644--- a/scripts/ci/windows/run-rust-e2e.ps1+++ b/scripts/ci/windows/run-rust-e2e.ps1@@ -436,6 +436,10 @@ if ($suite -in @("capture", "all")) {"test", "-p", "cua-driver-e2e", "--test", "desktop_scope_windows_test", "--","--ignored", "--nocapture", "--test-threads=1")+ Invoke-CargoTest "perception capture loop" @(+ "test", "-p", "cua-driver-e2e", "--test", "perception_capture_loop_test", "--",+ "--ignored", "--nocapture", "--test-threads=1"+ )}if ($suite -in @("shared", "all")) {