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.

test(cua-driver): typed e2e evidence foundation (#2179)

Francesco Bonacci107915af3d52
diff --git a/.github/workflows/ci-cua-driver-interactive-linux.yml b/.github/workflows/ci-cua-driver-interactive-linux.yml
index d602841dad..8e9e2a5cb0 100644
--- a/.github/workflows/ci-cua-driver-interactive-linux.yml
+++ b/.github/workflows/ci-cua-driver-interactive-linux.yml
@@ -101,7 +101,7 @@ jobs:
python3 /tmp/atspi_probe.py || echo "[interactive-ci] AT-SPI probe inconclusive — AX assertions will skip if the bus is unavailable"
# capture_mode matrix (ax/vision/som): real assertions, headless-safe.
- cargo test -p cua-driver --test modality_capture_mode_test \
+ cargo test -p cua-driver --test capture_contract_test \
-- --ignored --nocapture --test-threads=1
# desktop-scope: run the GATE here (the desktop_scope_disabled
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 1941cee49d..e12a95f47a 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -483,12 +483,12 @@ Actions:
- `action` (string, required): Action to perform.
- `attributes` (array of string, optional): Element attributes to include in query_dom results.
- `bundle_id` (string, optional): Bundle ID of the browser. Required for enable_javascript_apple_events (macOS only).
-- `cdp_port` (integer, optional): Optional, for insert_text/type_keystrokes only: use this exact CDP port instead of auto-discovering one from pid. Needed when the port was opened via the browser's own remote-debugging toggle rather than a launch-time flag, since that path may not answer the auto-discovery probe.
+- `cdp_port` (integer, optional): Optional, for execute_javascript/insert_text/type_keystrokes: use this exact CDP port instead of auto-discovering one from pid. Needed when the port was opened via the browser's own remote-debugging toggle rather than a launch-time flag, since that path may not answer the auto-discovery probe.
- `css_selector` (string, optional): CSS selector for query_dom (e.g. 'a', 'button', 'input', 'h1'-'h6', 'p', 'img', 'select', '*').
- `javascript` (string, optional): JavaScript to execute. Required for execute_javascript.
- `pid` (integer, optional): Target process ID.
- `selector` (string, optional): CSS selector for click_element (e.g. 'button.submit', '#login a').
-- `target_url_contains` (string, optional): Optional, for insert_text/type_keystrokes only: pick the browser tab whose URL contains this substring instead of whichever tab is found first. Use this on a multi-tab browser — there's no built-in link between window_id and which tab a CDP call reaches.
+- `target_url_contains` (string, optional): Optional, for execute_javascript/insert_text/type_keystrokes: require exactly one browser tab whose URL contains this substring. Use this on a multi-tab browser — there's no built-in link between window_id and which tab a CDP call reaches.
- `text` (string, optional): Text to insert or type. Required for insert_text and type_keystrokes. The target field must already have DOM focus (click/focus it first).
- `user_has_confirmed_enabling` (boolean, optional): Must be true to proceed with enable_javascript_apple_events. This will quit and relaunch the browser.
- `window_id` (integer, optional): Target window ID from list_windows.
@@ -503,10 +503,13 @@ Actions:
Start trajectory recording. Every subsequent action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) writes a turn folder under `output_dir`:
+- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.
+- `before.png` / `after.png` — target-window screenshots immediately before and after the action.
+- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.
- `app_state.json` — post-action AX/UIA snapshot for the target pid.
-- `screenshot.png` — post-action per-window screenshot of the target's frontmost on-screen window.
+- `screenshot.png` — compatibility alias of `after.png`.
- `action.json` — tool name, full input arguments, result summary, pid, click point (when applicable), ISO-8601 timestamp.
-- `click.png` — for click-family actions only, `screenshot.png` with a red dot drawn at the click point.
+- `click.png` — for click-family actions only, `before.png` with a red marker at the click point.
Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 1f5737aaba..3fa53c2bcc 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -651,8 +651,13 @@ dependencies = [
name = "cua-driver-testkit"
version = "0.7.1"
dependencies = [
+ "core-foundation",
+ "objc2-app-kit",
+ "serde",
"serde_json",
+ "tempfile",
"windows 0.61.3",
+ "x11rb",
]
[[package]]
diff --git a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
index a7b2e55a98..d205613fc0 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md
@@ -67,26 +67,26 @@ daemon restart resets to disabled.
Each action writes to `turn-NNNNN/` (five-digit zero-padded counter):
-- `app_state.json` — post-action AX/UIA snapshot for the target
- `(pid, window_id)` carrying the same `tree_markdown` +
- `element_count` shape `get_window_state` returns (minus the
- screenshot fields — those live in `screenshot.png`). On macOS the
- recorder resolves a frontmost window internally when the action's
- args don't carry one; on Windows it uses the first window of the
- target pid. **Omitted on Linux** — ATSPI doesn't expose a cheap
- whole-tree snapshot, and the file is left out rather than faked.
-- `screenshot.png` — post-action capture of the target window.
- Omitted when the pid has no visible window.
+- `before_state.json` and `after_state.json` — application accessibility
+ state immediately before and after the action. They carry the same
+ `tree_markdown` and `element_count` shape as `get_window_state`.
+- `before.png` and `after.png` — target-window images immediately before
+ and after the action. Window capture remains scoped to the target when
+ another window covers it.
+- `evidence.json` — capture status for each phase. Missing expected capture
+ has an explicit classification instead of disappearing from the turn.
+- `app_state.json` and `screenshot.png` — compatibility aliases for
+ `after_state.json` and `after.png`.
- `action.json` — the tool name, full input arguments, result
summary, pid, click point (when applicable), ISO-8601 timestamp.
- `click.png` — for click-family actions (`click`, `double_click`,
- `right_click`): a copy of `screenshot.png` with a red dot drawn at
+ `right_click`): a copy of `before.png` with a red marker drawn at
the click point. **Both addressing modes are covered:** explicit
`x, y` clicks use the supplied coordinates directly, and
`element_index`-addressed clicks resolve to the element's center
via the live AX/UIA cache, then convert to window-local screenshot
- pixels. Absent for non-click tools and for clicks whose resolved
- point falls outside the captured window.
+ pixels. Absent for non-click tools and classified as unavailable when
+ a click point was expected but could not be resolved or rendered.
## When to use it
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs
index 6ba3dda49d..b463d8f95a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/cdp.rs
@@ -49,19 +49,14 @@ async fn cdp_evaluate(
await_promise: bool,
target_url_contains: Option<&str>,
) -> anyhow::Result<Value> {
- // Wrap the /json discovery in its own timeout — `cdp_list_pages` does an
- // unbounded `read_to_end`, and a half-open localhost socket (browser
- // mid-shutdown, firewall mismatch, port stolen by another process) would
- // otherwise hang us forever. 10 s is generous for a localhost HTTP roundtrip.
+ // A listener can be reachable before Chromium publishes its first page
+ // target. Bound both that readiness interval and the HTTP roundtrip.
let pages = tokio::time::timeout(
std::time::Duration::from_secs(10),
- cdp_list_pages(port),
+ cdp_wait_for_page(port),
)
.await
.map_err(|_| anyhow::anyhow!("CDP /json discovery on port {port} timed out after 10 s"))??;
- if pages.is_empty() {
- anyhow::bail!("No CDP page tabs found on port {port}");
- }
let page = pick_page(&pages, target_url_contains)
.ok_or_else(|| match target_url_contains {
@@ -141,6 +136,16 @@ fn format_cdp_result(response: &Value) -> String {
// ── HTTP page discovery ───────────────────────────────────────────────────
+async fn cdp_wait_for_page(port: u16) -> anyhow::Result<Vec<Value>> {
+ loop {
+ let pages = cdp_list_pages(port).await?;
+ if !pages.is_empty() {
+ return Ok(pages);
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+}
+
async fn cdp_list_pages(port: u16) -> anyhow::Result<Vec<Value>> {
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
@@ -232,8 +237,8 @@ async fn cdp_ws_call(port: u16, ws_url: &str, message: &str) -> anyhow::Result<V
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let path: String = if let Some(rest) = ws_url.strip_prefix("ws://") {
- rest.splitn(2, '/')
- .nth(1)
+ rest.split_once('/')
+ .map(|(_, path)| path)
.map(|p| format!("/{p}"))
.unwrap_or_else(|| "/".into())
} else {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
index 602d079bf0..459a6dbc14 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording.rs
@@ -1,9 +1,9 @@
//! Trajectory recording session.
//!
//! When enabled, every non-read-only, non-recording tool call writes a
-//! `turn-NNNNN/action.json` file to the configured output directory.
-//! When a screenshot callback is registered via `set_screenshot_fn`, it also
-//! writes `screenshot.png` (extracted from `pid`/`window_id` in the args).
+//! `turn-NNNNN/action.json` file to the configured output directory. Targeted
+//! turns also persist explicit before/after state and image evidence. The
+//! legacy `app_state.json` and `screenshot.png` names remain post-action aliases.
//!
//! Schema mirrors the Swift/Windows reference `action.json`:
//! { tool, arguments, result_summary, timestamp, t_ms_from_session_start,
@@ -26,12 +26,48 @@ use crate::video::{self, VideoBackend, VideoMetadata};
// and returns raw PNG bytes, or None if capture fails. The callback is called
// synchronously from write_turn (a blocking context).
-type ScreenshotFnBox = Box<dyn Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync>;
+pub struct ScreenshotCapture {
+ pub png: Option<Vec<u8>>,
+ pub classification: Option<&'static str>,
+}
+
+impl ScreenshotCapture {
+ pub fn captured(png: Vec<u8>) -> Self {
+ Self {
+ png: Some(png),
+ classification: None,
+ }
+ }
+
+ pub fn unavailable(classification: &'static str) -> Self {
+ Self {
+ png: None,
+ classification: Some(classification),
+ }
+ }
+}
+
+type ScreenshotFnBox =
+ Box<dyn Fn(Option<u64>, Option<i64>) -> ScreenshotCapture + Send + Sync>;
static SCREENSHOT_FN: OnceLock<ScreenshotFnBox> = OnceLock::new();
/// Register the platform-specific screenshot callback. Call once at startup
/// before any tool invocations. Subsequent calls are silently ignored.
-pub fn set_screenshot_fn(f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync + 'static) {
+pub fn set_screenshot_fn(
+ f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync + 'static,
+) {
+ set_classified_screenshot_fn(move |window_id, pid| {
+ f(window_id, pid)
+ .map(ScreenshotCapture::captured)
+ .unwrap_or_else(|| ScreenshotCapture::unavailable("capture_failed"))
+ });
+}
+
+/// Register a screenshot callback that preserves a stable unavailable-capture
+/// classification for the turn evidence manifest.
+pub fn set_classified_screenshot_fn(
+ f: impl Fn(Option<u64>, Option<i64>) -> ScreenshotCapture + Send + Sync + 'static,
+) {
let _ = SCREENSHOT_FN.set(Box::new(f));
}
@@ -40,14 +76,16 @@ pub fn set_screenshot_fn(f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>>
/// by the PiP push hook (and by anything else that wants to share the
/// per-turn screenshot pipeline without duplicating the platform glue).
pub fn screenshot_for(window_id: Option<u64>, pid: Option<i64>) -> Option<Vec<u8>> {
- SCREENSHOT_FN.get().and_then(|f| f(window_id, pid))
+ SCREENSHOT_FN
+ .get()
+ .and_then(|capture| capture(window_id, pid).png)
}
// ── Platform click-marker callback ───────────────────────────────────────────
//
// Takes (png_bytes, cx, cy) and returns modified PNG bytes with a red crosshair
// at (cx, cy), or None if drawing fails. Used to produce click.png alongside
-// screenshot.png when a click-family tool is recorded.
+// before.png when a click-family tool is recorded, producing click.png.
type ClickMarkerFnBox = Box<dyn Fn(&[u8], f64, f64) -> Option<Vec<u8>> + Send + Sync>;
static CLICK_MARKER_FN: OnceLock<ClickMarkerFnBox> = OnceLock::new();
@@ -59,15 +97,16 @@ pub fn set_click_marker_fn(f: impl Fn(&[u8], f64, f64) -> Option<Vec<u8>> + Send
// ── Platform AX-snapshot callback ────────────────────────────────────────────
//
-// Takes (window_id, pid) and returns JSON bytes for `app_state.json` (the
-// post-action AX/UIA snapshot), or None if no snapshot is available on this
-// platform.
+// Takes (window_id, pid) and returns JSON bytes for the phase's application
+// state. The post-action bytes are also kept as legacy `app_state.json`.
type AxSnapshotFnBox = Box<dyn Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync>;
static AX_SNAPSHOT_FN: OnceLock<AxSnapshotFnBox> = OnceLock::new();
/// Register the platform-specific AX/UIA snapshot callback. Call once at startup.
-pub fn set_ax_snapshot_fn(f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync + 'static) {
+pub fn set_ax_snapshot_fn(
+ f: impl Fn(Option<u64>, Option<i64>) -> Option<Vec<u8>> + Send + Sync + 'static,
+) {
let _ = AX_SNAPSHOT_FN.set(Box::new(f));
}
@@ -82,10 +121,35 @@ type ElementBoundsFnBox = Box<dyn Fn(u64, i64, u32) -> Option<(f64, f64)> + Send
static ELEMENT_BOUNDS_FN: OnceLock<ElementBoundsFnBox> = OnceLock::new();
/// Register the platform-specific element-bounds resolver. Args: (window_id, pid, element_index).
-pub fn set_element_bounds_fn(f: impl Fn(u64, i64, u32) -> Option<(f64, f64)> + Send + Sync + 'static) {
+pub fn set_element_bounds_fn(
+ f: impl Fn(u64, i64, u32) -> Option<(f64, f64)> + Send + Sync + 'static,
+) {
let _ = ELEMENT_BOUNDS_FN.set(Box::new(f));
}
+#[derive(Default)]
+struct TurnCapture {
+ state: Option<Vec<u8>>,
+ screenshot: Option<Vec<u8>>,
+ screenshot_classification: Option<&'static str>,
+}
+
+/// A reserved recording turn captured immediately before tool dispatch.
+/// `ToolRegistry` passes this token back after dispatch so both phases share
+/// one stable `turn-NNNNN` directory even when calls complete out of order.
+pub struct PendingTurn {
+ generation: u64,
+ turn_dir: PathBuf,
+ tool_name: String,
+ args: Value,
+ start_ms: u64,
+ session_start_ms: u64,
+ window_id: Option<u64>,
+ pid: Option<i64>,
+ click_point: Option<(f64, f64)>,
+ before: TurnCapture,
+}
+
/// Persistent recording session state (singleton per process).
pub struct RecordingSession {
inner: Mutex<RecordingInner>,
@@ -93,6 +157,7 @@ pub struct RecordingSession {
struct RecordingInner {
enabled: bool,
+ generation: u64,
/// Session that owns the live recording, stamped on every successful
/// `start()` from the daemon-injected `_session_id`. The daemon-global
/// recorder is a singleton, so when session A starts a recording and
@@ -156,6 +221,7 @@ impl RecordingSession {
Self {
inner: Mutex::new(RecordingInner {
enabled: false,
+ generation: 0,
owner: None,
output_dir: None,
next_turn: 1,
@@ -179,7 +245,7 @@ impl RecordingSession {
/// `recording_tools.rs` — so video only records when explicitly requested.
/// The legacy CLI `recording start` path via `configure()` still forces
/// video on. If ffmpeg isn't on PATH the start still succeeds —
- /// the per-turn capture (action.json + screenshot.png) is independent
+ /// the per-turn capture (action.json + pre/post evidence) is independent
/// of video — but the structured state carries the ffmpeg error so
/// the caller can surface it.
///
@@ -187,7 +253,12 @@ impl RecordingSession {
/// `_session_id`). `None` marks an anonymous start (CLI one-shot / legacy
/// `configure()` shim) owned by nobody. See `stop_owner()` for how this
/// gates teardown.
- pub fn start(&self, output_dir: &str, record_video: bool, owner: Option<&str>) -> anyhow::Result<()> {
+ pub fn start(
+ &self,
+ output_dir: &str,
+ record_video: bool,
+ owner: Option<&str>,
+ ) -> anyhow::Result<()> {
let mut inner = self.inner.lock().unwrap();
// Write-boundary resurrection guard — checked INSIDE the lock so the
// is_session_ended test is atomic with the enabled/owner write below.
@@ -249,7 +320,9 @@ impl RecordingSession {
// background thread + a small jsonl file.
let cursor_path = dir.join("cursor.jsonl");
match CursorSampler::start(cursor_path, monotonic_start) {
- Ok(s) => { inner.cursor = Some(s); }
+ Ok(s) => {
+ inner.cursor = Some(s);
+ }
Err(e) => {
tracing::warn!(target: "recording",
"Cursor sampler failed to start: {e}");
@@ -265,10 +338,7 @@ impl RecordingSession {
"video": video_session_payload(video_present, video_error.as_deref(), None),
"cursor": { "present": inner.cursor.is_some(), "sample_count": 0 }
});
- let _ = write_json_atomic(
- &dir.join("session.json"),
- &session_payload,
- );
+ let _ = write_json_atomic(&dir.join("session.json"), &session_payload);
// Stamp the owning session on every successful start (reached only on
// the success path — start() returns early via `?` on `create_dir_all`
@@ -276,6 +346,7 @@ impl RecordingSession {
// the daemon-global recorder is a singleton, so the latest start() owns
// it. The previous owner's disconnect then no-ops in stop_owner().
inner.owner = owner.map(str::to_owned);
+ inner.generation = inner.generation.wrapping_add(1);
inner.enabled = true;
inner.output_dir = Some(dir);
inner.next_turn = 1;
@@ -302,6 +373,7 @@ impl RecordingSession {
/// whose recording was already clobbered by a newer `start()`, or which
/// never started a recording) — silent no-op, leaving the current
/// owner's recording running.
+ ///
/// The guard lives inside the lock so it is race-free against a concurrent
/// `start()`. Supersedes the #1775 generation-token `stop()`.
pub fn stop_owner(&self, requester: Option<&str>) -> anyhow::Result<()> {
@@ -320,7 +392,14 @@ impl RecordingSession {
}
inner.owner = None;
let dir = inner.output_dir.clone();
- let video_meta = inner.video.take().and_then(|rec| rec.stop().ok());
+ let (video_meta, stop_error) = match inner.video.take().map(|rec| rec.stop()) {
+ Some(Ok(meta)) => match validate_video_metadata(meta) {
+ Ok(meta) => (Some(meta), None),
+ Err(error) => (None, Some(error.to_string())),
+ },
+ Some(Err(error)) => (None, Some(error.to_string())),
+ None => (None, None),
+ };
let cursor_samples = inner.cursor.take().map(|c| c.stop()).unwrap_or(0);
inner.enabled = false;
@@ -328,11 +407,14 @@ impl RecordingSession {
inner.next_turn = 1;
inner.session_start_ms = 0;
inner.session_monotonic_start = None;
- if video_meta.is_some() {
+ if let Some(error) = &stop_error {
+ inner.last_error = Some(error.clone());
+ } else if video_meta.is_some() {
inner.last_error = None;
}
inner.last_video = video_meta.clone();
inner.last_cursor_samples = cursor_samples;
+ let final_video_error = inner.last_error.clone();
// Rewrite session.json with final video metadata + cursor count
// so the renderer (and any external analysis) sees what actually
@@ -341,7 +423,7 @@ impl RecordingSession {
let video_block = if let Some(ref m) = video_meta {
video_session_payload(true, None, Some(m))
} else {
- video_session_payload(false, None, None)
+ video_session_payload(false, final_video_error.as_deref(), None)
};
let session_payload = serde_json::json!({
"schema_version": 1,
@@ -349,10 +431,10 @@ impl RecordingSession {
"video": video_block,
"cursor": { "present": cursor_samples > 0, "sample_count": cursor_samples }
});
- let _ = write_json_atomic(
- &dir.join("session.json"),
- &session_payload,
- );
+ let _ = write_json_atomic(&dir.join("session.json"), &session_payload);
+ }
+ if let Some(error) = stop_error {
+ anyhow::bail!("video finalization failed: {error}");
}
Ok(())
}
@@ -377,37 +459,37 @@ impl RecordingSession {
let inner = self.inner.lock().unwrap();
RecordingState {
enabled: inner.enabled,
- output_dir: inner.output_dir.as_ref().map(|p| p.to_string_lossy().into_owned()),
+ output_dir: inner
+ .output_dir
+ .as_ref()
+ .map(|p| p.to_string_lossy().into_owned()),
next_turn: inner.next_turn,
last_error: inner.last_error.clone(),
video_active: inner.video.is_some(),
- last_video_path: inner.last_video.as_ref()
+ last_video_path: inner
+ .last_video
+ .as_ref()
.map(|m| m.path.to_string_lossy().into_owned()),
owner: inner.owner.clone(),
}
}
- /// Record a completed tool call. No-op when recording is disabled.
- /// `start_ms` — wall-clock ms at invocation start (use `now_ms()` before calling the tool).
- pub fn record(
- &self,
- tool_name: &str,
- args: &Value,
- result_text: &str,
- start_ms: u64,
- ) {
- let (turn_dir, session_start_ms) = {
+ /// Reserve a turn and capture its target immediately before tool dispatch.
+ /// No-op when recording is disabled.
+ pub fn begin_turn(&self, tool_name: &str, args: &Value, start_ms: u64) -> Option<PendingTurn> {
+ let (turn_dir, session_start_ms, generation) = {
let mut inner = self.inner.lock().unwrap();
if !inner.enabled {
- return;
+ return None;
}
- let out = match inner.output_dir.clone() {
- Some(o) => o,
- None => return,
- };
+ let out = inner.output_dir.clone()?;
let idx = inner.next_turn;
inner.next_turn += 1;
- (out.join(format!("turn-{idx:05}")), inner.session_start_ms)
+ (
+ out.join(format!("turn-{idx:05}")),
+ inner.session_start_ms,
+ inner.generation,
+ )
};
// Strip the daemon-injected `_session_id` (and any other reserved
@@ -415,28 +497,184 @@ impl RecordingSession {
// in action.json's `arguments`. The injection point is the daemon
// `call` branch (serve.rs); recording is the single chokepoint where
// those internal keys must not leak into the persisted trajectory.
- let args = strip_internal_keys(args);
+ let args = strip_internal_keys(args).into_owned();
+ use crate::tool_args::ArgsExt;
+ let mut window_id = args.opt_u64("window_id");
+ let pid = args.opt_i64("pid");
+ let mut element_index = args.opt_u64("element_index");
+ if let (Some(pid), Some(token)) = (
+ pid.and_then(|pid| i32::try_from(pid).ok()),
+ args.get("element_token").and_then(Value::as_str),
+ ) {
+ if let Ok((resolved_window, resolved_index)) =
+ crate::element_token::global().resolve(pid, token)
+ {
+ window_id = Some(u64::from(resolved_window));
+ element_index = u64::try_from(resolved_index).ok();
+ }
+ }
+ let click_point = resolve_click_point(tool_name, &args, window_id, pid, element_index);
+ let before = capture_turn(window_id, pid);
- if let Err(e) = write_turn(
- &turn_dir,
- tool_name,
- args.as_ref(),
- result_text,
+ let mut inner = self.inner.lock().unwrap();
+ if !inner.enabled || inner.generation != generation {
+ return None;
+ }
+ if let Err(error) = write_phase_artifacts(&turn_dir, "before", &before) {
+ inner.last_error = Some(error.to_string());
+ }
+ drop(inner);
+
+ Some(PendingTurn {
+ generation,
+ turn_dir,
+ tool_name: tool_name.to_owned(),
+ args,
start_ms,
session_start_ms,
- ) {
- let mut inner = self.inner.lock().unwrap();
- inner.last_error = Some(e.to_string());
+ window_id,
+ pid,
+ click_point,
+ before,
+ })
+ }
+
+ /// Finalize a previously reserved turn after tool dispatch.
+ pub fn finish_turn(&self, pending: PendingTurn, result_text: &str) {
+ let mut inner = self.inner.lock().unwrap();
+ if !inner.enabled || inner.generation != pending.generation {
+ tracing::warn!(
+ target: "recording",
+ "discarding a turn from an inactive recording generation"
+ );
+ return;
}
+ if let Err(error) = write_turn(pending, result_text) {
+ inner.last_error = Some(error.to_string());
+ }
+ }
+
+ /// Compatibility helper for callers that only report completed calls.
+ /// New dispatch paths should use `begin_turn` and `finish_turn` so the
+ /// before phase is captured before the action changes application state.
+ pub fn record(&self, tool_name: &str, args: &Value, result_text: &str, start_ms: u64) {
+ let Some(pending) = self.begin_turn(tool_name, args, start_ms) else {
+ return;
+ };
+ self.finish_turn(pending, result_text);
}
}
impl Default for RecordingSession {
- fn default() -> Self { Self::new() }
+ fn default() -> Self {
+ Self::new()
+ }
}
// ── helpers ───────────────────────────────────────────────────────────────────
+fn capture_turn(window_id: Option<u64>, pid: Option<i64>) -> TurnCapture {
+ let screenshot = SCREENSHOT_FN
+ .get()
+ .map(|capture| capture(window_id, pid))
+ .unwrap_or_else(|| ScreenshotCapture::unavailable("capture_hook_unavailable"));
+ TurnCapture {
+ state: AX_SNAPSHOT_FN
+ .get()
+ .and_then(|capture| capture(window_id, pid)),
+ screenshot: screenshot.png,
+ screenshot_classification: screenshot.classification,
+ }
+}
+
+fn resolve_click_point(
+ tool_name: &str,
+ args: &Value,
+ window_id: Option<u64>,
+ pid: Option<i64>,
+ element_index: Option<u64>,
+) -> Option<(f64, f64)> {
+ use crate::tool_args::ArgsExt;
+ if !matches!(tool_name, "click" | "double_click" | "right_click") {
+ return None;
+ }
+ match (args.opt_f64("x"), args.opt_f64("y")) {
+ (Some(x), Some(y)) => Some((x, y)),
+ _ => match (window_id, pid, element_index, ELEMENT_BOUNDS_FN.get()) {
+ (Some(wid), Some(pid), Some(index), Some(resolve)) => u32::try_from(index)
+ .ok()
+ .and_then(|index| resolve(wid, pid, index)),
+ _ => None,
+ },
+ }
+}
+
+fn write_phase_artifacts(
+ turn_dir: &Path,
+ phase: &str,
+ capture: &TurnCapture,
+) -> anyhow::Result<()> {
+ std::fs::create_dir_all(turn_dir)?;
+ if let Some(state) = &capture.state {
+ std::fs::write(turn_dir.join(format!("{phase}_state.json")), state)?;
+ }
+ if let Some(screenshot) = &capture.screenshot {
+ std::fs::write(turn_dir.join(format!("{phase}.png")), screenshot)?;
+ }
+ Ok(())
+}
+
+fn capture_status(
+ captured: bool,
+ expected: bool,
+ classification: Option<&'static str>,
+) -> Value {
+ if captured {
+ serde_json::json!({ "status": "captured" })
+ } else if expected {
+ serde_json::json!({
+ "status": "unavailable",
+ "classification": classification.unwrap_or("capture_failed")
+ })
+ } else {
+ serde_json::json!({
+ "status": "not_applicable",
+ "classification": "no_target_pid"
+ })
+ }
+}
+
+fn write_evidence_manifest(
+ turn_dir: &Path,
+ before: &TurnCapture,
+ after: &TurnCapture,
+ state_expected: bool,
+ click_expected: bool,
+ click_captured: bool,
+) -> anyhow::Result<()> {
+ let manifest = serde_json::json!({
+ "schema": "cua-turn-evidence/v1",
+ "before": {
+ "state": capture_status(before.state.is_some(), state_expected, None),
+ "screenshot": capture_status(
+ before.screenshot.is_some(),
+ true,
+ before.screenshot_classification,
+ ),
+ },
+ "after": {
+ "state": capture_status(after.state.is_some(), state_expected, None),
+ "screenshot": capture_status(
+ after.screenshot.is_some(),
+ true,
+ after.screenshot_classification,
+ ),
+ },
+ "click": capture_status(click_captured, click_expected, None),
+ });
+ write_json_atomic(&turn_dir.join("evidence.json"), &manifest)
+}
+
/// Drop reserved internal keys (any `_`-prefixed key, e.g. the daemon-injected
/// `_session_id`) from a tool-call args object so they never persist into a
/// recorded `action.json`. Returns the value unchanged when it isn't an object
@@ -455,42 +693,26 @@ fn strip_internal_keys(args: &Value) -> std::borrow::Cow<'_, Value> {
}
}
-fn write_turn(
- turn_dir: &Path,
- tool_name: &str,
- args: &Value,
- result_text: &str,
- start_ms: u64,
- session_start_ms: u64,
-) -> anyhow::Result<()> {
- std::fs::create_dir_all(turn_dir)?;
+fn write_turn(pending: PendingTurn, result_text: &str) -> anyhow::Result<()> {
+ let PendingTurn {
+ generation: _,
+ turn_dir,
+ tool_name,
+ args,
+ start_ms,
+ session_start_ms,
+ window_id,
+ pid,
+ click_point,
+ before,
+ } = pending;
+ std::fs::create_dir_all(&turn_dir)?;
let now = now_ms();
-
- use crate::tool_args::ArgsExt;
- // Extract window_id and pid from args for screenshot capture.
- let window_id = args.opt_u64("window_id");
- let pid = args.opt_i64("pid");
- let element_index = args.opt_u64("element_index");
-
- // Extract click point for click-family tools. Falls back to the
- // platform element_index → window-local-pixels resolver when the call
- // used `element_index` instead of explicit `x, y`, so click.png is
- // written for AX-indexed clicks too.
- let click_point: Option<(f64, f64)> = if matches!(
- tool_name, "click" | "double_click" | "right_click"
- ) {
- match (args.opt_f64("x"), args.opt_f64("y")) {
- (Some(x), Some(y)) => Some((x, y)),
- _ => match (window_id, pid, element_index, ELEMENT_BOUNDS_FN.get()) {
- (Some(wid), Some(p), Some(idx), Some(f)) => {
- u32::try_from(idx).ok().and_then(|idx32| f(wid, p, idx32))
- }
- _ => None,
- },
- }
- } else {
- None
- };
+ let after = capture_turn(window_id, pid);
+ let click_expected = matches!(
+ tool_name.as_str(),
+ "click" | "double_click" | "right_click"
+ );
let mut payload = serde_json::json!({
"tool": tool_name,
@@ -504,29 +726,38 @@ fn write_turn(
payload["click_point"] = serde_json::json!({"x": cx, "y": cy});
}
write_json_atomic(&turn_dir.join("action.json"), &payload)?;
+ write_phase_artifacts(&turn_dir, "after", &after)?;
- // Post-action AX/UIA snapshot — omitted on platforms that don't expose
- // a cheap snapshot helper (today: Linux ATSPI).
- if let Some(ax_fn) = AX_SNAPSHOT_FN.get() {
- if let Some(json_bytes) = ax_fn(window_id, pid) {
- let _ = std::fs::write(turn_dir.join("app_state.json"), &json_bytes);
- }
+ // Preserve the original post-action names for existing trajectory readers.
+ if let Some(state) = &after.state {
+ std::fs::write(turn_dir.join("app_state.json"), state)?;
+ }
+ if let Some(screenshot) = &after.screenshot {
+ std::fs::write(turn_dir.join("screenshot.png"), screenshot)?;
}
- // Capture screenshot if a callback is registered.
- if let Some(screenshot_fn) = SCREENSHOT_FN.get() {
- if let Some(png_bytes) = screenshot_fn(window_id, pid) {
- let _ = std::fs::write(turn_dir.join("screenshot.png"), &png_bytes);
- // Write click.png (screenshot + red crosshair) for click-family tools.
- if let Some((cx, cy)) = click_point {
- if let Some(marker_fn) = CLICK_MARKER_FN.get() {
- if let Some(click_png) = marker_fn(&png_bytes, cx, cy) {
- let _ = std::fs::write(turn_dir.join("click.png"), &click_png);
- }
- }
- }
+ // A click marker describes where the action was aimed, so ground it on
+ // the pre-action image. This also keeps modal-dismiss evidence available
+ // after the modal HWND has closed.
+ let mut click_captured = false;
+ if let (Some((cx, cy)), Some(screenshot), Some(marker)) = (
+ click_point,
+ before.screenshot.as_deref(),
+ CLICK_MARKER_FN.get(),
+ ) {
+ if let Some(click_png) = marker(screenshot, cx, cy) {
+ std::fs::write(turn_dir.join("click.png"), click_png)?;
+ click_captured = true;
}
}
+ write_evidence_manifest(
+ &turn_dir,
+ &before,
+ &after,
+ pid.is_some(),
+ click_expected,
+ click_captured,
+ )?;
Ok(())
}
@@ -593,3 +824,239 @@ fn expand_tilde(path: &str) -> PathBuf {
}
PathBuf::from(path)
}
+
+fn validate_video_metadata(meta: VideoMetadata) -> anyhow::Result<VideoMetadata> {
+ if !meta.finalized {
+ anyhow::bail!("video backend did not finalize {}", meta.path.display());
+ }
+ let output = std::fs::metadata(&meta.path).map_err(|error| {
+ anyhow::anyhow!(
+ "finalized video is missing at {}: {error}",
+ meta.path.display()
+ )
+ })?;
+ if output.len() == 0 {
+ anyhow::bail!("finalized video is empty at {}", meta.path.display());
+ }
+ Ok(meta)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ struct FailingVideo;
+
+ impl VideoBackend for FailingVideo {
+ fn stop(self: Box<Self>) -> anyhow::Result<VideoMetadata> {
+ anyhow::bail!("recorder did not finalize")
+ }
+ }
+
+ #[test]
+ fn turn_capture_brackets_action_and_preserves_post_action_aliases() {
+ static SCREENSHOTS: AtomicUsize = AtomicUsize::new(0);
+ static STATES: AtomicUsize = AtomicUsize::new(0);
+ set_screenshot_fn(|window_id, pid| {
+ if (window_id, pid) == (Some(2), Some(1)) {
+ let phase = SCREENSHOTS.fetch_add(1, Ordering::SeqCst);
+ return Some(if phase == 0 {
+ b"before".to_vec()
+ } else {
+ b"after".to_vec()
+ });
+ }
+ // Other recording tests share this process-global hook and may run
+ // concurrently. Give them stable bytes without advancing this
+ // test's before/after phase counter.
+ Some(b"after".to_vec())
+ });
+ set_ax_snapshot_fn(|_, _| {
+ let phase = STATES.fetch_add(1, Ordering::SeqCst);
+ Some(format!(r#"{{"phase":{phase}}}"#).into_bytes())
+ });
+ set_click_marker_fn(|_, _, _| Some(b"click".to_vec()));
+ set_element_bounds_fn(|window_id, pid, element_index| {
+ Some((window_id as f64 + element_index as f64, pid as f64))
+ });
+
+ let output_dir = std::env::temp_dir().join(format!(
+ "cua-recording-turn-evidence-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ let session = RecordingSession::new();
+ {
+ let mut inner = session.inner.lock().expect("recording lock");
+ inner.enabled = true;
+ inner.output_dir = Some(output_dir.clone());
+ inner.session_start_ms = now_ms();
+ }
+ let pending = session
+ .begin_turn(
+ "click",
+ &serde_json::json!({"pid": 1, "window_id": 2, "x": 3, "y": 4}),
+ now_ms(),
+ )
+ .expect("recording should reserve a turn");
+ let turn = output_dir.join("turn-00001");
+ assert_eq!(std::fs::read(turn.join("before.png")).unwrap(), b"before");
+ assert!(!turn.join("after.png").exists());
+
+ session.finish_turn(pending, "clicked");
+ assert_eq!(std::fs::read(turn.join("after.png")).unwrap(), b"after");
+ assert_eq!(
+ std::fs::read(turn.join("screenshot.png")).unwrap(),
+ std::fs::read(turn.join("after.png")).unwrap()
+ );
+ assert_eq!(
+ std::fs::read(turn.join("app_state.json")).unwrap(),
+ std::fs::read(turn.join("after_state.json")).unwrap()
+ );
+ assert_eq!(std::fs::read(turn.join("click.png")).unwrap(), b"click");
+
+ let snapshot_id = crate::element_token::global().register_snapshot(1, 77, 1);
+ let token = crate::element_token::token_for(snapshot_id, 0);
+ let pending = session
+ .begin_turn(
+ "click",
+ &serde_json::json!({"pid": 1, "element_token": token}),
+ now_ms(),
+ )
+ .expect("token-only click should reserve a targeted turn");
+ session.finish_turn(pending, "token click");
+ let token_turn = output_dir.join("turn-00002");
+ let token_action: Value = serde_json::from_slice(
+ &std::fs::read(token_turn.join("action.json")).expect("read token action"),
+ )
+ .expect("parse token action");
+ assert_eq!(token_action["click_point"]["x"], 77.0);
+ assert_eq!(token_action["click_point"]["y"], 1.0);
+ assert!(token_turn.join("click.png").exists());
+
+ let files = [
+ "action.json",
+ "app_state.json",
+ "screenshot.png",
+ "click.png",
+ "before_state.json",
+ "before.png",
+ "after_state.json",
+ "after.png",
+ "evidence.json",
+ ];
+ for directory in [&turn, &token_turn] {
+ for file in files {
+ std::fs::remove_file(directory.join(file)).expect("remove turn fixture file");
+ }
+ std::fs::remove_dir(directory).expect("remove turn fixture directory");
+ }
+ std::fs::remove_dir(&output_dir).expect("remove recording fixture directory");
+ }
+
+ #[test]
+ fn stale_recording_generation_cannot_finalize_a_reserved_turn() {
+ let output_dir = std::env::temp_dir().join(format!(
+ "cua-recording-generation-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ let session = RecordingSession::new();
+ {
+ let mut inner = session.inner.lock().expect("recording lock");
+ inner.enabled = true;
+ inner.generation = 1;
+ inner.output_dir = Some(output_dir.clone());
+ inner.session_start_ms = now_ms();
+ }
+ let pending = session
+ .begin_turn("click", &serde_json::json!({"x": 1, "y": 2}), now_ms())
+ .expect("reserve first generation turn");
+ session.inner.lock().unwrap().generation = 2;
+ session.finish_turn(pending, "must be discarded");
+
+ let turn = output_dir.join("turn-00001");
+ assert!(!turn.join("action.json").exists());
+ for entry in std::fs::read_dir(&turn).expect("read partial turn") {
+ std::fs::remove_file(entry.expect("turn entry").path()).expect("remove partial file");
+ }
+ std::fs::remove_dir(&turn).expect("remove partial turn");
+ std::fs::remove_dir(&output_dir).expect("remove recording directory");
+ }
+
+ #[test]
+ fn stop_owner_surfaces_video_finalization_failure() {
+ let output_dir = std::env::temp_dir().join(format!(
+ "cua-recording-stop-failure-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ std::fs::create_dir_all(&output_dir).expect("create recording test directory");
+ let session = RecordingSession::new();
+ {
+ let mut inner = session.inner.lock().expect("recording lock");
+ inner.enabled = true;
+ inner.output_dir = Some(output_dir.clone());
+ inner.video = Some(Box::new(FailingVideo));
+ }
+
+ let error = session
+ .stop_owner(None)
+ .expect_err("video finalization failure must reach the caller");
+ assert!(error.to_string().contains("recorder did not finalize"));
+ let state = session.current_state();
+ assert!(!state.enabled);
+ assert!(state.last_video_path.is_none());
+ assert_eq!(
+ state.last_error.as_deref(),
+ Some("recorder did not finalize")
+ );
+
+ let manifest: Value = serde_json::from_slice(
+ &std::fs::read(output_dir.join("session.json")).expect("read session manifest"),
+ )
+ .expect("parse session manifest");
+ assert_eq!(manifest["video"]["present"], false);
+ assert_eq!(manifest["video"]["error"], "recorder did not finalize");
+ let _ = std::fs::remove_dir_all(output_dir);
+ }
+
+ #[test]
+ fn video_metadata_requires_finalized_nonempty_output() {
+ let output_dir = std::env::temp_dir().join(format!(
+ "cua-recording-metadata-{}-{}",
+ std::process::id(),
+ now_ms()
+ ));
+ std::fs::create_dir_all(&output_dir).expect("create video metadata test directory");
+ let path = output_dir.join("recording.mp4");
+ std::fs::write(&path, b"video").expect("write video fixture");
+
+ let error = validate_video_metadata(VideoMetadata {
+ path: path.clone(),
+ duration_ms: 1,
+ finalized: false,
+ })
+ .expect_err("unfinalized output must fail");
+ assert!(error.to_string().contains("did not finalize"));
+
+ std::fs::write(&path, []).expect("empty video fixture");
+ let error = validate_video_metadata(VideoMetadata {
+ path: path.clone(),
+ duration_ms: 1,
+ finalized: true,
+ })
+ .expect_err("empty finalized output must fail");
+ assert!(error.to_string().contains("is empty"));
+
+ std::fs::write(&path, b"video").expect("restore video fixture");
+ validate_video_metadata(VideoMetadata {
+ path,
+ duration_ms: 1,
+ finalized: true,
+ })
+ .expect("finalized nonempty output must pass");
+ let _ = std::fs::remove_dir_all(output_dir);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
index 0860954f7c..48896552c6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs
@@ -59,13 +59,18 @@ impl Tool for StartRecordingTool {
description: "Start trajectory recording. Every subsequent action-tool \
invocation (click, right_click, scroll, type_text, press_key, hotkey, \
set_value) writes a turn folder under `output_dir`:\n\n\
+ - `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI \
+ state immediately before and after the action.\n\
+ - `before.png` / `after.png` — target-window screenshots immediately \
+ before and after the action.\n\
+ - `evidence.json` — capture status and a stable classification when an \
+ expected artifact could not be captured.\n\
- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n\
- - `screenshot.png` — post-action per-window screenshot of the target's \
- frontmost on-screen window.\n\
+ - `screenshot.png` — compatibility alias of `after.png`.\n\
- `action.json` — tool name, full input arguments, result summary, pid, \
click point (when applicable), ISO-8601 timestamp.\n\
- - `click.png` — for click-family actions only, `screenshot.png` with a \
- red dot drawn at the click point.\n\n\
+ - `click.png` — for click-family actions only, `before.png` with a red \
+ marker at the click point.\n\n\
Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn \
numbering restarts at 1 each time recording is (re-)started.\n\n\
**Video is off by default.** Pass `record_video: true` to also \
@@ -323,9 +328,9 @@ impl Tool for ReplayTrajectoryTool {
// Expand ~/
let dir = {
let p = std::path::PathBuf::from(&dir_str);
- if dir_str.starts_with("~/") {
+ if let Some(relative) = dir_str.strip_prefix("~/") {
if let Ok(home) = std::env::var("HOME") {
- std::path::PathBuf::from(home).join(&dir_str[2..])
+ std::path::PathBuf::from(home).join(relative)
} else { p }
} else { p }
};
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 77c53d14d7..b31c7fae17 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -392,6 +392,19 @@ impl ToolRegistry {
other => other,
};
+ // Reserve and capture the turn before dispatch so recorded evidence
+ // shows the application immediately before the action changed it.
+ let should_record = self.tools.get(resolved_name)
+ .map(|tool| !tool.def().read_only)
+ .unwrap_or(false)
+ && !matches!(
+ resolved_name,
+ "start_recording" | "stop_recording" | "get_recording_state" | "replay_trajectory"
+ );
+ let pending_turn = should_record
+ .then(|| self.recording.begin_turn(resolved_name, &args, start_ms))
+ .flatten();
+
let result = match self.tools.get(resolved_name) {
Some(tool) => tool.invoke(args.clone()).await,
None => return ToolResult::error(format!("Unknown tool: {name}")),
@@ -405,22 +418,14 @@ impl ToolRegistry {
// control tools themselves are excluded so the recorded turn
// stream stays the actual user-action sequence (not the meta
// start/stop frames).
- let should_record = self.tools.get(name)
- .map(|t| !t.def().read_only)
- .unwrap_or(false)
- && !matches!(
- name,
- "start_recording" | "stop_recording" | "get_recording_state" | "replay_trajectory"
- );
-
- if should_record {
+ if let Some(pending_turn) = pending_turn {
let result_text = result.content.iter()
.find_map(|c| {
if let Content::Text { text, .. } = c { Some(text.as_str()) }
else { None }
})
.unwrap_or("");
- self.recording.record(name, &args, result_text, start_ms);
+ self.recording.finish_turn(pending_turn, result_text);
}
// Experimental PiP push — only when --experimental-pip is on argv
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
index b030305eb6..c5264661c9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/Cargo.toml
@@ -9,7 +9,21 @@ description = "Shared harness for cua-driver integration tests: MCP/CLI transpor
publish = false
[dependencies]
+serde = { workspace = true }
serde_json = { workspace = true }
+tempfile = "3"
+
+[target.'cfg(target_os = "linux")'.dependencies]
+x11rb = "0.13"
+
+[target.'cfg(target_os = "macos")'.dependencies]
+core-foundation = "0.10"
+objc2-app-kit = { version = "0.2", features = [
+ "NSApplication",
+ "NSRunningApplication",
+ "NSWorkspace",
+ "libc",
+] }
[target.'cfg(target_os = "windows")'.dependencies]
windows = { version = "0.61", features = [
@@ -17,6 +31,9 @@ windows = { version = "0.61", features = [
# Job Object: assign every spawned test child to a KILL_ON_JOB_CLOSE job so
# the OS terminates the whole tree when the test process dies for ANY reason.
"Win32_System_JobObjects",
+ "Win32_System_Console",
"Win32_Security",
"Win32_System_Threading",
+ "Win32_UI_Input_KeyboardAndMouse",
+ "Win32_UI_WindowsAndMessaging",
] }
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/bin/cua-e2e-report.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/bin/cua-e2e-report.rs
new file mode 100644
index 0000000000..f2654872d5
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/bin/cua-e2e-report.rs
@@ -0,0 +1,101 @@
+use std::path::PathBuf;
+
+use cua_driver_testkit::e2e::{
+ environment_schema_supported, read_json_lines, validate_catalog, CaseDeclaration, CaseResult,
+ EnvironmentRecord, EnvironmentStatus, DECLARATION_SCHEMA,
+};
+
+fn value(args: &[String], name: &str) -> Option<String> {
+ args.windows(2)
+ .find(|pair| pair[0] == name)
+ .map(|pair| pair[1].clone())
+}
+
+fn emit(markdown: String, output: Option<&PathBuf>) {
+ if let Some(path) = output {
+ std::fs::write(path, markdown)
+ .unwrap_or_else(|error| panic!("{}: {error}", path.display()));
+ } else {
+ print!("{markdown}");
+ }
+}
+
+fn print_help() {
+ println!(
+ "cua-e2e-report\n\n\
+Usage:\n cua-e2e-report --declarations <jsonl> --results <jsonl> [OPTIONS]\n\n\
+Options:\n --artifact-root <dir> Resolve and validate linked evidence artifacts\n --environment <jsonl> Include the runner environment record\n --output <path> Write Markdown to a file instead of stdout\n --require-video Require valid trajectory video evidence\n -h, --help Print this help"
+ );
+}
+
+fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args.iter().any(|arg| arg == "--help" || arg == "-h") {
+ print_help();
+ return;
+ }
+ let declarations = value(&args, "--declarations")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| panic!("missing --declarations"));
+ let results = value(&args, "--results")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| panic!("missing --results"));
+ let output = value(&args, "--output").map(PathBuf::from);
+ let artifact_root = value(&args, "--artifact-root").map(PathBuf::from);
+ let environment = value(&args, "--environment").map(PathBuf::from);
+ let require_video = args.iter().any(|arg| arg == "--require-video");
+
+ let declarations: Vec<CaseDeclaration> = read_json_lines(&declarations)
+ .unwrap_or_else(|errors| panic!("invalid declarations:\n{}", errors.join("\n")));
+ let declarations = declarations
+ .into_iter()
+ .map(|declaration| {
+ assert_eq!(
+ declaration.schema, DECLARATION_SCHEMA,
+ "unsupported declaration schema"
+ );
+ declaration.case
+ })
+ .collect::<Vec<_>>();
+ let results: Vec<CaseResult> = read_json_lines(&results)
+ .unwrap_or_else(|errors| panic!("invalid results:\n{}", errors.join("\n")));
+ let mut source_sha = None;
+ let mut environment_record = None;
+ if let Some(path) = environment {
+ let records: Vec<EnvironmentRecord> = read_json_lines(&path)
+ .unwrap_or_else(|errors| panic!("invalid environment:\n{}", errors.join("\n")));
+ assert_eq!(records.len(), 1, "expected one environment record");
+ assert!(
+ environment_schema_supported(&records[0].schema),
+ "unsupported environment schema: {}",
+ records[0].schema,
+ );
+ source_sha = records[0].source_sha.clone();
+ if records[0].status == EnvironmentStatus::Error {
+ emit(
+ format!(
+ "# CUA Driver E2E\n\n**Environment:** ERROR\n\n{}\n",
+ records[0].message
+ ),
+ output.as_ref(),
+ );
+ eprintln!("E2E environment is not ready: {}", records[0].message);
+ std::process::exit(2);
+ }
+ environment_record = records.into_iter().next();
+ }
+ let summary = validate_catalog(
+ &declarations,
+ &results,
+ artifact_root.as_deref(),
+ require_video,
+ )
+ .unwrap_or_else(|errors| panic!("invalid E2E report:\n{}", errors.join("\n")));
+ let markdown = summary.markdown_with_declarations_source_and_environment(
+ &declarations,
+ &results,
+ source_sha.as_deref(),
+ environment_record.as_ref(),
+ );
+ emit(markdown, output.as_ref());
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/driver.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/driver.rs
index 758ae9bf4b..eae7a18d48 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/driver.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/driver.rs
@@ -13,3 +13,8 @@ pub trait Driver {
/// Invoke `tool` with `args`, returning the normalized response.
fn call(&mut self, tool: &str, args: Value) -> ToolResponse;
}
+
+/// Explicit lifecycle capability for canonical per-cell behavioral clips.
+pub trait BehaviorRecording {
+ fn start_behavior_recording(&mut self);
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
new file mode 100644
index 0000000000..f6d47c7c10
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs
@@ -0,0 +1,2261 @@
+//! Typed contracts and result reporting for desktop E2E cells.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs::{File, OpenOptions};
+use std::io::{self, BufRead, BufReader, Write};
+use std::panic::{self, AssertUnwindSafe};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+use serde::{de::DeserializeOwned, Deserialize, Serialize};
+use serde_json::Value;
+
+pub const DECLARATION_SCHEMA: &str = "cua-e2e-case/v2";
+pub const ENVIRONMENT_SCHEMA_V2: &str = "cua-e2e-environment/v2";
+pub const ENVIRONMENT_SCHEMA: &str = "cua-e2e-environment/v3";
+pub const RESULT_SCHEMA: &str = "cua-e2e-result/v2";
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Platform {
+ Windows,
+ Macos,
+ Linux,
+}
+
+impl Platform {
+ pub fn current() -> Self {
+ #[cfg(target_os = "windows")]
+ {
+ Self::Windows
+ }
+ #[cfg(target_os = "macos")]
+ {
+ Self::Macos
+ }
+ #[cfg(target_os = "linux")]
+ {
+ Self::Linux
+ }
+ #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
+ {
+ panic!("unsupported E2E platform")
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DisplayServer {
+ Win32,
+ Quartz,
+ X11,
+ Wayland,
+}
+
+impl DisplayServer {
+ pub fn current() -> Self {
+ #[cfg(target_os = "windows")]
+ {
+ Self::Win32
+ }
+ #[cfg(target_os = "macos")]
+ {
+ Self::Quartz
+ }
+ #[cfg(target_os = "linux")]
+ {
+ match std::env::var("XDG_SESSION_TYPE")
+ .unwrap_or_else(|_| "x11".to_owned())
+ .to_ascii_lowercase()
+ .as_str()
+ {
+ "wayland" => Self::Wayland,
+ _ => Self::X11,
+ }
+ }
+ #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
+ {
+ panic!("unsupported E2E display server")
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Targeting {
+ Ax,
+ Px,
+ Page,
+ NotApplicable,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Delivery {
+ Background,
+ Foreground,
+ NotApplicable,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Scope {
+ Window,
+ Desktop,
+ NotApplicable,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DriverRoute {
+ AxRead,
+ WindowState,
+ UiaInvoke,
+ UiaToggle,
+ UiaSelection,
+ UiaExpandCollapse,
+ UiaValue,
+ UiaRangeValue,
+ UiaScroll,
+ PostMessage,
+ WindowsTargetedInjection,
+ WindowsSendInput,
+ WindowsShellExecute,
+ WindowsPrintWindow,
+ WindowsOverlay,
+ MacosAxAction,
+ MacosAxValue,
+ MacosCgEventPid,
+ MacosCgEventHid,
+ LinuxAtSpiAction,
+ LinuxAtSpiValue,
+ LinuxXSendEvent,
+ LinuxXTest,
+ LinuxLibei,
+ LinuxWaylandVirtualPointer,
+ LinuxCuaCompositorInject,
+ Cdp,
+ Composite,
+}
+
+pub fn shared_web_route(
+ platform: Platform,
+ display_server: DisplayServer,
+ action: &str,
+ targeting: Targeting,
+ delivery: Delivery,
+) -> Result<DriverRoute, String> {
+ shared_web_route_for_environment(
+ platform,
+ display_server,
+ action,
+ targeting,
+ delivery,
+ nested_inject_from_env(),
+ )
+}
+
+fn shared_web_route_for_environment(
+ platform: Platform,
+ display_server: DisplayServer,
+ action: &str,
+ targeting: Targeting,
+ delivery: Delivery,
+ nested_inject: bool,
+) -> Result<DriverRoute, String> {
+ use DriverRoute as Route;
+
+ let pointer_or_key_route = |background, foreground| match delivery {
+ Delivery::Background => Ok(background),
+ Delivery::Foreground => Ok(foreground),
+ Delivery::NotApplicable => Err(format!("{action}: delivery mode is required")),
+ };
+ match (platform, display_server, targeting, action) {
+ (Platform::Windows, DisplayServer::Win32, Targeting::Px, _) => {
+ pointer_or_key_route(Route::WindowsTargetedInjection, Route::WindowsSendInput)
+ }
+ (Platform::Windows, DisplayServer::Win32, Targeting::Ax, "left_click")
+ | (Platform::Windows, DisplayServer::Win32, Targeting::Ax, "child_window") => {
+ Ok(Route::UiaInvoke)
+ }
+ (Platform::Windows, DisplayServer::Win32, Targeting::Ax, "type_text") => {
+ Ok(Route::UiaValue)
+ }
+ (Platform::Windows, DisplayServer::Win32, Targeting::Ax, "scroll") => {
+ Ok(Route::UiaScroll)
+ }
+ (
+ Platform::Windows,
+ DisplayServer::Win32,
+ Targeting::Ax,
+ "right_click" | "double_click" | "press_key" | "hotkey",
+ ) => pointer_or_key_route(Route::PostMessage, Route::WindowsSendInput),
+ (Platform::Windows, DisplayServer::Win32, Targeting::Ax, "editor_save") => {
+ Ok(Route::Composite)
+ }
+
+ (Platform::Macos, DisplayServer::Quartz, Targeting::Px, _) => {
+ pointer_or_key_route(Route::MacosCgEventPid, Route::MacosCgEventHid)
+ }
+ (Platform::Macos, DisplayServer::Quartz, Targeting::Ax, "left_click")
+ | (Platform::Macos, DisplayServer::Quartz, Targeting::Ax, "child_window") => {
+ Ok(Route::MacosAxAction)
+ }
+ (Platform::Macos, DisplayServer::Quartz, Targeting::Ax, "scroll") => {
+ Ok(Route::Composite)
+ }
+ (Platform::Macos, DisplayServer::Quartz, Targeting::Ax, "type_text") => {
+ Ok(Route::MacosAxValue)
+ }
+ (
+ Platform::Macos,
+ DisplayServer::Quartz,
+ Targeting::Ax,
+ "right_click" | "double_click" | "press_key" | "hotkey",
+ ) => pointer_or_key_route(Route::MacosCgEventPid, Route::MacosCgEventHid),
+ (Platform::Macos, DisplayServer::Quartz, Targeting::Ax, "editor_save") => {
+ Ok(Route::Composite)
+ }
+
+ (Platform::Linux, DisplayServer::Wayland, Targeting::Px, _) if nested_inject =>
+ {
+ Ok(Route::LinuxCuaCompositorInject)
+ }
+ (Platform::Linux, DisplayServer::Wayland, Targeting::Px, _) => {
+ Ok(Route::LinuxWaylandVirtualPointer)
+ }
+ (Platform::Linux, DisplayServer::X11, Targeting::Px, _) => {
+ pointer_or_key_route(Route::LinuxXSendEvent, Route::LinuxXTest)
+ }
+ (Platform::Linux, DisplayServer::Wayland, Targeting::Ax, "type_text")
+ if nested_inject =>
+ {
+ Ok(Route::LinuxCuaCompositorInject)
+ }
+ (
+ Platform::Linux,
+ DisplayServer::X11 | DisplayServer::Wayland,
+ Targeting::Ax,
+ "left_click" | "child_window" | "scroll",
+ ) => Ok(Route::LinuxAtSpiAction),
+ (
+ Platform::Linux,
+ DisplayServer::X11 | DisplayServer::Wayland,
+ Targeting::Ax,
+ "type_text",
+ ) => Ok(Route::LinuxAtSpiValue),
+ (
+ Platform::Linux,
+ DisplayServer::X11,
+ Targeting::Ax,
+ "right_click" | "double_click" | "press_key" | "hotkey",
+ ) => pointer_or_key_route(Route::LinuxXSendEvent, Route::LinuxXTest),
+ (
+ Platform::Linux,
+ DisplayServer::Wayland,
+ Targeting::Ax,
+ "right_click" | "double_click" | "press_key" | "hotkey",
+ ) if nested_inject => Ok(Route::LinuxCuaCompositorInject),
+ (
+ Platform::Linux,
+ DisplayServer::Wayland,
+ Targeting::Ax,
+ "right_click" | "double_click" | "press_key" | "hotkey",
+ ) => Ok(Route::LinuxWaylandVirtualPointer),
+ (
+ Platform::Linux,
+ DisplayServer::X11 | DisplayServer::Wayland,
+ Targeting::Ax,
+ "editor_save",
+ ) => Ok(Route::Composite),
+ _ => Err(format!(
+ "no shared route for {platform:?}/{display_server:?}/{action}/{targeting:?}/{delivery:?}"
+ )),
+ }
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum OracleKind {
+ FixtureState,
+ AxState,
+ Pixels,
+ Focus,
+ ZOrder,
+ Cursor,
+ NoLeakedInput,
+ Protocol,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum RefusalCode {
+ BackgroundUnavailable,
+ BackgroundOccluded,
+ BackgroundUipiBlocked,
+}
+
+impl RefusalCode {
+ pub fn from_driver_code(code: &str) -> Option<Self> {
+ match code {
+ "background_unavailable" => Some(Self::BackgroundUnavailable),
+ "background_occluded" => Some(Self::BackgroundOccluded),
+ "background_uipi_blocked" => Some(Self::BackgroundUipiBlocked),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+#[serde(rename_all = "snake_case", tag = "kind")]
+pub enum ContractExpectation {
+ Deliver,
+ Refuse { allowed_codes: Vec<RefusalCode> },
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TestStatus {
+ Pass,
+ Fail,
+ Skip,
+ EnvironmentError,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EnvironmentStatus {
+ Ready,
+ Error,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct EnvironmentRecord {
+ pub schema: String,
+ pub platform: Platform,
+ pub display_server: DisplayServer,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub compositor: Option<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub input_backends: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub source_sha: Option<String>,
+ pub status: EnvironmentStatus,
+ pub duration_ms: u128,
+ pub message: String,
+}
+
+impl EnvironmentRecord {
+ pub fn ready(duration: Duration) -> Self {
+ Self {
+ schema: ENVIRONMENT_SCHEMA.to_owned(),
+ platform: Platform::current(),
+ display_server: DisplayServer::current(),
+ compositor: compositor_from_env(),
+ input_backends: input_backends_from_env(),
+ source_sha: source_sha_from_env(),
+ status: EnvironmentStatus::Ready,
+ duration_ms: duration.as_millis(),
+ message: String::new(),
+ }
+ }
+
+ pub fn error(duration: Duration, message: impl Into<String>) -> Self {
+ Self {
+ schema: ENVIRONMENT_SCHEMA.to_owned(),
+ platform: Platform::current(),
+ display_server: DisplayServer::current(),
+ compositor: compositor_from_env(),
+ input_backends: input_backends_from_env(),
+ source_sha: source_sha_from_env(),
+ status: EnvironmentStatus::Error,
+ duration_ms: duration.as_millis(),
+ message: message.into(),
+ }
+ }
+}
+
+pub fn environment_schema_supported(schema: &str) -> bool {
+ matches!(schema, ENVIRONMENT_SCHEMA | ENVIRONMENT_SCHEMA_V2)
+}
+
+fn nested_inject_from_env() -> bool {
+ std::env::var_os("CUA_INJECT_SOCKET").is_some()
+}
+
+fn compositor_from_env() -> Option<String> {
+ if let Ok(value) = std::env::var("CUA_E2E_COMPOSITOR") {
+ if !value.trim().is_empty() {
+ return Some(value);
+ }
+ }
+ match (Platform::current(), DisplayServer::current()) {
+ (Platform::Windows, DisplayServer::Win32) => Some("windows-desktop".to_owned()),
+ (Platform::Macos, DisplayServer::Quartz) => Some("windowserver".to_owned()),
+ (Platform::Linux, DisplayServer::X11) => Some("openbox-x11".to_owned()),
+ (Platform::Linux, DisplayServer::Wayland) if nested_inject_from_env() => {
+ Some("cua-compositor-nested".to_owned())
+ }
+ (Platform::Linux, DisplayServer::Wayland) => {
+ let desktop = std::env::var("XDG_CURRENT_DESKTOP")
+ .unwrap_or_default()
+ .to_ascii_lowercase();
+ if desktop.contains("sway") {
+ Some("sway".to_owned())
+ } else if desktop.contains("gnome") {
+ Some("gnome-mutter".to_owned())
+ } else if desktop.contains("kde") || desktop.contains("plasma") {
+ Some("kwin".to_owned())
+ } else {
+ Some("wayland-unknown".to_owned())
+ }
+ }
+ _ => None,
+ }
+}
+
+fn input_backends_from_env() -> Vec<String> {
+ if let Ok(value) = std::env::var("CUA_E2E_INPUT_BACKENDS") {
+ let mut backends = value
+ .split(',')
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned)
+ .collect::<Vec<_>>();
+ backends.sort();
+ backends.dedup();
+ return backends;
+ }
+ match (Platform::current(), DisplayServer::current()) {
+ (Platform::Windows, DisplayServer::Win32) => vec!["win32".to_owned(), "uia".to_owned()],
+ (Platform::Macos, DisplayServer::Quartz) => {
+ vec!["accessibility".to_owned(), "cg-event".to_owned()]
+ }
+ (Platform::Linux, DisplayServer::X11) => vec![
+ "atspi".to_owned(),
+ "xsend-event".to_owned(),
+ "xtest".to_owned(),
+ ],
+ (Platform::Linux, DisplayServer::Wayland) if nested_inject_from_env() => {
+ vec!["atspi".to_owned(), "cua-compositor-inject".to_owned()]
+ }
+ (Platform::Linux, DisplayServer::Wayland) => vec!["atspi".to_owned()],
+ _ => Vec::new(),
+ }
+}
+
+fn source_sha_from_env() -> Option<String> {
+ std::env::var("CUA_E2E_SOURCE_SHA")
+ .ok()
+ .filter(|sha| !sha.is_empty())
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ObservedBehavior {
+ Delivered,
+ Refused,
+ NoEffect,
+ Error,
+ NotRun,
+}
+
+#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
+pub struct Evidence {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub video: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub trajectory: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub screenshot: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub log: Option<String>,
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct CaseSpec {
+ pub cell_id: String,
+ pub platform: Platform,
+ pub display_server: DisplayServer,
+ pub harness: String,
+ pub toolkit: String,
+ pub action: String,
+ pub targeting: Targeting,
+ pub delivery: Delivery,
+ pub scope: Scope,
+ pub driver_route: DriverRoute,
+ pub expected_behavior: ContractExpectation,
+ pub oracles: Vec<OracleKind>,
+}
+
+impl CaseSpec {
+ #[allow(clippy::too_many_arguments)]
+ pub fn delivered(
+ cell_id: impl Into<String>,
+ harness: impl Into<String>,
+ toolkit: impl Into<String>,
+ action: impl Into<String>,
+ targeting: Targeting,
+ delivery: Delivery,
+ scope: Scope,
+ driver_route: DriverRoute,
+ oracles: Vec<OracleKind>,
+ ) -> Self {
+ Self {
+ cell_id: cell_id.into(),
+ platform: Platform::current(),
+ display_server: DisplayServer::current(),
+ harness: harness.into(),
+ toolkit: toolkit.into(),
+ action: action.into(),
+ targeting,
+ delivery,
+ scope,
+ driver_route,
+ expected_behavior: ContractExpectation::Deliver,
+ oracles,
+ }
+ }
+
+ pub fn expecting_refusal(mut self, allowed_codes: Vec<RefusalCode>) -> Self {
+ self.expected_behavior = ContractExpectation::Refuse { allowed_codes };
+ self
+ }
+
+ pub fn validate(&self) -> Result<(), String> {
+ if self.cell_id.is_empty()
+ || !self
+ .cell_id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
+ {
+ return Err(format!("{}: cell id is not artifact-safe", self.cell_id));
+ }
+ if self.oracles.is_empty() {
+ return Err(format!("{}: no external oracle declared", self.cell_id));
+ }
+ if let ContractExpectation::Refuse { allowed_codes } = &self.expected_behavior {
+ if self.delivery != Delivery::Background {
+ return Err(format!(
+ "{}: only background delivery may declare refusal",
+ self.cell_id
+ ));
+ }
+ if allowed_codes.is_empty() {
+ return Err(format!("{}: refusal has no allowed code", self.cell_id));
+ }
+ for required in [
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ] {
+ if !self.oracles.contains(&required) {
+ return Err(format!(
+ "{}: refusal is missing {:?} oracle",
+ self.cell_id, required
+ ));
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+fn native_cell_id(toolkit: &str, action: &str, targeting: Targeting, delivery: Delivery) -> String {
+ let targeting = match targeting {
+ Targeting::Ax => "ax",
+ Targeting::Px => "px",
+ Targeting::Page => "page",
+ Targeting::NotApplicable => "not-applicable",
+ };
+ let delivery = match delivery {
+ Delivery::Background => "background",
+ Delivery::Foreground => "foreground",
+ Delivery::NotApplicable => "not-applicable",
+ };
+ format!(
+ "{}-{toolkit}-{action}-{targeting}-{delivery}",
+ std::env::consts::OS
+ )
+ .replace('_', "-")
+}
+
+pub fn native_background_case(
+ toolkit: &str,
+ action: &str,
+ targeting: Targeting,
+ route: DriverRoute,
+) -> CaseSpec {
+ let mut oracles = vec![
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ];
+ if DisplayServer::current() != DisplayServer::Wayland {
+ oracles.push(OracleKind::Cursor);
+ }
+ CaseSpec::delivered(
+ native_cell_id(toolkit, action, targeting, Delivery::Background),
+ toolkit,
+ toolkit,
+ action,
+ targeting,
+ Delivery::Background,
+ Scope::Window,
+ route,
+ oracles,
+ )
+}
+
+pub fn native_foreground_case(
+ toolkit: &str,
+ action: &str,
+ targeting: Targeting,
+ route: DriverRoute,
+) -> CaseSpec {
+ CaseSpec::delivered(
+ native_cell_id(toolkit, action, targeting, Delivery::Foreground),
+ toolkit,
+ toolkit,
+ action,
+ targeting,
+ Delivery::Foreground,
+ Scope::Window,
+ route,
+ vec![OracleKind::FixtureState],
+ )
+}
+
+pub fn native_readonly_case(
+ toolkit: &str,
+ action: &str,
+ targeting: Targeting,
+ route: DriverRoute,
+ oracles: Vec<OracleKind>,
+) -> CaseSpec {
+ CaseSpec::delivered(
+ native_cell_id(toolkit, action, targeting, Delivery::NotApplicable),
+ toolkit,
+ toolkit,
+ action,
+ targeting,
+ Delivery::NotApplicable,
+ Scope::Window,
+ route,
+ oracles,
+ )
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct CaseDeclaration {
+ pub schema: String,
+ #[serde(flatten)]
+ pub case: CaseSpec,
+}
+
+impl From<CaseSpec> for CaseDeclaration {
+ fn from(case: CaseSpec) -> Self {
+ Self {
+ schema: DECLARATION_SCHEMA.to_owned(),
+ case,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct Observation {
+ pub behavior: ObservedBehavior,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub refusal_code: Option<RefusalCode>,
+ pub passed_oracles: Vec<OracleKind>,
+ pub message: String,
+ pub evidence: Evidence,
+}
+
+impl Observation {
+ pub fn delivered(passed_oracles: Vec<OracleKind>, evidence: Evidence) -> Self {
+ Self {
+ behavior: ObservedBehavior::Delivered,
+ refusal_code: None,
+ passed_oracles,
+ message: String::new(),
+ evidence,
+ }
+ }
+
+ pub fn delivered_with_fixture_state(mut passed_oracles: Vec<OracleKind>) -> Self {
+ passed_oracles.push(OracleKind::FixtureState);
+ passed_oracles.sort();
+ passed_oracles.dedup();
+ Self::delivered(passed_oracles, Evidence::default())
+ }
+
+ pub fn refused(
+ code: RefusalCode,
+ passed_oracles: Vec<OracleKind>,
+ message: impl Into<String>,
+ evidence: Evidence,
+ ) -> Self {
+ Self {
+ behavior: ObservedBehavior::Refused,
+ refusal_code: Some(code),
+ passed_oracles,
+ message: message.into(),
+ evidence,
+ }
+ }
+
+ pub fn error(message: impl Into<String>, evidence: Evidence) -> Self {
+ Self {
+ behavior: ObservedBehavior::Error,
+ refusal_code: None,
+ passed_oracles: Vec::new(),
+ message: message.into(),
+ evidence,
+ }
+ }
+}
+
+#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
+pub struct CaseResult {
+ pub schema: String,
+ #[serde(flatten)]
+ pub case: CaseSpec,
+ pub test_status: TestStatus,
+ pub observed_behavior: ObservedBehavior,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub refusal_code: Option<RefusalCode>,
+ pub passed_oracles: Vec<OracleKind>,
+ pub duration_ms: u128,
+ pub message: String,
+ pub evidence: Evidence,
+}
+
+impl CaseResult {
+ pub fn evaluate(case: CaseSpec, observation: Observation, duration: Duration) -> Self {
+ let mut failures = Vec::new();
+ if let Err(error) = case.validate() {
+ failures.push(error);
+ }
+ for oracle in &case.oracles {
+ if !observation.passed_oracles.contains(oracle) {
+ failures.push(format!("missing {:?} oracle", oracle));
+ }
+ }
+ match (&case.expected_behavior, observation.behavior) {
+ (ContractExpectation::Deliver, ObservedBehavior::Delivered) => {}
+ (ContractExpectation::Deliver, ObservedBehavior::Refused) => {
+ failures.push("required delivery was refused".to_owned());
+ }
+ (ContractExpectation::Refuse { allowed_codes }, ObservedBehavior::Refused) => {
+ match observation.refusal_code {
+ Some(code) if allowed_codes.contains(&code) => {}
+ Some(code) => failures.push(format!("unexpected refusal code: {code:?}")),
+ None => failures.push("refusal has no structured code".to_owned()),
+ }
+ }
+ (ContractExpectation::Refuse { .. }, ObservedBehavior::Delivered) => {
+ failures.push("unexpected delivery requires contract review".to_owned());
+ }
+ (_, other) => failures.push(format!("observed behavior was {other:?}")),
+ }
+
+ let status = if failures.is_empty() {
+ TestStatus::Pass
+ } else {
+ TestStatus::Fail
+ };
+ let message = [observation.message, failures.join("; ")]
+ .into_iter()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("; ");
+ Self {
+ schema: RESULT_SCHEMA.to_owned(),
+ case,
+ test_status: status,
+ observed_behavior: observation.behavior,
+ refusal_code: observation.refusal_code,
+ passed_oracles: observation.passed_oracles,
+ duration_ms: duration.as_millis(),
+ message,
+ evidence: observation.evidence,
+ }
+ }
+}
+
+#[derive(Debug, Default, Eq, PartialEq)]
+pub struct ValidationSummary {
+ pub delivered: usize,
+ pub refused: usize,
+ pub failed: usize,
+ pub skipped: usize,
+}
+
+impl ValidationSummary {
+ pub fn markdown(&self, results: &[CaseResult]) -> String {
+ let declarations = results
+ .iter()
+ .map(|result| result.case.clone())
+ .collect::<Vec<_>>();
+ self.markdown_with_declarations(&declarations, results)
+ }
+
+ pub fn markdown_with_declarations(
+ &self,
+ declarations: &[CaseSpec],
+ results: &[CaseResult],
+ ) -> String {
+ self.markdown_with_declarations_and_source(declarations, results, None)
+ }
+
+ pub fn markdown_with_declarations_and_source(
+ &self,
+ declarations: &[CaseSpec],
+ results: &[CaseResult],
+ source_sha: Option<&str>,
+ ) -> String {
+ self.markdown_with_declarations_source_and_environment(
+ declarations,
+ results,
+ source_sha,
+ None,
+ )
+ }
+
+ pub fn markdown_with_declarations_source_and_environment(
+ &self,
+ declarations: &[CaseSpec],
+ results: &[CaseResult],
+ source_sha: Option<&str>,
+ environment: Option<&EnvironmentRecord>,
+ ) -> String {
+ let mut output = format!(
+ "# CUA Driver E2E\n\n**Result:** {} delivered, {} refused, {} failed, {} skipped\n\n",
+ self.delivered, self.refused, self.failed, self.skipped
+ );
+ if let Some(source_sha) = source_sha {
+ output.push_str(&format!("**Source SHA:** `{source_sha}`\n\n"));
+ }
+ if let Some(environment) = environment {
+ let compositor = environment.compositor.as_deref().unwrap_or("unknown");
+ let input_backends = if environment.input_backends.is_empty() {
+ "unknown".to_owned()
+ } else {
+ environment.input_backends.join(", ")
+ };
+ output.push_str(&format!(
+ "**Environment:** `{:?}/{:?}` · compositor `{}` · input backends `{}`\n\n",
+ environment.platform,
+ environment.display_server,
+ markdown_inline_code(compositor),
+ markdown_inline_code(&input_backends),
+ ));
+ }
+ output.push_str("## Declared Coverage\n\n");
+ output.push_str(&declared_coverage_markdown(declarations, results));
+ output.push_str("\n## Detailed Results\n\n");
+ output.push_str(
+ "| Cell | Platform | Harness | Action | Targeting | Delivery | Scope | Route | Oracles | Expected | Observed | Status | Duration | Evidence | Details |\n",
+ );
+ output.push_str("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | ---: | --- | --- |\n");
+ for result in results {
+ let evidence = result
+ .evidence
+ .video
+ .as_deref()
+ .or(result.evidence.trajectory.as_deref())
+ .unwrap_or("-");
+ let oracles = result
+ .case
+ .oracles
+ .iter()
+ .map(|oracle| format!("{oracle:?}"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let details = if result.message.is_empty() {
+ "-".to_owned()
+ } else {
+ result.message.replace('|', "\\|").replace('\n', " ")
+ };
+ output.push_str(&format!(
+ "| {} | {:?}/{:?} | {} | {} | {:?} | {:?} | {:?} | {:?} | {} | {:?} | {:?} | {:?} | {} ms | {} | {} |\n",
+ result.case.cell_id,
+ result.case.platform,
+ result.case.display_server,
+ result.case.harness,
+ result.case.action,
+ result.case.targeting,
+ result.case.delivery,
+ result.case.scope,
+ result.case.driver_route,
+ oracles,
+ result.case.expected_behavior,
+ result.observed_behavior,
+ result.test_status,
+ result.duration_ms,
+ evidence,
+ details,
+ ));
+ }
+ output
+ }
+}
+
+fn markdown_inline_code(value: &str) -> String {
+ value.replace('`', "\\`").replace('\n', " ")
+}
+
+#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
+enum CoverageColumn {
+ AxBackground,
+ AxForeground,
+ PxBackground,
+ PxForeground,
+ Page,
+ NotApplicable,
+}
+
+const COVERAGE_COLUMNS: [CoverageColumn; 6] = [
+ CoverageColumn::AxBackground,
+ CoverageColumn::AxForeground,
+ CoverageColumn::PxBackground,
+ CoverageColumn::PxForeground,
+ CoverageColumn::Page,
+ CoverageColumn::NotApplicable,
+];
+
+fn declared_coverage_markdown(declarations: &[CaseSpec], results: &[CaseResult]) -> String {
+ let results_by_cell = results
+ .iter()
+ .map(|result| (result.case.cell_id.as_str(), result))
+ .collect::<BTreeMap<_, _>>();
+ let mut rows = BTreeMap::<(String, String), BTreeMap<CoverageColumn, Vec<String>>>::new();
+
+ for declaration in declarations {
+ let column = coverage_column(declaration);
+ let status = results_by_cell
+ .get(declaration.cell_id.as_str())
+ .map(|result| coverage_status(result))
+ .unwrap_or("MISSING");
+ let label = match column {
+ CoverageColumn::Page => format!("{:?}: {status}", declaration.delivery),
+ CoverageColumn::NotApplicable => format!(
+ "{:?}/{:?}: {status}",
+ declaration.targeting, declaration.delivery
+ ),
+ _ => status.to_owned(),
+ };
+ rows.entry((declaration.harness.clone(), declaration.action.clone()))
+ .or_default()
+ .entry(column)
+ .or_default()
+ .push(label);
+ }
+
+ let mut output = String::from(
+ "| Harness | Action | AX/BG | AX/FG | PX/BG | PX/FG | Page | NotApplicable |\n",
+ );
+ output.push_str("| --- | --- | --- | --- | --- | --- | --- | --- |\n");
+ for ((harness, action), cells) in rows {
+ output.push_str(&format!(
+ "| {} | {} | {} |\n",
+ markdown_table_text(&harness),
+ markdown_table_text(&action),
+ COVERAGE_COLUMNS
+ .iter()
+ .map(|column| render_coverage_cell(cells.get(column)))
+ .collect::<Vec<_>>()
+ .join(" | ")
+ ));
+ }
+ output
+}
+
+fn coverage_column(case: &CaseSpec) -> CoverageColumn {
+ match (case.targeting, case.delivery) {
+ (Targeting::Page, _) => CoverageColumn::Page,
+ (Targeting::Ax, Delivery::Background) => CoverageColumn::AxBackground,
+ (Targeting::Ax, Delivery::Foreground) => CoverageColumn::AxForeground,
+ (Targeting::Px, Delivery::Background) => CoverageColumn::PxBackground,
+ (Targeting::Px, Delivery::Foreground) => CoverageColumn::PxForeground,
+ _ => CoverageColumn::NotApplicable,
+ }
+}
+
+fn coverage_status(result: &CaseResult) -> &'static str {
+ match (result.test_status, result.observed_behavior) {
+ (TestStatus::Pass, ObservedBehavior::Delivered) => "PASS",
+ (TestStatus::Pass, ObservedBehavior::Refused) => "REFUSED",
+ (TestStatus::Pass, _) => "INVALID",
+ (TestStatus::Fail | TestStatus::EnvironmentError, _) => "FAIL",
+ (TestStatus::Skip, _) => "SKIP",
+ }
+}
+
+fn render_coverage_cell(labels: Option<&Vec<String>>) -> String {
+ let Some(labels) = labels else {
+ return "-".to_owned();
+ };
+ let mut counts = BTreeMap::new();
+ for label in labels {
+ *counts.entry(label).or_insert(0usize) += 1;
+ }
+ counts
+ .into_iter()
+ .map(|(label, count)| {
+ if count == 1 {
+ label.clone()
+ } else {
+ format!("{label} ({count})")
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("<br>")
+}
+
+fn markdown_table_text(value: &str) -> String {
+ value.replace('|', "\\|").replace('\n', " ")
+}
+
+pub fn append_json_line<T: Serialize>(path: &Path, value: &T) -> io::Result<()> {
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let mut file = OpenOptions::new().create(true).append(true).open(path)?;
+ serde_json::to_writer(&mut file, value)?;
+ file.write_all(b"\n")
+}
+
+pub fn write_declaration_from_env(case: &CaseSpec) -> io::Result<()> {
+ let Some(path) = std::env::var_os("CUA_E2E_DECLARATIONS_FILE") else {
+ return Ok(());
+ };
+ append_json_line(&PathBuf::from(path), &CaseDeclaration::from(case.clone()))
+}
+
+pub fn write_result_from_env(result: &CaseResult) -> io::Result<()> {
+ let Some(path) = std::env::var_os("CUA_E2E_RESULTS_FILE") else {
+ return Ok(());
+ };
+ append_json_line(&PathBuf::from(path), result)
+}
+
+/// Execute one declared E2E cell, persist its typed result even when the body
+/// panics, and preserve Cargo's failing-test signal.
+pub fn execute_case(case: CaseSpec, test: impl FnOnce(&mut Evidence) -> Observation) -> CaseResult {
+ write_declaration_from_env(&case).expect("write E2E case declaration");
+ let started = Instant::now();
+ let mut evidence = Evidence::default();
+ let outcome = panic::catch_unwind(AssertUnwindSafe(|| test(&mut evidence)));
+ let observation = match outcome {
+ Ok(mut observation) => {
+ if observation.evidence == Evidence::default() {
+ observation.evidence = evidence;
+ }
+ observation
+ }
+ Err(payload) => Observation::error(panic_message(&payload), evidence),
+ };
+ let result = CaseResult::evaluate(case, observation, started.elapsed());
+ write_result_from_env(&result).expect("write E2E case result");
+ assert_eq!(
+ result.test_status,
+ TestStatus::Pass,
+ "{}: {}",
+ result.case.cell_id,
+ result.message
+ );
+ result
+}
+
+pub fn recording_evidence(recording_dir: Option<&Path>) -> Evidence {
+ let Some(recording_dir) = recording_dir else {
+ return Evidence::default();
+ };
+ let relative_dir = std::env::var_os("CUA_E2E_RECORDINGS_ROOT")
+ .map(PathBuf::from)
+ .and_then(|root| recording_dir.strip_prefix(root).ok().map(PathBuf::from))
+ .unwrap_or_else(|| {
+ recording_dir
+ .file_name()
+ .map(PathBuf::from)
+ .unwrap_or_default()
+ });
+ let artifact_dir = PathBuf::from("recordings").join(relative_dir);
+ let path = |name: &str| artifact_dir.join(name).to_string_lossy().replace('\\', "/");
+ Evidence {
+ video: Some(path("recording.mp4")),
+ trajectory: Some(path("trajectory.json")),
+ screenshot: None,
+ log: None,
+ }
+}
+
+fn panic_message(payload: &Box<dyn std::any::Any + Send>) -> String {
+ payload
+ .downcast_ref::<String>()
+ .cloned()
+ .or_else(|| {
+ payload
+ .downcast_ref::<&str>()
+ .map(|message| (*message).to_owned())
+ })
+ .unwrap_or_else(|| "E2E cell panicked without a string payload".to_owned())
+}
+
+pub fn write_environment_from_env(record: &EnvironmentRecord) -> io::Result<()> {
+ let Some(path) = std::env::var_os("CUA_E2E_ENVIRONMENT_FILE") else {
+ return Ok(());
+ };
+ append_json_line(&PathBuf::from(path), record)
+}
+
+pub fn read_json_lines<T: DeserializeOwned>(path: &Path) -> Result<Vec<T>, Vec<String>> {
+ let file = File::open(path).map_err(|error| vec![format!("{}: {error}", path.display())])?;
+ let mut values = Vec::new();
+ let mut errors = Vec::new();
+ for (line_index, line) in BufReader::new(file).lines().enumerate() {
+ match line {
+ Ok(line) if line.trim().is_empty() => {}
+ Ok(line) => match serde_json::from_str(&line) {
+ Ok(value) => values.push(value),
+ Err(error) => {
+ errors.push(format!("{}:{}: {error}", path.display(), line_index + 1))
+ }
+ },
+ Err(error) => errors.push(format!("{}:{}: {error}", path.display(), line_index + 1)),
+ }
+ }
+ if errors.is_empty() {
+ Ok(values)
+ } else {
+ Err(errors)
+ }
+}
+
+pub fn validate_catalog(
+ declarations: &[CaseSpec],
+ results: &[CaseResult],
+ artifact_root: Option<&Path>,
+ require_video: bool,
+) -> Result<ValidationSummary, Vec<String>> {
+ validate_catalog_with_evidence(
+ declarations,
+ results,
+ artifact_root,
+ require_video,
+ require_video,
+ )
+}
+
+pub fn validate_catalog_with_evidence(
+ declarations: &[CaseSpec],
+ results: &[CaseResult],
+ artifact_root: Option<&Path>,
+ require_video: bool,
+ require_turn_evidence: bool,
+) -> Result<ValidationSummary, Vec<String>> {
+ let mut errors = Vec::new();
+ if declarations.is_empty() {
+ errors.push("E2E catalog has no declarations".to_owned());
+ }
+ let mut declared = BTreeMap::new();
+ for case in declarations {
+ if let Err(error) = case.validate() {
+ errors.push(error);
+ }
+ if declared.insert(case.cell_id.clone(), case).is_some() {
+ errors.push(format!("duplicate declaration: {}", case.cell_id));
+ }
+ }
+
+ let mut observed = BTreeSet::new();
+ let mut summary = ValidationSummary::default();
+ for result in results {
+ let cell_id = &result.case.cell_id;
+ if result.schema != RESULT_SCHEMA {
+ errors.push(format!(
+ "unsupported result schema for {cell_id}: {}",
+ result.schema
+ ));
+ }
+ if !observed.insert(cell_id.clone()) {
+ errors.push(format!("duplicate result: {cell_id}"));
+ continue;
+ }
+ match declared.get(cell_id) {
+ Some(case) if **case == result.case => {}
+ Some(_) => errors.push(format!("result contract changed: {cell_id}")),
+ None => errors.push(format!("undeclared result: {cell_id}")),
+ }
+
+ let rebuilt = CaseResult::evaluate(
+ result.case.clone(),
+ Observation {
+ behavior: result.observed_behavior,
+ refusal_code: result.refusal_code,
+ passed_oracles: result.passed_oracles.clone(),
+ message: String::new(),
+ evidence: result.evidence.clone(),
+ },
+ Duration::from_millis(result.duration_ms.min(u64::MAX as u128) as u64),
+ );
+ if rebuilt.test_status != result.test_status {
+ errors.push(format!("invalid status for {cell_id}"));
+ }
+ match result.test_status {
+ TestStatus::Pass => match result.observed_behavior {
+ ObservedBehavior::Delivered => summary.delivered += 1,
+ ObservedBehavior::Refused => summary.refused += 1,
+ _ => errors.push(format!("passing cell has no valid behavior: {cell_id}")),
+ },
+ TestStatus::Fail | TestStatus::EnvironmentError => summary.failed += 1,
+ TestStatus::Skip => summary.skipped += 1,
+ }
+
+ if require_video {
+ let Some(video) = result.evidence.video.as_deref() else {
+ errors.push(format!("missing video evidence: {cell_id}"));
+ continue;
+ };
+ if let Some(root) = artifact_root {
+ let path = root.join(video);
+ if std::fs::metadata(&path)
+ .map(|metadata| metadata.len() == 0)
+ .unwrap_or(true)
+ {
+ errors.push(format!(
+ "video evidence is missing or empty: {}",
+ path.display()
+ ));
+ }
+ }
+ }
+ if require_turn_evidence {
+ match (artifact_root, recording_directory(&result.evidence)) {
+ (Some(root), Some(relative_dir)) => {
+ validate_turn_evidence(
+ &root.join(relative_dir),
+ cell_id,
+ case_requires_action_turn(&result.case),
+ &mut errors,
+ );
+ }
+ (None, _) => errors.push(format!(
+ "cannot validate turn evidence without an artifact root: {cell_id}"
+ )),
+ (_, None) => errors.push(format!(
+ "missing recording path for turn evidence: {cell_id}"
+ )),
+ }
+ }
+ }
+
+ for cell_id in declared.keys() {
+ if !observed.contains(cell_id) {
+ errors.push(format!("missing result: {cell_id}"));
+ }
+ }
+
+ if errors.is_empty() {
+ Ok(summary)
+ } else {
+ Err(errors)
+ }
+}
+
+fn case_requires_action_turn(case: &CaseSpec) -> bool {
+ !matches!(case.driver_route, DriverRoute::AxRead | DriverRoute::WindowState)
+ && case.action != "screenshot"
+}
+
+fn recording_directory(evidence: &Evidence) -> Option<&Path> {
+ evidence
+ .video
+ .as_deref()
+ .or(evidence.trajectory.as_deref())
+ .and_then(|path| Path::new(path).parent())
+}
+
+fn validate_turn_evidence(
+ recording_dir: &Path,
+ cell_id: &str,
+ require_turn: bool,
+ errors: &mut Vec<String>,
+) {
+ let trajectory = recording_dir.join("trajectory.json");
+ match read_json_value(&trajectory) {
+ Ok(manifest) => {
+ if manifest["behavior_video"]["status"] != "finalized" {
+ errors.push(format!(
+ "behavioral video phase is not finalized for {cell_id}: {}",
+ manifest["behavior_video"]["status"]
+ ));
+ }
+ let started = manifest["behavior_video"]["started_at_unix_ms"].as_u64();
+ let baseline = manifest["behavior_video"]["baseline_ready_at_unix_ms"].as_u64();
+ let finalized = manifest["behavior_video"]["finalized_at_unix_ms"].as_u64();
+ if !matches!(
+ (started, baseline, finalized),
+ (Some(started), Some(baseline), Some(finalized))
+ if baseline.saturating_sub(started) >= 250 && finalized >= baseline
+ ) {
+ errors.push(format!(
+ "behavioral video boundary timestamps are invalid for {cell_id}"
+ ));
+ }
+ if !matches!(
+ manifest["hosted_runner_console"]["status"].as_str(),
+ Some("minimized" | "already_minimized" | "not_applicable")
+ ) {
+ errors.push(format!(
+ "hosted-runner console cleanup status is invalid for {cell_id}: {}",
+ manifest["hosted_runner_console"]["status"]
+ ));
+ }
+ }
+ Err(error) => errors.push(format!("invalid trajectory evidence for {cell_id}: {error}")),
+ }
+
+ let mut turns = match std::fs::read_dir(recording_dir) {
+ Ok(entries) => entries
+ .filter_map(Result::ok)
+ .filter(|entry| {
+ entry.file_type().is_ok_and(|kind| kind.is_dir())
+ && entry.file_name().to_string_lossy().starts_with("turn-")
+ })
+ .map(|entry| entry.path())
+ .collect::<Vec<_>>(),
+ Err(error) => {
+ errors.push(format!(
+ "turn evidence directory is unavailable for {cell_id}: {}: {error}",
+ recording_dir.display()
+ ));
+ return;
+ }
+ };
+ turns.sort();
+ if turns.is_empty() {
+ if require_turn {
+ errors.push(format!("missing turn evidence: {cell_id}"));
+ }
+ return;
+ }
+
+ for turn in turns {
+ validate_one_turn(&turn, cell_id, errors);
+ }
+}
+
+fn validate_one_turn(turn: &Path, cell_id: &str, errors: &mut Vec<String>) {
+ let turn_name = turn
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or("turn-unknown");
+ let action_path = turn.join("action.json");
+ let action = match read_json_value(&action_path) {
+ Ok(action) => Some(action),
+ Err(error) => {
+ errors.push(format!(
+ "invalid action evidence for {cell_id}/{turn_name}: {error}"
+ ));
+ None
+ }
+ };
+ let manifest_path = turn.join("evidence.json");
+ let manifest = match read_json_value(&manifest_path) {
+ Ok(manifest) if manifest["schema"] == "cua-turn-evidence/v1" => Some(manifest),
+ Ok(_) => {
+ errors.push(format!(
+ "unsupported turn evidence manifest for {cell_id}/{turn_name}: {}",
+ manifest_path.display()
+ ));
+ None
+ }
+ Err(error) => {
+ errors.push(format!(
+ "invalid turn evidence manifest for {cell_id}/{turn_name}: {error}"
+ ));
+ None
+ }
+ };
+ let classification = |phase: &str, kind: &str| {
+ manifest
+ .as_ref()
+ .and_then(|value| value[phase][kind]["classification"].as_str())
+ };
+
+ for (phase, kind) in [("before", "screenshot"), ("after", "screenshot")] {
+ validate_capture_status(
+ manifest.as_ref(),
+ &[phase, kind],
+ cell_id,
+ &format!("{turn_name}/{phase} {kind}"),
+ errors,
+ );
+ }
+
+ for (file, phase, kind) in [
+ ("before.png", "before", "screenshot"),
+ ("after.png", "after", "screenshot"),
+ ("screenshot.png", "after", "screenshot"),
+ ] {
+ validate_nonempty_file(
+ &turn.join(file),
+ cell_id,
+ &format!("{turn_name}/{file}"),
+ classification(phase, kind),
+ errors,
+ );
+ }
+
+ let state_expected = action
+ .as_ref()
+ .and_then(|value| value["arguments"]["pid"].as_i64())
+ .is_some();
+ if state_expected {
+ for phase in ["before", "after"] {
+ validate_capture_status(
+ manifest.as_ref(),
+ &[phase, "state"],
+ cell_id,
+ &format!("{turn_name}/{phase} state"),
+ errors,
+ );
+ }
+ for (file, phase) in [
+ ("before_state.json", "before"),
+ ("after_state.json", "after"),
+ ("app_state.json", "after"),
+ ] {
+ validate_json_file(
+ &turn.join(file),
+ cell_id,
+ &format!("{turn_name}/{file}"),
+ classification(phase, "state"),
+ errors,
+ );
+ }
+ }
+
+ if action.as_ref().is_some_and(|value| {
+ matches!(
+ value["tool"].as_str(),
+ Some("click" | "double_click" | "right_click")
+ )
+ }) {
+ validate_capture_status(
+ manifest.as_ref(),
+ &["click"],
+ cell_id,
+ &format!("{turn_name}/click"),
+ errors,
+ );
+ validate_nonempty_file(
+ &turn.join("click.png"),
+ cell_id,
+ &format!("{turn_name}/click.png"),
+ manifest
+ .as_ref()
+ .and_then(|value| value["click"]["classification"].as_str()),
+ errors,
+ );
+ }
+}
+
+fn validate_capture_status(
+ manifest: Option<&Value>,
+ path: &[&str],
+ cell_id: &str,
+ label: &str,
+ errors: &mut Vec<String>,
+) {
+ let Some(manifest) = manifest else {
+ return;
+ };
+ let value = path.iter().fold(manifest, |value, key| &value[*key]);
+ if value["status"] == "captured" {
+ return;
+ }
+ let classification = value["classification"]
+ .as_str()
+ .unwrap_or("missing_classification");
+ errors.push(format!(
+ "required evidence capture failed for {cell_id}: {label} (classified {classification})"
+ ));
+}
+
+fn validate_nonempty_file(
+ path: &Path,
+ cell_id: &str,
+ label: &str,
+ classification: Option<&str>,
+ errors: &mut Vec<String>,
+) {
+ if std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0) {
+ return;
+ }
+ let classified = classification
+ .map(|value| format!(" (classified {value})"))
+ .unwrap_or_default();
+ errors.push(format!(
+ "required evidence is missing or empty for {cell_id}: {label}{classified}"
+ ));
+}
+
+fn validate_json_file(
+ path: &Path,
+ cell_id: &str,
+ label: &str,
+ classification: Option<&str>,
+ errors: &mut Vec<String>,
+) {
+ if read_json_value(path).is_ok() {
+ return;
+ }
+ let classified = classification
+ .map(|value| format!(" (classified {value})"))
+ .unwrap_or_default();
+ errors.push(format!(
+ "required JSON evidence is missing or invalid for {cell_id}: {label}{classified}"
+ ));
+}
+
+fn read_json_value(path: &Path) -> Result<Value, String> {
+ let bytes = std::fs::read(path).map_err(|error| format!("{}: {error}", path.display()))?;
+ if bytes.is_empty() {
+ return Err(format!("{} is empty", path.display()));
+ }
+ serde_json::from_slice(&bytes).map_err(|error| format!("{}: {error}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ fn delivered_case(id: &str) -> CaseSpec {
+ CaseSpec::delivered(
+ id,
+ "electron",
+ "chromium",
+ "click",
+ Targeting::Ax,
+ Delivery::Background,
+ Scope::Window,
+ DriverRoute::UiaInvoke,
+ vec![OracleKind::FixtureState],
+ )
+ }
+
+ fn coverage_case(
+ id: &str,
+ harness: &str,
+ action: &str,
+ targeting: Targeting,
+ delivery: Delivery,
+ ) -> CaseSpec {
+ CaseSpec::delivered(
+ id,
+ harness,
+ harness,
+ action,
+ targeting,
+ delivery,
+ Scope::Window,
+ DriverRoute::Composite,
+ vec![OracleKind::FixtureState],
+ )
+ }
+
+ fn complete_turn_fixture() -> (TempDir, CaseSpec, CaseResult, PathBuf) {
+ let root = tempfile::tempdir().expect("create artifact root");
+ let recording = root.path().join("recordings/cell-pid1-001");
+ let turn = recording.join("turn-00001");
+ std::fs::create_dir_all(&turn).expect("create turn fixture");
+ std::fs::write(recording.join("recording.mp4"), b"video").expect("write video");
+ std::fs::write(
+ recording.join("trajectory.json"),
+ br#"{
+ "behavior_video":{
+ "status":"finalized",
+ "started_at_unix_ms":100,
+ "baseline_ready_at_unix_ms":400,
+ "finalized_at_unix_ms":800
+ },
+ "hosted_runner_console":{"status":"not_applicable"}
+ }"#,
+ )
+ .expect("write trajectory");
+ std::fs::write(
+ turn.join("action.json"),
+ br#"{
+ "tool":"click",
+ "arguments":{"pid":1,"window_id":2},
+ "click_point":{"x":10,"y":20}
+ }"#,
+ )
+ .expect("write action");
+ std::fs::write(
+ turn.join("evidence.json"),
+ br#"{
+ "schema":"cua-turn-evidence/v1",
+ "before":{"state":{"status":"captured"},"screenshot":{"status":"captured"}},
+ "after":{"state":{"status":"captured"},"screenshot":{"status":"captured"}},
+ "click":{"status":"captured"}
+ }"#,
+ )
+ .expect("write manifest");
+ for file in ["before_state.json", "after_state.json", "app_state.json"] {
+ std::fs::write(turn.join(file), b"{}").expect("write state evidence");
+ }
+ for file in ["before.png", "after.png", "screenshot.png", "click.png"] {
+ std::fs::write(turn.join(file), b"png").expect("write image evidence");
+ }
+
+ let case = delivered_case("cell");
+ let evidence = Evidence {
+ video: Some("recordings/cell-pid1-001/recording.mp4".to_owned()),
+ trajectory: Some("recordings/cell-pid1-001/trajectory.json".to_owned()),
+ ..Evidence::default()
+ };
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], evidence),
+ Duration::from_millis(1),
+ );
+ (root, case, result, turn)
+ }
+
+ #[test]
+ fn required_delivery_rejects_honest_refusal() {
+ let case = delivered_case("required-delivery");
+ let result = CaseResult::evaluate(
+ case,
+ Observation::refused(
+ RefusalCode::BackgroundUnavailable,
+ vec![OracleKind::FixtureState],
+ "honest refusal",
+ Evidence::default(),
+ ),
+ Duration::from_millis(1),
+ );
+ assert_eq!(result.test_status, TestStatus::Fail);
+ assert!(result.message.contains("required delivery was refused"));
+ }
+
+ #[test]
+ fn refusal_requires_explicit_code_and_side_effect_oracles() {
+ let case = delivered_case("expected-refusal")
+ .expecting_refusal(vec![RefusalCode::BackgroundUnavailable]);
+ assert!(case.validate().is_err());
+
+ let mut case = case;
+ case.oracles = vec![
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ];
+ let result = CaseResult::evaluate(
+ case,
+ Observation::refused(
+ RefusalCode::BackgroundUnavailable,
+ vec![
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ],
+ "",
+ Evidence::default(),
+ ),
+ Duration::from_millis(1),
+ );
+ assert_eq!(result.test_status, TestStatus::Pass);
+ assert_eq!(result.observed_behavior, ObservedBehavior::Refused);
+ }
+
+ #[test]
+ fn unknown_background_error_is_not_a_refusal_code() {
+ assert_eq!(
+ RefusalCode::from_driver_code("background_unavailable"),
+ Some(RefusalCode::BackgroundUnavailable)
+ );
+ assert_eq!(RefusalCode::from_driver_code("background_timeout"), None);
+ }
+
+ #[test]
+ fn validator_rejects_missing_and_duplicate_results() {
+ let case = delivered_case("one");
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ );
+ let errors = validate_catalog(
+ std::slice::from_ref(&case),
+ &[result.clone(), result],
+ None,
+ false,
+ )
+ .expect_err("duplicate result should fail");
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("duplicate result")));
+
+ let errors =
+ validate_catalog(&[case], &[], None, false).expect_err("missing result should fail");
+ assert!(errors.iter().any(|error| error.contains("missing result")));
+ }
+
+ #[test]
+ fn validator_rejects_empty_catalog() {
+ let errors = validate_catalog(&[], &[], None, false)
+ .expect_err("an empty E2E catalog must not pass");
+ assert!(errors.iter().any(|error| error.contains("no declarations")));
+ }
+
+ #[test]
+ fn validator_rejects_contradictory_status_and_missing_video() {
+ let case = delivered_case("contradiction");
+ let mut result = CaseResult::evaluate(
+ case.clone(),
+ Observation::error("driver failed", Evidence::default()),
+ Duration::from_millis(1),
+ );
+ result.test_status = TestStatus::Pass;
+ let errors = validate_catalog(std::slice::from_ref(&case), &[result], None, false)
+ .expect_err("contradictory status should fail");
+ assert!(errors.iter().any(|error| error.contains("invalid status")));
+
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ );
+ let errors = validate_catalog(&[case], &[result], None, true)
+ .expect_err("required video should fail");
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("missing video evidence")));
+ }
+
+ #[test]
+ fn validator_accepts_complete_pre_and_post_turn_evidence() {
+ let (root, case, result, _) = complete_turn_fixture();
+ validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect("complete turn evidence should pass strict validation");
+ }
+
+ #[test]
+ fn validator_rejects_unreached_behavior_video_boundary() {
+ let (root, case, result, turn) = complete_turn_fixture();
+ let recording = turn.parent().expect("turn has recording parent");
+ std::fs::write(
+ recording.join("trajectory.json"),
+ br#"{
+ "behavior_video":{"status":"pending"},
+ "hosted_runner_console":{"status":"minimized"}
+ }"#,
+ )
+ .expect("write pending trajectory");
+
+ let errors = validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect_err("pending behavior phase must fail strict validation");
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("behavioral video phase is not finalized")));
+ }
+
+ #[test]
+ fn strict_readonly_cell_does_not_invent_an_action_turn() {
+ let root = tempfile::tempdir().expect("create artifact root");
+ let recording = root.path().join("recordings/readonly-pid1-001");
+ std::fs::create_dir_all(&recording).expect("create recording fixture");
+ std::fs::write(recording.join("recording.mp4"), b"video").expect("write video");
+ std::fs::write(
+ recording.join("trajectory.json"),
+ br#"{
+ "behavior_video":{
+ "status":"finalized",
+ "started_at_unix_ms":100,
+ "baseline_ready_at_unix_ms":400,
+ "finalized_at_unix_ms":800
+ },
+ "hosted_runner_console":{"status":"not_applicable"}
+ }"#,
+ )
+ .expect("write trajectory");
+ let case = native_readonly_case(
+ "wpf",
+ "ax_tree",
+ Targeting::Ax,
+ DriverRoute::AxRead,
+ vec![OracleKind::FixtureState],
+ );
+ let evidence = Evidence {
+ video: Some("recordings/readonly-pid1-001/recording.mp4".to_owned()),
+ trajectory: Some("recordings/readonly-pid1-001/trajectory.json".to_owned()),
+ ..Evidence::default()
+ };
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], evidence),
+ Duration::from_millis(1),
+ );
+
+ validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect("readonly cells have no action turn to capture");
+ }
+
+ #[test]
+ fn strict_background_screenshot_does_not_invent_an_action_turn() {
+ let case = CaseSpec::delivered(
+ "windows-wpf-screenshot-px-background",
+ "wpf",
+ "wpf",
+ "screenshot",
+ Targeting::Px,
+ Delivery::Background,
+ Scope::Window,
+ DriverRoute::WindowsPrintWindow,
+ vec![OracleKind::Pixels],
+ );
+ assert!(!case_requires_action_turn(&case));
+ }
+
+ #[test]
+ fn strict_not_applicable_mutation_still_requires_an_action_turn() {
+ let root = tempfile::tempdir().expect("create artifact root");
+ let recording = root.path().join("recordings/cursor-pid1-001");
+ std::fs::create_dir_all(&recording).expect("create recording fixture");
+ std::fs::write(recording.join("recording.mp4"), b"video").expect("write video");
+ std::fs::write(
+ recording.join("trajectory.json"),
+ br#"{
+ "behavior_video":{
+ "status":"finalized",
+ "started_at_unix_ms":100,
+ "baseline_ready_at_unix_ms":400,
+ "finalized_at_unix_ms":800
+ },
+ "hosted_runner_console":{"status":"not_applicable"}
+ }"#,
+ )
+ .expect("write trajectory");
+ let case = CaseSpec::delivered(
+ "cursor",
+ "desktop",
+ "win32",
+ "agent_cursor",
+ Targeting::Px,
+ Delivery::NotApplicable,
+ Scope::Desktop,
+ DriverRoute::WindowsOverlay,
+ vec![OracleKind::FixtureState],
+ );
+ let evidence = Evidence {
+ video: Some("recordings/cursor-pid1-001/recording.mp4".to_owned()),
+ trajectory: Some("recordings/cursor-pid1-001/trajectory.json".to_owned()),
+ ..Evidence::default()
+ };
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], evidence),
+ Duration::from_millis(1),
+ );
+
+ let errors = validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect_err("mutable not-applicable cells still need a recorded turn");
+ assert!(errors.iter().any(|error| error.contains("missing turn evidence")));
+ }
+
+ #[test]
+ fn validator_exposes_missing_legacy_modal_images() {
+ let (root, case, result, turn) = complete_turn_fixture();
+ std::fs::remove_file(turn.join("screenshot.png")).expect("remove screenshot fixture");
+ std::fs::remove_file(turn.join("click.png")).expect("remove click fixture");
+
+ let errors = validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect_err("missing expected images must fail closed");
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("turn-00001/screenshot.png")));
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("turn-00001/click.png")));
+ }
+
+ #[test]
+ fn validator_reports_capture_classification_for_missing_phase() {
+ let (root, case, result, turn) = complete_turn_fixture();
+ std::fs::remove_file(turn.join("after.png")).expect("remove after image fixture");
+ std::fs::write(
+ turn.join("evidence.json"),
+ br#"{
+ "schema":"cua-turn-evidence/v1",
+ "before":{"state":{"status":"captured"},"screenshot":{"status":"captured"}},
+ "after":{"state":{"status":"captured"},"screenshot":{"status":"unavailable","classification":"capture_failed"}},
+ "click":{"status":"captured"}
+ }"#,
+ )
+ .expect("write classified manifest");
+
+ let errors = validate_catalog(&[case], &[result], Some(root.path()), true)
+ .expect_err("classified unavailability must remain a strict failure");
+ assert!(errors.iter().any(|error| {
+ error.contains("turn-00001/after.png") && error.contains("classified capture_failed")
+ }));
+ }
+
+ #[test]
+ fn non_strict_validation_keeps_legacy_results_compatible() {
+ let case = delivered_case("legacy");
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ );
+ validate_catalog(&[case], &[result], None, false)
+ .expect("non-canonical legacy results remain valid");
+ }
+
+ #[test]
+ fn validator_rejects_unknown_result_schema() {
+ let case = delivered_case("unknown-schema");
+ let mut result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ );
+ result.schema = "cua-e2e-result/v999".to_owned();
+ let errors = validate_catalog(&[case], &[result], None, false)
+ .expect_err("unknown result schema should fail");
+ assert!(errors
+ .iter()
+ .any(|error| error.contains("unsupported result schema")));
+ }
+
+ #[test]
+ fn valid_catalog_renders_delivered_rollup_and_flat_schema() {
+ let case = delivered_case("rendered");
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(7),
+ );
+ let summary = validate_catalog(
+ std::slice::from_ref(&case),
+ std::slice::from_ref(&result),
+ None,
+ false,
+ )
+ .expect("valid catalog");
+ assert_eq!(summary.delivered, 1);
+ assert!(summary
+ .markdown_with_declarations(std::slice::from_ref(&case), std::slice::from_ref(&result),)
+ .contains("1 delivered"));
+
+ let value = serde_json::to_value(result).expect("serialize result");
+ assert_eq!(value["schema"], RESULT_SCHEMA);
+ assert_eq!(value["cell_id"], "rendered");
+ assert!(value.get("case").is_none());
+ }
+
+ #[test]
+ fn declared_coverage_distinguishes_statuses_and_groups_harness_actions() {
+ let delivered = coverage_case(
+ "electron-click-ax-background",
+ "electron",
+ "click",
+ Targeting::Ax,
+ Delivery::Background,
+ );
+ let mut refused = coverage_case(
+ "electron-click-px-background",
+ "electron",
+ "click",
+ Targeting::Px,
+ Delivery::Background,
+ )
+ .expecting_refusal(vec![RefusalCode::BackgroundUnavailable]);
+ refused.oracles = vec![
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ];
+ let failed = coverage_case(
+ "electron-click-px-foreground",
+ "electron",
+ "click",
+ Targeting::Px,
+ Delivery::Foreground,
+ );
+ let grouped = coverage_case(
+ "tauri-type-text-ax-background",
+ "tauri",
+ "type_text",
+ Targeting::Ax,
+ Delivery::Background,
+ );
+
+ let results = vec![
+ CaseResult::evaluate(
+ delivered.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ ),
+ CaseResult::evaluate(
+ refused.clone(),
+ Observation::refused(
+ RefusalCode::BackgroundUnavailable,
+ vec![
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ],
+ "",
+ Evidence::default(),
+ ),
+ Duration::from_millis(1),
+ ),
+ CaseResult::evaluate(
+ failed.clone(),
+ Observation::error("driver error", Evidence::default()),
+ Duration::from_millis(1),
+ ),
+ CaseResult::evaluate(
+ grouped.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ ),
+ ];
+ let declarations = vec![delivered, refused, failed, grouped];
+ let summary =
+ validate_catalog(&declarations, &results, None, false).expect("valid catalog");
+ let markdown = summary.markdown_with_declarations(&declarations, &results);
+
+ assert!(markdown.contains("| electron | click | PASS | - | REFUSED | FAIL | - | - |"));
+ assert!(markdown.contains("| tauri | type_text | PASS | - | - | - | - | - |"));
+ }
+
+ #[test]
+ fn summary_records_the_exact_source_sha() {
+ let case = delivered_case("source-sha");
+ let result = CaseResult::evaluate(
+ case.clone(),
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ );
+ let summary = validate_catalog(
+ std::slice::from_ref(&case),
+ std::slice::from_ref(&result),
+ None,
+ false,
+ )
+ .expect("valid catalog");
+ let sha = "0123456789abcdef0123456789abcdef01234567";
+ let markdown = summary.markdown_with_declarations_and_source(
+ std::slice::from_ref(&case),
+ std::slice::from_ref(&result),
+ Some(sha),
+ );
+
+ assert!(markdown.contains(&format!("**Source SHA:** `{sha}`")));
+ }
+
+ #[test]
+ fn declared_coverage_keeps_page_and_not_applicable_out_of_the_ax_px_grid() {
+ let page = coverage_case(
+ "web-evaluate-page-background",
+ "web",
+ "evaluate",
+ Targeting::Page,
+ Delivery::Background,
+ );
+ let not_applicable = coverage_case(
+ "web-evaluate-not-applicable-background",
+ "web",
+ "evaluate",
+ Targeting::NotApplicable,
+ Delivery::Background,
+ );
+ let results = [page.clone(), not_applicable.clone()]
+ .into_iter()
+ .map(|case| {
+ CaseResult::evaluate(
+ case,
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default()),
+ Duration::from_millis(1),
+ )
+ })
+ .collect::<Vec<_>>();
+ let declarations = vec![page, not_applicable];
+ let summary =
+ validate_catalog(&declarations, &results, None, false).expect("valid catalog");
+ let markdown = summary.markdown_with_declarations(&declarations, &results);
+
+ assert!(markdown.contains(
+ "| web | evaluate | - | - | - | - | Background: PASS | NotApplicable/Background: PASS |"
+ ));
+ }
+
+ #[test]
+ fn native_case_builders_encode_delivery_and_oracle_contracts() {
+ let background =
+ native_background_case("wpf", "left_click", Targeting::Ax, DriverRoute::UiaInvoke);
+ assert_eq!(background.delivery, Delivery::Background);
+ assert_eq!(
+ background.cell_id,
+ format!("{}-wpf-left-click-ax-background", std::env::consts::OS)
+ );
+ for oracle in [
+ OracleKind::FixtureState,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::Cursor,
+ OracleKind::NoLeakedInput,
+ ] {
+ assert!(background.oracles.contains(&oracle));
+ }
+ background.validate().expect("background case is valid");
+
+ let foreground = native_foreground_case(
+ "wpf",
+ "right_click",
+ Targeting::Ax,
+ DriverRoute::WindowsSendInput,
+ );
+ assert_eq!(foreground.delivery, Delivery::Foreground);
+ assert_eq!(foreground.oracles, vec![OracleKind::FixtureState]);
+
+ let readonly = native_readonly_case(
+ "wpf",
+ "ax_tree",
+ Targeting::Ax,
+ DriverRoute::AxRead,
+ vec![OracleKind::AxState],
+ );
+ assert_eq!(readonly.delivery, Delivery::NotApplicable);
+ assert_eq!(readonly.oracles, vec![OracleKind::AxState]);
+ readonly.validate().expect("read-only case is valid");
+ }
+
+ #[test]
+ fn delivered_with_fixture_state_deduplicates_the_oracle() {
+ let observation = Observation::delivered_with_fixture_state(vec![
+ OracleKind::Focus,
+ OracleKind::FixtureState,
+ ]);
+ assert_eq!(
+ observation.passed_oracles,
+ vec![OracleKind::FixtureState, OracleKind::Focus]
+ );
+ }
+
+ #[test]
+ fn shared_routes_are_explicit_for_the_current_matrix() {
+ let mut cells = Vec::new();
+ for action in [
+ "left_click",
+ "right_click",
+ "double_click",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "child_window",
+ ] {
+ for targeting in [Targeting::Ax, Targeting::Px] {
+ for delivery in [Delivery::Background, Delivery::Foreground] {
+ cells.push((action, targeting, delivery));
+ }
+ }
+ }
+ for delivery in [Delivery::Background, Delivery::Foreground] {
+ cells.push(("drag", Targeting::Px, delivery));
+ cells.push(("editor_save", Targeting::Ax, delivery));
+ }
+ assert_eq!(cells.len(), 36);
+ for (platform, display_server) in [
+ (Platform::Windows, DisplayServer::Win32),
+ (Platform::Macos, DisplayServer::Quartz),
+ (Platform::Linux, DisplayServer::X11),
+ (Platform::Linux, DisplayServer::Wayland),
+ ] {
+ for (action, targeting, delivery) in cells.iter().copied() {
+ shared_web_route(platform, display_server, action, targeting, delivery)
+ .unwrap_or_else(|error| panic!("{error}"));
+ }
+ }
+ }
+
+ #[test]
+ fn windows_pixel_background_route_remains_targeted_injection() {
+ assert_eq!(
+ shared_web_route(
+ Platform::Windows,
+ DisplayServer::Win32,
+ "left_click",
+ Targeting::Px,
+ Delivery::Background,
+ ),
+ Ok(DriverRoute::WindowsTargetedInjection)
+ );
+ }
+
+ #[test]
+ fn nested_wayland_pixel_route_is_distinct_from_stock_wayland() {
+ let stock = shared_web_route_for_environment(
+ Platform::Linux,
+ DisplayServer::Wayland,
+ "left_click",
+ Targeting::Px,
+ Delivery::Background,
+ false,
+ );
+ let nested = shared_web_route_for_environment(
+ Platform::Linux,
+ DisplayServer::Wayland,
+ "left_click",
+ Targeting::Px,
+ Delivery::Background,
+ true,
+ );
+ assert_eq!(stock, Ok(DriverRoute::LinuxWaylandVirtualPointer));
+ assert_eq!(nested, Ok(DriverRoute::LinuxCuaCompositorInject));
+
+ let nested_text = shared_web_route_for_environment(
+ Platform::Linux,
+ DisplayServer::Wayland,
+ "type_text",
+ Targeting::Ax,
+ Delivery::Background,
+ true,
+ );
+ assert_eq!(nested_text, Ok(DriverRoute::LinuxCuaCompositorInject));
+ }
+
+ #[test]
+ fn environment_v2_artifacts_remain_readable() {
+ let record: EnvironmentRecord = serde_json::from_value(serde_json::json!({
+ "schema": ENVIRONMENT_SCHEMA_V2,
+ "platform": "linux",
+ "display_server": "wayland",
+ "source_sha": null,
+ "status": "ready",
+ "duration_ms": 1,
+ "message": ""
+ }))
+ .expect("v2 environment record should deserialize");
+ assert!(environment_schema_supported(&record.schema));
+ assert_eq!(record.compositor, None);
+ assert!(record.input_backends.is_empty());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs
new file mode 100644
index 0000000000..6a08db3a04
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/journal.rs
@@ -0,0 +1,176 @@
+use std::io::{Read, Write};
+use std::net::TcpListener;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::Duration;
+
+/// Fixture-owned state receiver used as an oracle independently of cua-driver.
+///
+/// Web fixtures POST their current DOM state to this loopback endpoint. Tests
+/// may still use AX or pixels to target an action, but delivery is judged from
+/// this state rather than by reading the driver's own accessibility snapshot.
+pub struct FixtureJournal {
+ url: String,
+ latest: Arc<Mutex<serde_json::Value>>,
+ stop: Arc<AtomicBool>,
+ worker: Option<thread::JoinHandle<()>>,
+}
+
+impl FixtureJournal {
+ pub fn start() -> Self {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind fixture journal");
+ listener
+ .set_nonblocking(true)
+ .expect("make fixture journal nonblocking");
+ let address = listener.local_addr().expect("read fixture journal address");
+ let latest = Arc::new(Mutex::new(serde_json::json!({})));
+ let stop = Arc::new(AtomicBool::new(false));
+ let latest_for_worker = Arc::clone(&latest);
+ let stop_for_worker = Arc::clone(&stop);
+ let worker = thread::spawn(move || {
+ while !stop_for_worker.load(Ordering::Relaxed) {
+ match listener.accept() {
+ Ok((mut stream, _)) => {
+ let _ = stream.set_nonblocking(false);
+ let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
+ let mut request = Vec::new();
+ let mut chunk = [0u8; 8192];
+ let mut body_range = None;
+ loop {
+ match stream.read(&mut chunk) {
+ Ok(0) => break,
+ Ok(n) => request.extend_from_slice(&chunk[..n]),
+ Err(error)
+ if matches!(
+ error.kind(),
+ std::io::ErrorKind::WouldBlock
+ | std::io::ErrorKind::TimedOut
+ ) =>
+ {
+ break;
+ }
+ Err(_) => break,
+ }
+ if body_range.is_none() {
+ body_range = request
+ .windows(4)
+ .position(|window| window == b"\r\n\r\n")
+ .map(|header_end| {
+ let headers =
+ String::from_utf8_lossy(&request[..header_end]);
+ let content_len = headers
+ .lines()
+ .find_map(|line| {
+ line.split_once(':').and_then(|(name, value)| {
+ name.eq_ignore_ascii_case("content-length")
+ .then_some(value)
+ })
+ })
+ .and_then(|value| value.trim().parse::<usize>().ok())
+ .unwrap_or(0);
+ (header_end + 4, content_len)
+ });
+ }
+ if let Some((body_start, content_len)) = body_range {
+ if request.len() >= body_start + content_len {
+ break;
+ }
+ }
+ }
+ if let Some((body_start, content_len)) = body_range {
+ if let Some(body) = request.get(body_start..body_start + content_len) {
+ if let Ok(state) = serde_json::from_slice(body) {
+ *latest_for_worker.lock().expect("lock fixture journal") =
+ state;
+ }
+ }
+ }
+ let _ = stream.write_all(
+ b"HTTP/1.1 204 No Content\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n",
+ );
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
+ thread::sleep(Duration::from_millis(10));
+ }
+ Err(_) => break,
+ }
+ }
+ });
+ Self {
+ url: format!("http://{address}/state"),
+ latest,
+ stop,
+ worker: Some(worker),
+ }
+ }
+
+ pub fn url(&self) -> &str {
+ &self.url
+ }
+
+ pub fn contains(&self, marker: &str) -> bool {
+ self.latest
+ .lock()
+ .expect("lock fixture journal")
+ .to_string()
+ .contains(marker)
+ }
+
+ pub fn text(&self, id: &str) -> Option<String> {
+ self.latest
+ .lock()
+ .expect("lock fixture journal")
+ .get(id)
+ .and_then(|entry| entry.get("text"))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_owned)
+ }
+
+ pub fn snapshot(&self) -> serde_json::Value {
+ self.latest.lock().expect("lock fixture journal").clone()
+ }
+}
+
+impl Drop for FixtureJournal {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Relaxed);
+ if let Some(worker) = self.worker.take() {
+ let _ = worker.join();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::FixtureJournal;
+ use std::io::Write;
+ use std::net::TcpStream;
+ use std::time::{Duration, Instant};
+
+ #[test]
+ fn receives_fixture_state_over_loopback() {
+ let journal = FixtureJournal::start();
+ let body = r#"{"status":{"text":"last_action=left_click"}}"#;
+ let address = journal
+ .url()
+ .strip_prefix("http://")
+ .and_then(|url| url.strip_suffix("/state"))
+ .expect("journal URL shape");
+ let mut stream = TcpStream::connect(address).expect("connect fixture journal");
+ let request = format!(
+ "POST /state HTTP/1.1\r\nHost: {address}\r\nContent-Length: {}\r\n\r\n{body}",
+ body.len()
+ );
+ stream
+ .write_all(request.as_bytes())
+ .expect("post fixture state");
+ drop(stream);
+
+ let deadline = Instant::now() + Duration::from_secs(1);
+ while !journal.contains("last_action=left_click") && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ assert!(journal.contains("last_action=left_click"));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
index 504eb22c50..547133d985 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/lib.rs
@@ -35,14 +35,20 @@
pub mod ax;
mod driver;
+pub mod e2e;
+mod journal;
mod mcp;
mod cli;
+pub mod observer;
mod paths;
mod raw;
mod reaper;
mod response;
+pub mod sentinel;
+mod windows_setup;
-pub use driver::Driver;
+pub use driver::{BehaviorRecording, Driver};
+pub use journal::FixtureJournal;
pub use mcp::McpDriver;
pub use raw::RawDriver;
pub use cli::CliDriver;
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
index 50f2d1441a..9eb4243853 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use serde_json::Value;
-use crate::driver::Driver;
+use crate::driver::{BehaviorRecording, Driver};
use crate::paths::driver_binary;
use crate::reaper::{spawn_in_job, ChildReaper};
use crate::response::ToolResponse;
@@ -27,6 +27,7 @@ pub struct McpDriver {
rx: Receiver<String>,
next_id: u32,
recording_dir: Option<PathBuf>,
+ recording_started: bool,
}
static RECORDING_SEQUENCE: AtomicU64 = AtomicU64::new(1);
@@ -44,6 +45,11 @@ impl McpDriver {
Self::spawn_internal(&[], Some(recording_label))
}
+ /// Spawn a named driver with environment variables scoped to this child.
+ pub fn spawn_named_with_env(recording_label: &str, env: &[(&str, &str)]) -> Option<Self> {
+ Self::spawn_internal(env, Some(recording_label))
+ }
+
/// Spawn the driver with extra environment variables set on the child.
pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {
Self::spawn_internal(env, None)
@@ -58,9 +64,14 @@ impl McpDriver {
let mut reaper = ChildReaper::new();
let mut cmd = Command::new(&bin);
+ let stderr = if std::env::var_os("CUA_TEST_DRIVER_STDERR").is_some() {
+ Stdio::inherit()
+ } else {
+ Stdio::null()
+ };
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
- .stderr(Stdio::null());
+ .stderr(stderr);
for (key, value) in env {
cmd.env(key, value);
}
@@ -94,9 +105,10 @@ impl McpDriver {
rx,
next_id: 2,
recording_dir: None,
+ recording_started: false,
};
d.initialize();
- d.start_e2e_recording(recording_label);
+ d.prepare_e2e_recording(recording_label);
Some(d)
}
@@ -144,7 +156,7 @@ impl McpDriver {
let _ = self.stdin.flush();
}
- fn start_e2e_recording(&mut self, explicit_label: Option<&str>) {
+ fn prepare_e2e_recording(&mut self, explicit_label: Option<&str>) {
let Some(root) = std::env::var_os("CUA_E2E_RECORDINGS_ROOT") else {
return;
};
@@ -156,6 +168,50 @@ impl McpDriver {
let label = recording_label(explicit_label.unwrap_or(&thread_name));
let output_dir =
PathBuf::from(root).join(format!("{label}-pid{}-{sequence:03}", std::process::id()));
+ std::fs::create_dir_all(&output_dir).unwrap_or_else(|error| {
+ panic!("could not prepare E2E recording directory for {thread_name}: {error}")
+ });
+ let runner_console = crate::windows_setup::minimize_hosted_runner_console();
+ let runner_console_status = runner_console.as_deref().unwrap_or("error");
+ let manifest = serde_json::json!({
+ "schema": "cua-e2e-trajectory/v1",
+ "label": label,
+ "rust_test_thread": thread_name,
+ "process_id": std::process::id(),
+ "sequence": sequence,
+ "behavior_video": {
+ "status": "pending",
+ "baseline_settle_ms": 300
+ },
+ "hosted_runner_console": {
+ "status": runner_console_status
+ }
+ });
+ std::fs::write(
+ output_dir.join("trajectory.json"),
+ serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
+ )
+ .expect("write prepared E2E trajectory manifest");
+ eprintln!(
+ "[testkit] prepared E2E evidence directory {}",
+ output_dir.display()
+ );
+ self.recording_dir = Some(output_dir);
+ if let Err(error) = runner_console {
+ panic!("hosted-runner console cleanup failed before fixture setup: {error}");
+ }
+ }
+
+ /// Begin the behavioral clip after fixture readiness and foreground or
+ /// background posture have been established. The settle interval gives
+ /// the video backend time to encode a visible baseline before dispatch.
+ pub fn start_behavior_recording(&mut self) {
+ let Some(output_dir) = self.recording_dir.clone() else {
+ return;
+ };
+ if self.recording_started {
+ return;
+ }
let response = self.call(
"start_recording",
serde_json::json!({
@@ -167,30 +223,33 @@ impl McpDriver {
.as_bool()
.unwrap_or(false);
if response.is_error() || !video_active {
+ update_behavior_video_status(&output_dir, "error");
panic!(
- "E2E video recording did not start for {thread_name}: {}",
- response.text()
+ "E2E behavioral video did not start after setup: {}; structured={}",
+ response.text(),
+ response.structured()
);
}
- let manifest = serde_json::json!({
- "schema": "cua-e2e-trajectory/v1",
- "label": label,
- "rust_test_thread": thread_name,
- "process_id": std::process::id(),
- "sequence": sequence
- });
- let _ = std::fs::write(
- output_dir.join("trajectory.json"),
- serde_json::to_vec_pretty(&manifest).unwrap_or_default(),
+ self.recording_started = true;
+ update_behavior_video_status(&output_dir, "started");
+ std::thread::sleep(Duration::from_millis(300));
+ mark_behavior_video_baseline_ready(&output_dir);
+ eprintln!(
+ "[testkit] behavioral E2E video started at {}",
+ output_dir.display()
);
- eprintln!("[testkit] recording E2E video to {}", output_dir.display());
- self.recording_dir = Some(output_dir);
}
fn stop_e2e_recording(&mut self) {
let Some(output_dir) = self.recording_dir.take() else {
return;
};
+ if !self.recording_started {
+ let message = "E2E behavioral video boundary was never reached; fixture setup or posture failed before capture";
+ eprintln!("[testkit] {message}");
+ let _ = std::fs::write(output_dir.join("recording-error.txt"), message);
+ return;
+ }
let response = self.call("stop_recording", serde_json::json!({}));
let video_path = output_dir.join("recording.mp4");
let valid_video = !response.is_error()
@@ -199,6 +258,7 @@ impl McpDriver {
.map(|metadata| metadata.len() > 0)
.unwrap_or(false);
if valid_video {
+ update_behavior_video_status(&output_dir, "finalized");
eprintln!("[testkit] finalized E2E video at {}", video_path.display());
return;
}
@@ -209,6 +269,7 @@ impl McpDriver {
response.text()
);
eprintln!("[testkit] {message}");
+ update_behavior_video_status(&output_dir, "error");
let _ = std::fs::create_dir_all(&output_dir);
let _ = std::fs::write(output_dir.join("recording-error.txt"), message);
}
@@ -219,6 +280,11 @@ impl McpDriver {
&mut self.reaper
}
+ /// Directory for this driver's active per-cell recording, when enabled.
+ pub fn recording_dir(&self) -> Option<&std::path::Path> {
+ self.recording_dir.as_deref()
+ }
+
/// Poll `list_windows` until a window of `pid` whose title contains
/// `title_substr` appears (up to ~12s). Returns `(window_id, title)`.
/// Replaces the per-file `find_harness_window` helper.
@@ -287,6 +353,58 @@ fn recording_label(name: &str) -> String {
}
}
+impl Driver for McpDriver {
+ fn call(&mut self, tool: &str, args: Value) -> ToolResponse {
+ ToolResponse::from_mcp(self.call_raw(tool, args))
+ }
+}
+
+impl BehaviorRecording for McpDriver {
+ fn start_behavior_recording(&mut self) {
+ McpDriver::start_behavior_recording(self);
+ }
+}
+
+fn update_behavior_video_status(output_dir: &std::path::Path, status: &str) {
+ let path = output_dir.join("trajectory.json");
+ let Ok(bytes) = std::fs::read(&path) else {
+ return;
+ };
+ let Ok(mut manifest) = serde_json::from_slice::<Value>(&bytes) else {
+ return;
+ };
+ manifest["behavior_video"]["status"] = Value::String(status.to_owned());
+ let timestamp_field = match status {
+ "started" => Some("started_at_unix_ms"),
+ "finalized" => Some("finalized_at_unix_ms"),
+ "error" => Some("error_at_unix_ms"),
+ _ => None,
+ };
+ if let Some(field) = timestamp_field {
+ manifest["behavior_video"][field] = Value::from(unix_ms());
+ }
+ let _ = std::fs::write(path, serde_json::to_vec_pretty(&manifest).unwrap_or_default());
+}
+
+fn mark_behavior_video_baseline_ready(output_dir: &std::path::Path) {
+ let path = output_dir.join("trajectory.json");
+ let Ok(bytes) = std::fs::read(&path) else {
+ return;
+ };
+ let Ok(mut manifest) = serde_json::from_slice::<Value>(&bytes) else {
+ return;
+ };
+ manifest["behavior_video"]["baseline_ready_at_unix_ms"] = Value::from(unix_ms());
+ let _ = std::fs::write(path, serde_json::to_vec_pretty(&manifest).unwrap_or_default());
+}
+
+fn unix_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_millis() as u64
+}
+
#[cfg(test)]
mod tests {
use super::recording_label;
@@ -300,9 +418,3 @@ mod tests {
assert_eq!(recording_label("///"), "unnamed-test");
}
}
-
-impl Driver for McpDriver {
- fn call(&mut self, tool: &str, args: Value) -> ToolResponse {
- ToolResponse::from_mcp(self.call_raw(tool, args))
- }
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
new file mode 100644
index 0000000000..90f2ce9fc7
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
@@ -0,0 +1,1736 @@
+//! Driver-independent desktop side-effect observations for E2E tests.
+
+use std::fmt;
+use std::time::Duration;
+
+use crate::e2e::OracleKind;
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct TargetWindow {
+ pub pid: u32,
+ pub native_id: u64,
+}
+
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
+pub struct ObserverCapabilities {
+ pub focus: bool,
+ pub z_order: bool,
+ pub cursor: bool,
+ pub leaked_input: bool,
+}
+
+impl ObserverCapabilities {
+ fn supports(self, oracle: OracleKind) -> bool {
+ match oracle {
+ OracleKind::Focus => self.focus,
+ OracleKind::ZOrder => self.z_order,
+ OracleKind::Cursor => self.cursor,
+ OracleKind::NoLeakedInput => self.leaked_input,
+ _ => true,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum TargetZ {
+ BackgroundOccluded,
+ BackgroundVisible,
+ Foreground,
+ Minimized,
+ NotFound,
+}
+
+impl TargetZ {
+ fn rank(self) -> Option<u8> {
+ match self {
+ Self::BackgroundOccluded => Some(0),
+ Self::BackgroundVisible => Some(1),
+ Self::Foreground => Some(2),
+ Self::Minimized | Self::NotFound => None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct DesktopSnapshot {
+ pub foreground: Option<u64>,
+ pub input_focus: Option<u64>,
+ pub target_z: TargetZ,
+ pub cursor_pos: Option<(f64, f64)>,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct FocusEvent {
+ pub from: Option<u64>,
+ pub to: Option<u64>,
+}
+
+#[derive(Clone, Debug, Default, Eq, PartialEq)]
+pub struct DesktopJournal {
+ pub focus_events: Vec<FocusEvent>,
+ pub leaked_input_events: Vec<String>,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ObserverError {
+ message: String,
+}
+
+impl ObserverError {
+ pub fn new(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ }
+ }
+}
+
+impl fmt::Display for ObserverError {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str(&self.message)
+ }
+}
+
+impl std::error::Error for ObserverError {}
+
+pub trait ObserverBackend {
+ fn capabilities(&self) -> ObserverCapabilities;
+ fn snapshot(&self, target: TargetWindow) -> Result<DesktopSnapshot, ObserverError>;
+ fn start_journal(&mut self) -> Result<(), ObserverError>;
+ fn drain_journal(&mut self) -> Result<DesktopJournal, ObserverError>;
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct ObservationDelta {
+ pub before: DesktopSnapshot,
+ pub after: DesktopSnapshot,
+ pub journal: DesktopJournal,
+ passed: Vec<OracleKind>,
+ unsupported: Vec<OracleKind>,
+ violations: Vec<String>,
+}
+
+impl ObservationDelta {
+ pub fn passed(&self) -> &[OracleKind] {
+ &self.passed
+ }
+
+ pub fn unsupported(&self) -> &[OracleKind] {
+ &self.unsupported
+ }
+
+ pub fn violations(&self) -> &[String] {
+ &self.violations
+ }
+
+ pub fn ensure_supported(&self) -> Result<(), ObserverError> {
+ if self.unsupported.is_empty() {
+ Ok(())
+ } else {
+ Err(ObserverError::new(format!(
+ "desktop observer does not support required oracles: {:?}",
+ self.unsupported
+ )))
+ }
+ }
+}
+
+pub struct DesktopObserver<B> {
+ backend: B,
+ target: TargetWindow,
+ settle: Duration,
+}
+
+impl<B: ObserverBackend> DesktopObserver<B> {
+ pub fn new(backend: B, target: TargetWindow) -> Self {
+ Self {
+ backend,
+ target,
+ settle: Duration::from_millis(150),
+ }
+ }
+
+ pub fn with_settle(mut self, settle: Duration) -> Self {
+ self.settle = settle;
+ self
+ }
+
+ pub fn snapshot(&self) -> Result<DesktopSnapshot, ObserverError> {
+ self.backend.snapshot(self.target)
+ }
+
+ pub fn observe<R>(
+ &mut self,
+ requested: &[OracleKind],
+ action: impl FnOnce() -> R,
+ ) -> Result<(R, ObservationDelta), ObserverError> {
+ let before = self.backend.snapshot(self.target)?;
+ self.backend.start_journal()?;
+ let result = action();
+ if !self.settle.is_zero() {
+ std::thread::sleep(self.settle);
+ }
+ let journal = self.backend.drain_journal()?;
+ let after = self.backend.snapshot(self.target)?;
+ let delta = evaluate(
+ self.backend.capabilities(),
+ requested,
+ before,
+ after,
+ journal,
+ );
+ Ok((result, delta))
+ }
+}
+
+fn evaluate(
+ capabilities: ObserverCapabilities,
+ requested: &[OracleKind],
+ before: DesktopSnapshot,
+ after: DesktopSnapshot,
+ journal: DesktopJournal,
+) -> ObservationDelta {
+ let mut passed = Vec::new();
+ let mut unsupported = Vec::new();
+ let mut violations = Vec::new();
+
+ for oracle in requested.iter().copied() {
+ if !capabilities.supports(oracle) {
+ unsupported.push(oracle);
+ continue;
+ }
+ let violation = match oracle {
+ OracleKind::Focus => {
+ if before.foreground != after.foreground {
+ Some(format!(
+ "foreground changed from {:?} to {:?}",
+ before.foreground, after.foreground
+ ))
+ } else if before.input_focus != after.input_focus {
+ Some(format!(
+ "input focus changed from {:?} to {:?}",
+ before.input_focus, after.input_focus
+ ))
+ } else if !journal.focus_events.is_empty() {
+ Some(format!(
+ "foreground changed transiently: {:?}",
+ journal.focus_events
+ ))
+ } else {
+ None
+ }
+ }
+ OracleKind::ZOrder => match (before.target_z.rank(), after.target_z.rank()) {
+ (Some(before_rank), Some(after_rank)) if after_rank <= before_rank => None,
+ (Some(_), Some(_)) => Some(format!(
+ "target rose from {:?} to {:?}",
+ before.target_z, after.target_z
+ )),
+ _ => Some(format!(
+ "target z-order could not be compared: {:?} -> {:?}",
+ before.target_z, after.target_z
+ )),
+ },
+ OracleKind::Cursor => match (before.cursor_pos, after.cursor_pos) {
+ (Some((before_x, before_y)), Some((after_x, after_y)))
+ if (before_x - after_x).abs() <= 1.0 && (before_y - after_y).abs() <= 1.0 =>
+ {
+ None
+ }
+ (Some(before_pos), Some(after_pos)) => Some(format!(
+ "real cursor moved from {before_pos:?} to {after_pos:?}"
+ )),
+ _ => Some("real cursor position was unavailable".to_owned()),
+ },
+ OracleKind::NoLeakedInput => {
+ if journal.leaked_input_events.is_empty() {
+ None
+ } else {
+ Some(format!(
+ "foreground sentinel received input: {:?}",
+ journal.leaked_input_events
+ ))
+ }
+ }
+ _ => continue,
+ };
+ if let Some(violation) = violation {
+ violations.push(violation);
+ } else {
+ passed.push(oracle);
+ }
+ }
+
+ ObservationDelta {
+ before,
+ after,
+ journal,
+ passed,
+ unsupported,
+ violations,
+ }
+}
+
+#[cfg(target_os = "windows")]
+pub mod windows {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::thread::JoinHandle;
+ use std::time::Duration;
+
+ use windows::Win32::Foundation::{HWND, POINT, RECT};
+ use windows::Win32::UI::WindowsAndMessaging::{
+ GetAncestor, GetCursorPos, GetForegroundWindow, GetWindowRect, IsIconic, IsWindow,
+ WindowFromPoint, GA_ROOT,
+ };
+
+ use super::{
+ DesktopJournal, DesktopSnapshot, FocusEvent, ObserverBackend, ObserverCapabilities,
+ ObserverError, TargetWindow, TargetZ,
+ };
+
+ pub struct WindowsObserver {
+ stop: Arc<AtomicBool>,
+ events: Arc<Mutex<Vec<FocusEvent>>>,
+ sampler: Option<JoinHandle<()>>,
+ }
+
+ impl WindowsObserver {
+ pub fn new() -> Self {
+ Self {
+ stop: Arc::new(AtomicBool::new(false)),
+ events: Arc::new(Mutex::new(Vec::new())),
+ sampler: None,
+ }
+ }
+ }
+
+ impl Default for WindowsObserver {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl ObserverBackend for WindowsObserver {
+ fn capabilities(&self) -> ObserverCapabilities {
+ ObserverCapabilities {
+ focus: true,
+ z_order: true,
+ cursor: true,
+ leaked_input: false,
+ }
+ }
+
+ fn snapshot(&self, target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let hwnd = HWND(target.native_id as *mut _);
+ let target_z = unsafe {
+ if !IsWindow(Some(hwnd)).as_bool() {
+ TargetZ::NotFound
+ } else if IsIconic(hwnd).as_bool() {
+ TargetZ::Minimized
+ } else if root(GetForegroundWindow()) == root(hwnd) {
+ TargetZ::Foreground
+ } else if is_occluded(hwnd)? {
+ TargetZ::BackgroundOccluded
+ } else {
+ TargetZ::BackgroundVisible
+ }
+ };
+ let foreground = unsafe { raw(root(GetForegroundWindow())) };
+ let mut cursor = POINT::default();
+ let cursor_pos = unsafe {
+ GetCursorPos(&mut cursor)
+ .ok()
+ .map(|_| (f64::from(cursor.x), f64::from(cursor.y)))
+ };
+ Ok(DesktopSnapshot {
+ foreground,
+ input_focus: foreground,
+ target_z,
+ cursor_pos,
+ })
+ }
+
+ fn start_journal(&mut self) -> Result<(), ObserverError> {
+ if self.sampler.is_some() {
+ return Err(ObserverError::new("Windows focus journal already active"));
+ }
+ self.stop.store(false, Ordering::Release);
+ self.events.lock().expect("focus journal lock").clear();
+ let stop = Arc::clone(&self.stop);
+ let events = Arc::clone(&self.events);
+ self.sampler = Some(std::thread::spawn(move || {
+ let mut previous = unsafe { raw(root(GetForegroundWindow())) };
+ while !stop.load(Ordering::Acquire) {
+ let current = unsafe { raw(root(GetForegroundWindow())) };
+ if current != previous {
+ events.lock().expect("focus journal lock").push(FocusEvent {
+ from: previous,
+ to: current,
+ });
+ previous = current;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }));
+ Ok(())
+ }
+
+ fn drain_journal(&mut self) -> Result<DesktopJournal, ObserverError> {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ sampler
+ .join()
+ .map_err(|_| ObserverError::new("Windows focus journal panicked"))?;
+ }
+ Ok(DesktopJournal {
+ focus_events: self.events.lock().expect("focus journal lock").clone(),
+ leaked_input_events: Vec::new(),
+ })
+ }
+ }
+
+ impl Drop for WindowsObserver {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ let _ = sampler.join();
+ }
+ }
+ }
+
+ unsafe fn root(hwnd: HWND) -> HWND {
+ if hwnd.0.is_null() {
+ hwnd
+ } else {
+ unsafe { GetAncestor(hwnd, GA_ROOT) }
+ }
+ }
+
+ fn raw(hwnd: HWND) -> Option<u64> {
+ (!hwnd.0.is_null()).then_some(hwnd.0 as usize as u64)
+ }
+
+ unsafe fn is_occluded(hwnd: HWND) -> Result<bool, ObserverError> {
+ let mut rect = RECT::default();
+ unsafe { GetWindowRect(hwnd, &mut rect) }
+ .map_err(|error| ObserverError::new(format!("GetWindowRect failed: {error}")))?;
+ if rect.right - rect.left <= 4 || rect.bottom - rect.top <= 4 {
+ return Ok(false);
+ }
+ let points = [
+ POINT {
+ x: rect.left + 2,
+ y: rect.top + 2,
+ },
+ POINT {
+ x: rect.right - 3,
+ y: rect.top + 2,
+ },
+ POINT {
+ x: rect.left + 2,
+ y: rect.bottom - 3,
+ },
+ POINT {
+ x: rect.right - 3,
+ y: rect.bottom - 3,
+ },
+ POINT {
+ x: (rect.left + rect.right) / 2,
+ y: (rect.top + rect.bottom) / 2,
+ },
+ ];
+ let target_root = unsafe { root(hwnd) };
+ let covered = points
+ .into_iter()
+ .filter(|point| {
+ let owner = unsafe { WindowFromPoint(*point) };
+ !owner.0.is_null() && unsafe { root(owner) } != target_root
+ })
+ .count();
+ Ok(covered >= 2)
+ }
+}
+
+#[cfg(target_os = "macos")]
+pub mod macos {
+ use std::ffi::c_void;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::thread::JoinHandle;
+ use std::time::Duration;
+
+ use core_foundation::array::{CFArray, CFArrayRef};
+ use core_foundation::base::{CFGetTypeID, CFTypeRef, TCFType};
+ use core_foundation::boolean::CFBoolean;
+ use core_foundation::dictionary::CFDictionary;
+ use core_foundation::number::CFNumber;
+ use core_foundation::string::CFString;
+ use objc2_app_kit::NSWorkspace;
+
+ use super::{
+ DesktopJournal, DesktopSnapshot, FocusEvent, ObserverBackend, ObserverCapabilities,
+ ObserverError, TargetWindow, TargetZ,
+ };
+
+ const WINDOW_LIST_ON_SCREEN: u32 = 1;
+ const WINDOW_LIST_EXCLUDE_DESKTOP: u32 = 16;
+
+ #[link(name = "CoreGraphics", kind = "framework")]
+ unsafe extern "C" {
+ fn CGWindowListCopyWindowInfo(option: u32, relative_to_window: u32) -> CFArrayRef;
+ fn CGEventCreate(source: *mut c_void) -> *mut c_void;
+ fn CGEventGetLocation(event: *mut c_void) -> CGPoint;
+ }
+
+ #[link(name = "CoreFoundation", kind = "framework")]
+ unsafe extern "C" {
+ fn CFRelease(value: *const c_void);
+ }
+
+ #[repr(C)]
+ struct CGPoint {
+ x: f64,
+ y: f64,
+ }
+
+ #[derive(Clone, Copy)]
+ struct Bounds {
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+ }
+
+ impl Bounds {
+ fn area(self) -> f64 {
+ self.width.max(0.0) * self.height.max(0.0)
+ }
+
+ fn intersection_area(self, other: Self) -> f64 {
+ let left = self.x.max(other.x);
+ let top = self.y.max(other.y);
+ let right = (self.x + self.width).min(other.x + other.width);
+ let bottom = (self.y + self.height).min(other.y + other.height);
+ (right - left).max(0.0) * (bottom - top).max(0.0)
+ }
+ }
+
+ struct WindowRow {
+ id: u64,
+ pid: u32,
+ on_screen: bool,
+ bounds: Bounds,
+ }
+
+ pub struct MacosObserver {
+ stop: Arc<AtomicBool>,
+ events: Arc<Mutex<Vec<FocusEvent>>>,
+ sampler: Option<JoinHandle<()>>,
+ }
+
+ impl MacosObserver {
+ pub fn new() -> Self {
+ Self {
+ stop: Arc::new(AtomicBool::new(false)),
+ events: Arc::new(Mutex::new(Vec::new())),
+ sampler: None,
+ }
+ }
+ }
+
+ impl Default for MacosObserver {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl ObserverBackend for MacosObserver {
+ fn capabilities(&self) -> ObserverCapabilities {
+ ObserverCapabilities {
+ focus: true,
+ z_order: true,
+ cursor: true,
+ leaked_input: false,
+ }
+ }
+
+ fn snapshot(&self, target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let rows = window_rows();
+ let target_index = rows.iter().position(|row| row.id == target.native_id);
+ let target_z = match target_index {
+ None => TargetZ::NotFound,
+ Some(index) if !rows[index].on_screen => TargetZ::Minimized,
+ Some(_) if frontmost_pid() == Some(target.pid as u64) => TargetZ::Foreground,
+ Some(index) => {
+ let target_bounds = rows[index].bounds;
+ let meaningful_cover = rows[..index].iter().any(|row| {
+ row.pid != target.pid
+ && target_bounds.intersection_area(row.bounds)
+ >= target_bounds.area() * 0.10
+ });
+ if meaningful_cover {
+ TargetZ::BackgroundOccluded
+ } else {
+ TargetZ::BackgroundVisible
+ }
+ }
+ };
+ let foreground = frontmost_pid();
+ Ok(DesktopSnapshot {
+ foreground,
+ input_focus: foreground,
+ target_z,
+ cursor_pos: cursor_position(),
+ })
+ }
+
+ fn start_journal(&mut self) -> Result<(), ObserverError> {
+ if self.sampler.is_some() {
+ return Err(ObserverError::new("macOS focus journal already active"));
+ }
+ self.stop.store(false, Ordering::Release);
+ self.events.lock().expect("focus journal lock").clear();
+ let stop = Arc::clone(&self.stop);
+ let events = Arc::clone(&self.events);
+ self.sampler = Some(std::thread::spawn(move || {
+ let mut previous = frontmost_pid();
+ while !stop.load(Ordering::Acquire) {
+ let current = frontmost_pid();
+ if current != previous {
+ events.lock().expect("focus journal lock").push(FocusEvent {
+ from: previous,
+ to: current,
+ });
+ previous = current;
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }));
+ Ok(())
+ }
+
+ fn drain_journal(&mut self) -> Result<DesktopJournal, ObserverError> {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ sampler
+ .join()
+ .map_err(|_| ObserverError::new("macOS focus journal panicked"))?;
+ }
+ Ok(DesktopJournal {
+ focus_events: self.events.lock().expect("focus journal lock").clone(),
+ leaked_input_events: Vec::new(),
+ })
+ }
+ }
+
+ impl Drop for MacosObserver {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ let _ = sampler.join();
+ }
+ }
+ }
+
+ fn frontmost_pid() -> Option<u64> {
+ unsafe {
+ Some(
+ NSWorkspace::sharedWorkspace()
+ .frontmostApplication()?
+ .processIdentifier() as u64,
+ )
+ }
+ }
+
+ fn cursor_position() -> Option<(f64, f64)> {
+ unsafe {
+ let event = CGEventCreate(std::ptr::null_mut());
+ if event.is_null() {
+ return None;
+ }
+ let point = CGEventGetLocation(event);
+ CFRelease(event);
+ Some((point.x, point.y))
+ }
+ }
+
+ fn window_rows() -> Vec<WindowRow> {
+ let raw = unsafe {
+ CGWindowListCopyWindowInfo(WINDOW_LIST_ON_SCREEN | WINDOW_LIST_EXCLUDE_DESKTOP, 0)
+ };
+ if raw.is_null() {
+ return Vec::new();
+ }
+ let array: CFArray<CFTypeRef> = unsafe { CFArray::wrap_under_create_rule(raw.cast()) };
+ array
+ .iter()
+ .filter_map(|item| parse_window_row(*item))
+ .collect()
+ }
+
+ fn parse_window_row(item: CFTypeRef) -> Option<WindowRow> {
+ let dictionary_type = CFDictionary::<*const c_void, *const c_void>::type_id();
+ if unsafe { CFGetTypeID(item) } != dictionary_type {
+ return None;
+ }
+ let dictionary: CFDictionary<*const c_void, *const c_void> =
+ unsafe { CFDictionary::wrap_under_get_rule(item.cast()) };
+ let id = number(&dictionary, "kCGWindowNumber")? as u64;
+ let pid = number(&dictionary, "kCGWindowOwnerPID")? as u32;
+ let on_screen = boolean(&dictionary, "kCGWindowIsOnscreen").unwrap_or(false);
+ let bounds = dictionary_value(&dictionary, "kCGWindowBounds")
+ .and_then(|value| {
+ if unsafe { CFGetTypeID(value) } != dictionary_type {
+ return None;
+ }
+ let bounds: CFDictionary<*const c_void, *const c_void> =
+ unsafe { CFDictionary::wrap_under_get_rule(value.cast()) };
+ Some(Bounds {
+ x: number(&bounds, "X").unwrap_or(0) as f64,
+ y: number(&bounds, "Y").unwrap_or(0) as f64,
+ width: number(&bounds, "Width").unwrap_or(0) as f64,
+ height: number(&bounds, "Height").unwrap_or(0) as f64,
+ })
+ })
+ .unwrap_or(Bounds {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ });
+ Some(WindowRow {
+ id,
+ pid,
+ on_screen,
+ bounds,
+ })
+ }
+
+ fn dictionary_value(
+ dictionary: &CFDictionary<*const c_void, *const c_void>,
+ key: &str,
+ ) -> Option<CFTypeRef> {
+ let key = CFString::new(key);
+ dictionary
+ .find(key.as_concrete_TypeRef().cast())
+ .map(|value| (*value).cast())
+ }
+
+ fn number(dictionary: &CFDictionary<*const c_void, *const c_void>, key: &str) -> Option<i64> {
+ let value = dictionary_value(dictionary, key)?;
+ if unsafe { CFGetTypeID(value) } != CFNumber::type_id() {
+ return None;
+ }
+ unsafe { CFNumber::wrap_under_get_rule(value.cast()) }.to_i64()
+ }
+
+ fn boolean(dictionary: &CFDictionary<*const c_void, *const c_void>, key: &str) -> Option<bool> {
+ let value = dictionary_value(dictionary, key)?;
+ if unsafe { CFGetTypeID(value) } != CFBoolean::type_id() {
+ return None;
+ }
+ Some(bool::from(unsafe {
+ CFBoolean::wrap_under_get_rule(value.cast())
+ }))
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn native_snapshot_reads_desktop_without_a_target() {
+ let snapshot = MacosObserver::new()
+ .snapshot(TargetWindow {
+ native_id: u64::MAX,
+ pid: u32::MAX,
+ })
+ .expect("macOS desktop snapshot");
+ assert_eq!(snapshot.target_z, TargetZ::NotFound);
+ assert!(snapshot.foreground.is_some());
+ assert!(snapshot.cursor_pos.is_some());
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+pub mod linux {
+ use std::process::{Command, Stdio};
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::{Arc, Mutex};
+ use std::thread::JoinHandle;
+ use std::time::Duration;
+
+ use serde::Deserialize;
+ use x11rb::connection::Connection;
+ use x11rb::protocol::xproto::{
+ AtomEnum, ConnectionExt, MapState, Rectangle, Window, WindowClass,
+ };
+ use x11rb::rust_connection::RustConnection;
+
+ use super::{
+ DesktopJournal, DesktopSnapshot, FocusEvent, ObserverBackend, ObserverCapabilities,
+ ObserverError, TargetWindow, TargetZ,
+ };
+
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
+ enum SessionKind {
+ X11,
+ Sway,
+ Gnome,
+ CuaCompositor,
+ Missing,
+ }
+
+ pub struct LinuxObserver {
+ session: SessionKind,
+ stop: Arc<AtomicBool>,
+ events: Arc<Mutex<Vec<FocusEvent>>>,
+ sampler: Option<JoinHandle<()>>,
+ }
+
+ impl LinuxObserver {
+ pub fn new() -> Self {
+ let explicit_wayland = std::env::var("XDG_SESSION_TYPE")
+ .map(|value| value.eq_ignore_ascii_case("wayland"))
+ .unwrap_or(false)
+ || std::env::var_os("WAYLAND_DISPLAY").is_some();
+ let session = if explicit_wayland {
+ if cua_compositor_available() {
+ SessionKind::CuaCompositor
+ } else if sway_available() {
+ SessionKind::Sway
+ } else if gnome_windows().is_ok() {
+ SessionKind::Gnome
+ } else {
+ SessionKind::Missing
+ }
+ } else if std::env::var_os("DISPLAY").is_some() {
+ if x11_window_manager_ready() {
+ SessionKind::X11
+ } else {
+ SessionKind::Missing
+ }
+ } else {
+ SessionKind::Missing
+ };
+ Self {
+ session,
+ stop: Arc::new(AtomicBool::new(false)),
+ events: Arc::new(Mutex::new(Vec::new())),
+ sampler: None,
+ }
+ }
+ }
+
+ impl Default for LinuxObserver {
+ fn default() -> Self {
+ Self::new()
+ }
+ }
+
+ impl ObserverBackend for LinuxObserver {
+ fn capabilities(&self) -> ObserverCapabilities {
+ match self.session {
+ SessionKind::X11 => ObserverCapabilities {
+ focus: true,
+ z_order: true,
+ cursor: true,
+ leaked_input: false,
+ },
+ SessionKind::Sway | SessionKind::Gnome | SessionKind::CuaCompositor => {
+ ObserverCapabilities {
+ focus: true,
+ z_order: true,
+ cursor: false,
+ leaked_input: false,
+ }
+ }
+ SessionKind::Missing => ObserverCapabilities::default(),
+ }
+ }
+
+ fn snapshot(&self, target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ match self.session {
+ SessionKind::X11 => x11_snapshot(target),
+ SessionKind::Sway => sway_snapshot(target),
+ SessionKind::Gnome => gnome_snapshot(target),
+ SessionKind::CuaCompositor => cua_compositor_snapshot(target),
+ SessionKind::Missing => Ok(DesktopSnapshot {
+ foreground: None,
+ input_focus: None,
+ target_z: TargetZ::NotFound,
+ cursor_pos: None,
+ }),
+ }
+ }
+
+ fn start_journal(&mut self) -> Result<(), ObserverError> {
+ if self.sampler.is_some() {
+ return Err(ObserverError::new("Linux focus journal already active"));
+ }
+ self.stop.store(false, Ordering::Release);
+ self.events.lock().expect("focus journal lock").clear();
+ if self.session == SessionKind::Missing {
+ return Ok(());
+ }
+ let session = self.session;
+ let stop = Arc::clone(&self.stop);
+ let events = Arc::clone(&self.events);
+ self.sampler = Some(std::thread::spawn(move || {
+ let focus_identity = || match session {
+ SessionKind::X11 => x11_focus_identity(),
+ SessionKind::Sway => sway_focus_identity(),
+ SessionKind::Gnome => gnome_focus_identity(),
+ SessionKind::CuaCompositor => cua_compositor_focus_identity(),
+ SessionKind::Missing => Ok(None),
+ };
+ let mut previous = focus_identity().ok().flatten();
+ while !stop.load(Ordering::Acquire) {
+ if let Ok(current) = focus_identity() {
+ if current != previous {
+ events.lock().expect("focus journal lock").push(FocusEvent {
+ from: previous,
+ to: current,
+ });
+ previous = current;
+ }
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ }));
+ Ok(())
+ }
+
+ fn drain_journal(&mut self) -> Result<DesktopJournal, ObserverError> {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ sampler
+ .join()
+ .map_err(|_| ObserverError::new("Linux focus journal panicked"))?;
+ }
+ Ok(DesktopJournal {
+ focus_events: self.events.lock().expect("focus journal lock").clone(),
+ leaked_input_events: Vec::new(),
+ })
+ }
+ }
+
+ impl Drop for LinuxObserver {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(sampler) = self.sampler.take() {
+ let _ = sampler.join();
+ }
+ }
+ }
+
+ fn x11_connection() -> Result<(RustConnection, usize), ObserverError> {
+ x11rb::connect(None)
+ .map_err(|error| ObserverError::new(format!("X11 connect failed: {error}")))
+ }
+
+ #[derive(Default)]
+ struct SwayTreeState {
+ focused: Option<u64>,
+ focused_workspace: Option<u64>,
+ focused_fullscreen: Option<u64>,
+ target: Option<(u64, bool, Option<u64>)>,
+ }
+
+ fn sway_tree() -> Result<serde_json::Value, ObserverError> {
+ let output = Command::new("swaymsg")
+ .args(["-r", "-t", "get_tree"])
+ .output()
+ .map_err(|error| ObserverError::new(format!("swaymsg get_tree failed: {error}")))?;
+ if !output.status.success() {
+ return Err(ObserverError::new(format!(
+ "swaymsg get_tree exited with {}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ )));
+ }
+ serde_json::from_slice(&output.stdout)
+ .map_err(|error| ObserverError::new(format!("invalid sway tree JSON: {error}")))
+ }
+
+ fn sway_available() -> bool {
+ std::env::var_os("SWAYSOCK").is_some_and(|value| !value.is_empty()) && sway_tree().is_ok()
+ }
+
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
+ struct CuaCompositorState {
+ focused_pid: Option<u64>,
+ target_z: TargetZ,
+ }
+
+ fn parse_cua_compositor_state(line: &str) -> Result<CuaCompositorState, ObserverError> {
+ let mut fields = line.split_whitespace();
+ if fields.next() != Some("state") {
+ return Err(ObserverError::new(format!(
+ "invalid cua-compositor observer response: {line:?}"
+ )));
+ }
+ let focused_pid = fields
+ .next()
+ .ok_or_else(|| ObserverError::new("cua-compositor state omitted focused pid"))?
+ .parse::<u64>()
+ .map_err(|error| ObserverError::new(format!("invalid focused pid: {error}")))?;
+ let target_z = match fields.next() {
+ Some("foreground") => TargetZ::Foreground,
+ Some("background_occluded") => TargetZ::BackgroundOccluded,
+ Some("background_visible") => TargetZ::BackgroundVisible,
+ Some("not_found") => TargetZ::NotFound,
+ Some(value) => {
+ return Err(ObserverError::new(format!(
+ "invalid cua-compositor target state: {value}"
+ )))
+ }
+ None => {
+ return Err(ObserverError::new(
+ "cua-compositor state omitted target state",
+ ))
+ }
+ };
+ if fields.next().is_some() {
+ return Err(ObserverError::new(
+ "cua-compositor state contained trailing fields",
+ ));
+ }
+ Ok(CuaCompositorState {
+ focused_pid: (focused_pid != 0).then_some(focused_pid),
+ target_z,
+ })
+ }
+
+ fn cua_compositor_state(target_pid: u32) -> Result<CuaCompositorState, ObserverError> {
+ use std::io::{BufRead, BufReader, Write};
+ use std::os::unix::net::UnixStream;
+
+ let socket = std::env::var("CUA_INJECT_SOCKET")
+ .map_err(|_| ObserverError::new("CUA_INJECT_SOCKET is not set"))?;
+ let stream = UnixStream::connect(&socket).map_err(|error| {
+ ObserverError::new(format!("connect cua-compositor observer socket: {error}"))
+ })?;
+ stream
+ .set_read_timeout(Some(Duration::from_secs(2)))
+ .map_err(|error| ObserverError::new(format!("set observer timeout: {error}")))?;
+ let mut writer = stream
+ .try_clone()
+ .map_err(|error| ObserverError::new(format!("clone observer socket: {error}")))?;
+ let mut reader = BufReader::new(stream);
+
+ writeln!(writer, "cua-inject v1")
+ .and_then(|_| writer.flush())
+ .map_err(|error| ObserverError::new(format!("write observer handshake: {error}")))?;
+ let mut line = String::new();
+ reader
+ .read_line(&mut line)
+ .map_err(|error| ObserverError::new(format!("read observer handshake: {error}")))?;
+ if line.trim() != "cua-inject v1" {
+ return Err(ObserverError::new(format!(
+ "cua-compositor observer handshake mismatch: {:?}",
+ line.trim()
+ )));
+ }
+
+ writeln!(writer, "q {target_pid}")
+ .and_then(|_| writer.flush())
+ .map_err(|error| ObserverError::new(format!("write observer query: {error}")))?;
+ line.clear();
+ let read = reader
+ .read_line(&mut line)
+ .map_err(|error| ObserverError::new(format!("read observer query: {error}")))?;
+ if read == 0 {
+ return Err(ObserverError::new(
+ "cua-compositor closed the observer query",
+ ));
+ }
+ parse_cua_compositor_state(&line)
+ }
+
+ fn cua_compositor_available() -> bool {
+ std::env::var_os("CUA_INJECT_SOCKET").is_some() && cua_compositor_state(0).is_ok()
+ }
+
+ fn cua_compositor_snapshot(target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let state = cua_compositor_state(target.pid)?;
+ Ok(DesktopSnapshot {
+ foreground: state.focused_pid,
+ input_focus: state.focused_pid,
+ target_z: state.target_z,
+ cursor_pos: None,
+ })
+ }
+
+ fn cua_compositor_focus_identity() -> Result<Option<u64>, ObserverError> {
+ Ok(cua_compositor_state(0)?.focused_pid)
+ }
+
+ #[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
+ struct GnomeWindow {
+ id: u64,
+ pid: u32,
+ #[serde(rename = "title")]
+ _title: String,
+ x: i64,
+ y: i64,
+ w: i64,
+ h: i64,
+ focused: bool,
+ minimized: bool,
+ visible: bool,
+ stacking: u64,
+ }
+
+ fn gnome_windows() -> Result<Vec<GnomeWindow>, ObserverError> {
+ let mut child = Command::new("gdbus")
+ .args([
+ "call",
+ "--session",
+ "--dest",
+ "org.cua.WinRects",
+ "--object-path",
+ "/org/cua/WinRects",
+ "--method",
+ "org.cua.WinRects.GetRects",
+ ])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| ObserverError::new(format!("gdbus GetRects failed: {error}")))?;
+ let deadline = std::time::Instant::now() + Duration::from_millis(800);
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => {
+ let output = child.wait_with_output().map_err(|error| {
+ ObserverError::new(format!("gdbus GetRects output failed: {error}"))
+ })?;
+ if !output.status.success() {
+ return Err(ObserverError::new(format!(
+ "gdbus GetRects exited with {}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ )));
+ }
+ return parse_gnome_windows(&String::from_utf8_lossy(&output.stdout));
+ }
+ Ok(None) if std::time::Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(15))
+ }
+ Ok(None) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(ObserverError::new("gdbus GetRects timed out"));
+ }
+ Err(error) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(ObserverError::new(format!(
+ "gdbus GetRects wait failed: {error}"
+ )));
+ }
+ }
+ }
+ }
+
+ fn parse_gnome_windows(raw: &str) -> Result<Vec<GnomeWindow>, ObserverError> {
+ let start = raw
+ .find('[')
+ .ok_or_else(|| ObserverError::new("GetRects response had no JSON array"))?;
+ let end = raw
+ .rfind(']')
+ .filter(|end| *end >= start)
+ .ok_or_else(|| ObserverError::new("GetRects response had no complete JSON array"))?;
+ serde_json::from_str(&raw[start..=end])
+ .map_err(|error| ObserverError::new(format!("invalid GetRects JSON: {error}")))
+ }
+
+ fn gnome_target<'a>(
+ windows: &'a [GnomeWindow],
+ target: TargetWindow,
+ ) -> Option<&'a GnomeWindow> {
+ let matching = windows.iter().filter(|window| window.pid == target.pid);
+ matching
+ .clone()
+ .find(|window| window.id == target.native_id)
+ .or_else(|| matching.max_by_key(|window| window.stacking))
+ }
+
+ fn fully_covers(cover: &GnomeWindow, target: &GnomeWindow) -> bool {
+ target.w > 0
+ && target.h > 0
+ && cover.w > 0
+ && cover.h > 0
+ && cover.x <= target.x
+ && cover.y <= target.y
+ && cover.x.saturating_add(cover.w) >= target.x.saturating_add(target.w)
+ && cover.y.saturating_add(cover.h) >= target.y.saturating_add(target.h)
+ }
+
+ fn classify_gnome_target(windows: &[GnomeWindow], target: TargetWindow) -> TargetZ {
+ let Some(target) = gnome_target(windows, target) else {
+ return TargetZ::NotFound;
+ };
+ if target.focused {
+ TargetZ::Foreground
+ } else if target.minimized || !target.visible {
+ TargetZ::Minimized
+ } else if windows.iter().any(|window| {
+ window.stacking > target.stacking
+ && window.visible
+ && !window.minimized
+ && fully_covers(window, target)
+ }) {
+ TargetZ::BackgroundOccluded
+ } else {
+ TargetZ::BackgroundVisible
+ }
+ }
+
+ fn gnome_focus_identity_from(windows: &[GnomeWindow]) -> Option<u64> {
+ windows
+ .iter()
+ .find(|window| window.focused)
+ .map(|window| window.id)
+ }
+
+ fn gnome_snapshot(target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let windows = gnome_windows()?;
+ let focused = gnome_focus_identity_from(&windows);
+ Ok(DesktopSnapshot {
+ foreground: focused,
+ input_focus: focused,
+ target_z: classify_gnome_target(&windows, target),
+ cursor_pos: None,
+ })
+ }
+
+ fn gnome_focus_identity() -> Result<Option<u64>, ObserverError> {
+ Ok(gnome_focus_identity_from(&gnome_windows()?))
+ }
+
+ fn walk_sway_tree(
+ node: &serde_json::Value,
+ target_pid: u32,
+ workspace: Option<u64>,
+ state: &mut SwayTreeState,
+ ) {
+ let id = node["id"].as_u64();
+ let workspace = if node["type"].as_str() == Some("workspace") {
+ id
+ } else {
+ workspace
+ };
+ let focused = node["focused"].as_bool().unwrap_or(false);
+ if focused {
+ state.focused = id;
+ state.focused_workspace = workspace;
+ if node["fullscreen_mode"].as_i64().unwrap_or(0) != 0 {
+ state.focused_fullscreen = id;
+ }
+ }
+ if node["pid"].as_u64() == Some(u64::from(target_pid)) {
+ if let Some(id) = id {
+ state.target = Some((id, node["visible"].as_bool().unwrap_or(true), workspace));
+ }
+ }
+ for child in ["nodes", "floating_nodes"]
+ .into_iter()
+ .flat_map(|key| node[key].as_array().into_iter().flatten())
+ {
+ walk_sway_tree(child, target_pid, workspace, state);
+ }
+ }
+
+ fn classify_sway_target(state: &SwayTreeState) -> TargetZ {
+ match state.target {
+ None => TargetZ::NotFound,
+ Some((id, _, _)) if state.focused == Some(id) => TargetZ::Foreground,
+ Some((_, _, target_workspace))
+ if state.focused_fullscreen.is_some()
+ && target_workspace == state.focused_workspace =>
+ {
+ // Sway reports windows hidden behind a fullscreen sibling as
+ // visible=false. They are occluded, not minimized.
+ TargetZ::BackgroundOccluded
+ }
+ Some((_, false, _)) => TargetZ::Minimized,
+ Some(_) => TargetZ::BackgroundVisible,
+ }
+ }
+
+ fn sway_snapshot(target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let tree = sway_tree()?;
+ let mut state = SwayTreeState::default();
+ walk_sway_tree(&tree, target.pid, None, &mut state);
+ let target_z = classify_sway_target(&state);
+ Ok(DesktopSnapshot {
+ foreground: state.focused,
+ input_focus: state.focused,
+ target_z,
+ cursor_pos: None,
+ })
+ }
+
+ fn sway_focus_identity() -> Result<Option<u64>, ObserverError> {
+ let tree = sway_tree()?;
+ let mut state = SwayTreeState::default();
+ walk_sway_tree(&tree, 0, None, &mut state);
+ Ok(state.focused)
+ }
+
+ fn x11_snapshot(target: TargetWindow) -> Result<DesktopSnapshot, ObserverError> {
+ let (connection, screen_index) = x11_connection()?;
+ let root = connection.setup().roots[screen_index].root;
+ let target = u32::try_from(target.native_id)
+ .map_err(|_| ObserverError::new("X11 window id does not fit in u32"))?;
+ let target_root = match top_level(&connection, target, root) {
+ Ok(window) => window,
+ Err(_) => {
+ return Ok(DesktopSnapshot {
+ foreground: active_window(&connection, root)?.map(u64::from),
+ input_focus: input_focus(&connection, root)?.map(u64::from),
+ target_z: TargetZ::NotFound,
+ cursor_pos: query_pointer(&connection, root)?,
+ });
+ }
+ };
+ let active = active_window(&connection, root)?;
+ let focus = input_focus(&connection, root)?;
+ let target_z = if !is_viewable(&connection, target_root)? {
+ TargetZ::Minimized
+ } else if active == Some(target_root) || focus == Some(target_root) {
+ TargetZ::Foreground
+ } else if is_occluded(&connection, root, target_root)? {
+ TargetZ::BackgroundOccluded
+ } else {
+ TargetZ::BackgroundVisible
+ };
+ Ok(DesktopSnapshot {
+ foreground: active.map(u64::from),
+ input_focus: focus.map(u64::from),
+ target_z,
+ cursor_pos: query_pointer(&connection, root)?,
+ })
+ }
+
+ fn x11_focus_identity() -> Result<Option<u64>, ObserverError> {
+ let (connection, screen_index) = x11_connection()?;
+ let root = connection.setup().roots[screen_index].root;
+ Ok(active_window(&connection, root)?
+ .or(input_focus(&connection, root)?)
+ .map(u64::from))
+ }
+
+ fn x11_window_manager_ready() -> bool {
+ let Ok((connection, screen_index)) = x11_connection() else {
+ return false;
+ };
+ let root = connection.setup().roots[screen_index].root;
+ let Ok(atom_cookie) = connection.intern_atom(false, b"_NET_SUPPORTING_WM_CHECK") else {
+ return false;
+ };
+ let Ok(atom_reply) = atom_cookie.reply() else {
+ return false;
+ };
+ let atom = atom_reply.atom;
+ let read_window = |window| {
+ connection
+ .get_property(false, window, atom, AtomEnum::WINDOW, 0, 1)
+ .ok()?
+ .reply()
+ .ok()?
+ .value32()?
+ .next()
+ };
+ let Some(manager) = read_window(root) else {
+ return false;
+ };
+ manager != 0 && read_window(manager) == Some(manager)
+ }
+
+ fn active_window(
+ connection: &RustConnection,
+ root: Window,
+ ) -> Result<Option<Window>, ObserverError> {
+ let atom = connection
+ .intern_atom(false, b"_NET_ACTIVE_WINDOW")
+ .map_err(x11_error("intern _NET_ACTIVE_WINDOW"))?
+ .reply()
+ .map_err(x11_error("read _NET_ACTIVE_WINDOW atom"))?
+ .atom;
+ let reply = connection
+ .get_property(false, root, atom, AtomEnum::WINDOW, 0, 1)
+ .map_err(x11_error("request _NET_ACTIVE_WINDOW"))?
+ .reply()
+ .map_err(x11_error("read _NET_ACTIVE_WINDOW"))?;
+ let active = reply
+ .value32()
+ .and_then(|mut values| values.next())
+ .filter(|window| *window != 0);
+ active
+ .map(|window| top_level(connection, window, root))
+ .transpose()
+ }
+
+ fn input_focus(
+ connection: &RustConnection,
+ root: Window,
+ ) -> Result<Option<Window>, ObserverError> {
+ let window = connection
+ .get_input_focus()
+ .map_err(x11_error("request input focus"))?
+ .reply()
+ .map_err(x11_error("read input focus"))?
+ .focus;
+ if window == 0 || window == 1 {
+ Ok(None)
+ } else {
+ top_level(connection, window, root).map(Some)
+ }
+ }
+
+ fn top_level(
+ connection: &RustConnection,
+ mut window: Window,
+ root: Window,
+ ) -> Result<Window, ObserverError> {
+ for _ in 0..32 {
+ let tree = connection
+ .query_tree(window)
+ .map_err(x11_error("request X11 window tree"))?
+ .reply()
+ .map_err(x11_error("read X11 window tree"))?;
+ if tree.parent == root || window == root {
+ return Ok(window);
+ }
+ window = tree.parent;
+ }
+ Err(ObserverError::new("X11 window ancestry exceeded 32 levels"))
+ }
+
+ fn is_viewable(connection: &RustConnection, window: Window) -> Result<bool, ObserverError> {
+ let attributes = connection
+ .get_window_attributes(window)
+ .map_err(x11_error("request X11 window attributes"))?
+ .reply()
+ .map_err(x11_error("read X11 window attributes"))?;
+ Ok(attributes.class == WindowClass::INPUT_OUTPUT
+ && attributes.map_state == MapState::VIEWABLE)
+ }
+
+ fn absolute_bounds(
+ connection: &RustConnection,
+ window: Window,
+ root: Window,
+ ) -> Result<Rectangle, ObserverError> {
+ let geometry = connection
+ .get_geometry(window)
+ .map_err(x11_error("request X11 window geometry"))?
+ .reply()
+ .map_err(x11_error("read X11 window geometry"))?;
+ let translated = connection
+ .translate_coordinates(window, root, 0, 0)
+ .map_err(x11_error("request X11 translated coordinates"))?
+ .reply()
+ .map_err(x11_error("read X11 translated coordinates"))?;
+ Ok(Rectangle {
+ x: translated.dst_x,
+ y: translated.dst_y,
+ width: geometry.width,
+ height: geometry.height,
+ })
+ }
+
+ fn is_occluded(
+ connection: &RustConnection,
+ root: Window,
+ target: Window,
+ ) -> Result<bool, ObserverError> {
+ let target_bounds = absolute_bounds(connection, target, root)?;
+ if target_bounds.width <= 4 || target_bounds.height <= 4 {
+ return Ok(false);
+ }
+ let covered = sample_points(target_bounds)
+ .into_iter()
+ .filter(|(x, y)| {
+ connection
+ .translate_coordinates(root, root, *x, *y)
+ .ok()
+ .and_then(|cookie| cookie.reply().ok())
+ .map(|reply| reply.child != 0 && reply.child != target)
+ .unwrap_or(true)
+ })
+ .count();
+ Ok(covered >= 2)
+ }
+
+ fn sample_points(bounds: Rectangle) -> [(i16, i16); 5] {
+ let left = bounds.x.saturating_add(2);
+ let top = bounds.y.saturating_add(2);
+ let right = i32::from(bounds.x)
+ .saturating_add(i32::from(bounds.width))
+ .saturating_sub(3)
+ .clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
+ let bottom = i32::from(bounds.y)
+ .saturating_add(i32::from(bounds.height))
+ .saturating_sub(3)
+ .clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
+ let center_x = i32::from(bounds.x)
+ .saturating_add(i32::from(bounds.width) / 2)
+ .clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
+ let center_y = i32::from(bounds.y)
+ .saturating_add(i32::from(bounds.height) / 2)
+ .clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16;
+ [
+ (left, top),
+ (right, top),
+ (left, bottom),
+ (right, bottom),
+ (center_x, center_y),
+ ]
+ }
+
+ fn query_pointer(
+ connection: &RustConnection,
+ root: Window,
+ ) -> Result<Option<(f64, f64)>, ObserverError> {
+ let pointer = connection
+ .query_pointer(root)
+ .map_err(x11_error("request X11 pointer"))?
+ .reply()
+ .map_err(x11_error("read X11 pointer"))?;
+ Ok(Some((f64::from(pointer.root_x), f64::from(pointer.root_y))))
+ }
+
+ fn x11_error<E: std::fmt::Display>(operation: &'static str) -> impl FnOnce(E) -> ObserverError {
+ move |error| ObserverError::new(format!("{operation} failed: {error}"))
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ fn gnome_payload() -> &'static str {
+ r#"('[{"id":10,"pid":100,"title":"target","x":10,"y":20,"w":300,"h":200,"focused":false,"minimized":false,"visible":true,"stacking":0},{"id":20,"pid":200,"title":"sentinel","x":0,"y":0,"w":800,"h":600,"focused":true,"minimized":false,"visible":true,"stacking":1}]',)"#
+ }
+
+ #[test]
+ fn occlusion_samples_corners_and_center() {
+ let bounds = Rectangle {
+ x: -100,
+ y: 20,
+ width: 200,
+ height: 100,
+ };
+ assert_eq!(
+ sample_points(bounds),
+ [(-98, 22), (97, 22), (-98, 117), (97, 117), (0, 70)]
+ );
+ }
+
+ #[test]
+ fn sway_hidden_target_behind_fullscreen_sibling_is_occluded() {
+ let state = SwayTreeState {
+ focused: Some(30),
+ focused_workspace: Some(10),
+ focused_fullscreen: Some(30),
+ target: Some((20, false, Some(10))),
+ };
+ assert_eq!(classify_sway_target(&state), TargetZ::BackgroundOccluded);
+ }
+
+ #[test]
+ fn sway_hidden_target_on_another_workspace_is_not_occluded() {
+ let state = SwayTreeState {
+ focused: Some(30),
+ focused_workspace: Some(10),
+ focused_fullscreen: Some(30),
+ target: Some((20, false, Some(11))),
+ };
+ assert_eq!(classify_sway_target(&state), TargetZ::Minimized);
+ }
+
+ #[test]
+ fn cua_compositor_state_is_strict_and_pid_based() {
+ assert_eq!(
+ parse_cua_compositor_state("state 200 background_occluded\n")
+ .expect("valid compositor state"),
+ CuaCompositorState {
+ focused_pid: Some(200),
+ target_z: TargetZ::BackgroundOccluded,
+ }
+ );
+ assert_eq!(
+ parse_cua_compositor_state("state 0 not_found")
+ .expect("zero means no focused client"),
+ CuaCompositorState {
+ focused_pid: None,
+ target_z: TargetZ::NotFound,
+ }
+ );
+ assert!(parse_cua_compositor_state("ok").is_err());
+ assert!(parse_cua_compositor_state("state 1 unknown").is_err());
+ assert!(parse_cua_compositor_state("state 1 foreground trailing").is_err());
+ }
+
+ #[test]
+ fn gnome_json_and_focus_identity_are_compositor_derived() {
+ let windows = parse_gnome_windows(gnome_payload()).expect("GNOME JSON");
+ assert_eq!(windows.len(), 2);
+ assert_eq!(gnome_focus_identity_from(&windows), Some(20));
+ assert!(parse_gnome_windows(r#"('[{"pid":100}]',)"#).is_err());
+ }
+
+ #[test]
+ fn gnome_only_full_higher_cover_occludes() {
+ let mut windows = parse_gnome_windows(gnome_payload()).expect("GNOME JSON");
+ let target = TargetWindow {
+ pid: 100,
+ native_id: 10,
+ };
+ assert_eq!(
+ classify_gnome_target(&windows, target),
+ TargetZ::BackgroundOccluded
+ );
+ windows[1].w = 200;
+ assert_eq!(
+ classify_gnome_target(&windows, target),
+ TargetZ::BackgroundVisible
+ );
+ windows[1].w = 800;
+ windows[1].visible = false;
+ assert_eq!(
+ classify_gnome_target(&windows, target),
+ TargetZ::BackgroundVisible
+ );
+ }
+
+ #[test]
+ fn gnome_focused_and_minimized_are_direct() {
+ let mut windows = parse_gnome_windows(gnome_payload()).expect("GNOME JSON");
+ let target = TargetWindow {
+ pid: 100,
+ native_id: 10,
+ };
+ windows[0].focused = true;
+ assert_eq!(classify_gnome_target(&windows, target), TargetZ::Foreground);
+ windows[0].focused = false;
+ windows[0].minimized = true;
+ assert_eq!(classify_gnome_target(&windows, target), TargetZ::Minimized);
+ }
+ }
+}
+
+#[cfg(target_os = "linux")]
+pub use linux::LinuxObserver as NativeObserver;
+#[cfg(target_os = "macos")]
+pub use macos::MacosObserver as NativeObserver;
+#[cfg(target_os = "windows")]
+pub use windows::WindowsObserver as NativeObserver;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn snapshot(foreground: u64, target_z: TargetZ, cursor: (f64, f64)) -> DesktopSnapshot {
+ DesktopSnapshot {
+ foreground: Some(foreground),
+ input_focus: Some(foreground),
+ target_z,
+ cursor_pos: Some(cursor),
+ }
+ }
+
+ #[test]
+ fn transient_focus_change_fails_even_when_pre_and_post_match() {
+ let before = snapshot(10, TargetZ::BackgroundOccluded, (100.0, 100.0));
+ let after = before.clone();
+ let delta = evaluate(
+ ObserverCapabilities {
+ focus: true,
+ ..ObserverCapabilities::default()
+ },
+ &[OracleKind::Focus],
+ before,
+ after,
+ DesktopJournal {
+ focus_events: vec![
+ FocusEvent {
+ from: Some(10),
+ to: Some(20),
+ },
+ FocusEvent {
+ from: Some(20),
+ to: Some(10),
+ },
+ ],
+ leaked_input_events: Vec::new(),
+ },
+ );
+ assert!(delta.passed().is_empty());
+ assert!(delta.violations()[0].contains("transiently"));
+ }
+
+ #[test]
+ fn input_focus_change_fails_when_foreground_is_stable() {
+ let before = snapshot(10, TargetZ::BackgroundOccluded, (100.0, 100.0));
+ let mut after = before.clone();
+ after.input_focus = Some(20);
+ let delta = evaluate(
+ ObserverCapabilities {
+ focus: true,
+ ..ObserverCapabilities::default()
+ },
+ &[OracleKind::Focus],
+ before,
+ after,
+ DesktopJournal::default(),
+ );
+ assert!(delta.passed().is_empty());
+ assert!(delta.violations()[0].contains("input focus changed"));
+ }
+
+ #[test]
+ fn target_raise_cursor_move_and_input_leak_are_independent_failures() {
+ let delta = evaluate(
+ ObserverCapabilities {
+ focus: true,
+ z_order: true,
+ cursor: true,
+ leaked_input: true,
+ },
+ &[
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::Cursor,
+ OracleKind::NoLeakedInput,
+ ],
+ snapshot(10, TargetZ::BackgroundOccluded, (100.0, 100.0)),
+ snapshot(10, TargetZ::BackgroundVisible, (102.0, 100.0)),
+ DesktopJournal {
+ focus_events: Vec::new(),
+ leaked_input_events: vec!["keydown:A".to_owned()],
+ },
+ );
+ assert_eq!(delta.passed(), &[OracleKind::Focus]);
+ assert_eq!(delta.violations().len(), 3);
+ }
+
+ #[test]
+ fn unsupported_oracle_is_never_counted_as_passed() {
+ let state = snapshot(10, TargetZ::BackgroundOccluded, (100.0, 100.0));
+ let delta = evaluate(
+ ObserverCapabilities::default(),
+ &[OracleKind::NoLeakedInput],
+ state.clone(),
+ state,
+ DesktopJournal::default(),
+ );
+ assert_eq!(delta.unsupported(), &[OracleKind::NoLeakedInput]);
+ assert!(delta.ensure_supported().is_err());
+ assert!(delta.passed().is_empty());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/paths.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/paths.rs
index 1bb58655cb..2aafd74cbc 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/paths.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/paths.rs
@@ -34,6 +34,18 @@ pub fn driver_binary() -> PathBuf {
} else {
"cua-driver"
};
+ if let Ok(test_exe) = std::env::current_exe() {
+ if let Some(profile_dir) = test_exe
+ .parent()
+ .filter(|dir| dir.file_name().is_some_and(|name| name == "deps"))
+ .and_then(std::path::Path::parent)
+ {
+ let sibling = profile_dir.join(name);
+ if sibling.exists() {
+ return sibling;
+ }
+ }
+ }
let root = workspace_root();
let release = root.join("target/release").join(name);
if release.exists() {
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/reaper.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/reaper.rs
index a184c118bb..ac38d186c7 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/reaper.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/reaper.rs
@@ -15,7 +15,10 @@ pub struct ChildReaper {
impl ChildReaper {
pub fn new() -> Self {
- ChildReaper { children: Vec::new(), pids: Vec::new() }
+ ChildReaper {
+ children: Vec::new(),
+ pids: Vec::new(),
+ }
}
/// Spawn `cmd` into the kill-on-close job (Windows) and own the child.
@@ -55,6 +58,7 @@ impl Drop for ChildReaper {
tree_kill(pid);
}
for c in &mut self.children {
+ tree_kill(c.id());
let _ = c.kill();
let _ = c.wait();
}
@@ -100,8 +104,8 @@ mod win {
use std::sync::OnceLock;
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::{
- AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject,
- JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
+ SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
@@ -112,7 +116,8 @@ mod win {
fn job() -> HANDLE {
let raw = *JOB.get_or_init(|| unsafe {
- let h = CreateJobObjectW(None, windows::core::PCWSTR::null()).expect("CreateJobObjectW");
+ let h =
+ CreateJobObjectW(None, windows::core::PCWSTR::null()).expect("CreateJobObjectW");
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let _ = SetInformationJobObject(
@@ -130,7 +135,12 @@ mod win {
pub(super) fn assign_child(child: &Child) {
unsafe {
let h = HANDLE(child.as_raw_handle() as *mut c_void);
- let _ = AssignProcessToJobObject(job(), h);
+ if let Err(error) = AssignProcessToJobObject(job(), h) {
+ eprintln!(
+ "[testkit] could not assign child {} to job: {error}",
+ child.id()
+ );
+ }
}
}
@@ -139,7 +149,9 @@ mod win {
unsafe {
if let Ok(h) = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, pid) {
if !h.is_invalid() {
- let _ = AssignProcessToJobObject(job(), h);
+ if let Err(error) = AssignProcessToJobObject(job(), h) {
+ eprintln!("[testkit] could not assign pid {pid} to job: {error}");
+ }
let _ = CloseHandle(h);
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs
index e828766fa6..41418727c2 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/response.rs
@@ -33,6 +33,8 @@ impl ToolResponse {
pub(crate) fn from_mcp(raw: Value) -> Self {
let text = raw["result"]["content"][0]["text"]
.as_str()
+ .or_else(|| raw["error"]["message"].as_str())
+ .or_else(|| raw["error"].as_str())
.unwrap_or("")
.to_string();
let structured = raw["result"]["structuredContent"].clone();
@@ -99,3 +101,23 @@ impl ToolResponse {
.unwrap_or(false)
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::ToolResponse;
+
+ #[test]
+ fn mcp_error_text_accepts_object_and_string_envelopes() {
+ let object = ToolResponse::from_mcp(serde_json::json!({
+ "error": { "message": "object error" }
+ }));
+ assert!(object.is_error());
+ assert_eq!(object.text(), "object error");
+
+ let string = ToolResponse::from_mcp(serde_json::json!({
+ "error": "string error"
+ }));
+ assert!(string.is_error());
+ assert_eq!(string.text(), "string error");
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
new file mode 100644
index 0000000000..ad6b9171d3
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/sentinel.rs
@@ -0,0 +1,417 @@
+//! Full-desktop foreground sentinel used by background E2E cells.
+
+use std::fs;
+use std::net::TcpListener;
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use crate::e2e::OracleKind;
+use crate::observer::{DesktopObserver, NativeObserver, TargetWindow};
+use crate::{harness_app, spawn_in_job, BehaviorRecording, ChildReaper, Driver};
+
+/// A foreground Electron window that journals focus and leaked input while it
+/// fully occludes the background target.
+pub struct ForegroundSentinel {
+ journal_path: std::path::PathBuf,
+ target: TargetWindow,
+ _reaper: ChildReaper,
+ _user_data: tempfile::TempDir,
+}
+
+impl ForegroundSentinel {
+ pub fn launch(driver: &mut impl Driver) -> Self {
+ let electron = electron_fixture();
+ assert!(
+ electron.path.exists(),
+ "Electron sentinel fixture is missing at {}",
+ electron.path.display()
+ );
+ let user_data = tempfile::Builder::new()
+ .prefix("cua-e2e-sentinel-")
+ .tempdir()
+ .expect("create sentinel user-data directory");
+ let journal_path = user_data.path().join("sentinel-events.jsonl");
+ fs::write(&journal_path, "").expect("initialize sentinel event journal");
+ let cdp_port = TcpListener::bind(("127.0.0.1", 0))
+ .and_then(|listener| listener.local_addr())
+ .expect("allocate sentinel CDP port")
+ .port();
+ let mut command = Command::new(&electron.path);
+ command
+ .args(&electron.args)
+ .env("CUA_E2E_SENTINEL", "1")
+ .env("CUA_E2E_SENTINEL_JOURNAL", &journal_path)
+ .env("CUA_E2E_USER_DATA_DIR", user_data.path())
+ .env("CUA_ELECTRON_CDP_PORT", cdp_port.to_string())
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ let child = spawn_in_job(&mut command).expect("launch foreground sentinel");
+ let launched_pid = child.id();
+ let mut reaper = ChildReaper::new();
+ reaper.push(child);
+ let expected_title = format!("CuaTestHarness Sentinel [cdp={cdp_port}]");
+
+ let window_deadline = Instant::now() + Duration::from_secs(15);
+ let target = loop {
+ let windows = driver.call("list_windows", serde_json::json!({}));
+ if let Some(target) = windows.structured()["windows"]
+ .as_array()
+ .and_then(|windows| {
+ windows.iter().find_map(|window| {
+ let id = window["window_id"].as_u64()?;
+ let title = window["title"].as_str().unwrap_or("");
+ title.contains(&expected_title).then(|| TargetWindow {
+ pid: window["pid"].as_u64().unwrap_or(launched_pid as u64) as u32,
+ native_id: id,
+ })
+ })
+ })
+ {
+ assert_ne!(
+ target.pid, 0,
+ "foreground sentinel window has no process id"
+ );
+ break target;
+ }
+ assert!(
+ Instant::now() < window_deadline,
+ "foreground sentinel window did not appear"
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ };
+ reaper.track_pid(target.pid);
+
+ let focus_deadline = Instant::now() + Duration::from_secs(10);
+ if is_wayland_session() {
+ wait_for_journal(&journal_path, focus_deadline, r#""kind":"ready""#, "ready");
+ activate_native_foreground(driver, target);
+ // Electron may already be focused before its preload listener is ready.
+ // The compositor observation is the authoritative Wayland focus gate.
+ wait_for_native_focus_stable(target);
+ } else {
+ loop {
+ let journal = fs::read_to_string(&journal_path).unwrap_or_default();
+ if journal.contains(r#""kind":"ready""#) && journal.contains(r#""kind":"focus""#) {
+ break;
+ }
+ assert!(
+ Instant::now() < focus_deadline,
+ "foreground sentinel did not become ready and focused: {journal}"
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ }
+ activate_native_foreground(driver, target);
+ wait_for_native_focus_stable(target);
+ }
+ fs::write(&journal_path, "").expect("reset focused sentinel journal");
+
+ Self {
+ journal_path,
+ target,
+ _reaper: reaper,
+ _user_data: user_data,
+ }
+ }
+
+ pub fn observe(&self) -> (Vec<OracleKind>, Vec<String>) {
+ std::thread::sleep(Duration::from_millis(200));
+ let journal = match fs::read_to_string(&self.journal_path) {
+ Ok(journal) => journal,
+ Err(error) => {
+ return (
+ Vec::new(),
+ vec![format!(
+ "foreground sentinel journal could not be read: {error}"
+ )],
+ )
+ }
+ };
+ let mut passed = Vec::new();
+ let mut violations = Vec::new();
+ if journal.contains(r#""kind":"blur""#) {
+ violations.push("foreground sentinel lost focus".to_owned());
+ } else {
+ passed.push(OracleKind::Focus);
+ }
+ let leaked = ["keydown", "pointerdown", "wheel", "contextmenu"]
+ .into_iter()
+ .filter(|kind| journal.contains(&format!(r#""kind":"{kind}""#)))
+ .collect::<Vec<_>>();
+ if leaked.is_empty() {
+ passed.push(OracleKind::NoLeakedInput);
+ } else {
+ violations.push(format!(
+ "foreground sentinel received input events: {}",
+ leaked.join(", ")
+ ));
+ }
+ (passed, violations)
+ }
+
+ pub fn target(&self) -> TargetWindow {
+ self.target
+ }
+
+ /// Confirm the target is fully behind the ready foreground sentinel before
+ /// the behavioral video boundary is crossed.
+ pub fn assert_background_posture(&self, target: TargetWindow) -> Result<(), String> {
+ let observer = DesktopObserver::new(NativeObserver::new(), target);
+ let before = observer.snapshot().map_err(|error| error.to_string())?;
+ if before.target_z == crate::observer::TargetZ::BackgroundOccluded {
+ Ok(())
+ } else {
+ Err(format!(
+ "background target was not fully occluded before recording: {:?}",
+ before.target_z
+ ))
+ }
+ }
+
+ /// Run one background action while checking the native desktop and the
+ /// sentinel journal. The returned oracle list is suitable for a typed E2E
+ /// result; any unsupported observation or side effect is an error.
+ pub fn observe_background<R>(
+ &self,
+ target: TargetWindow,
+ action: impl FnOnce() -> R,
+ ) -> Result<(R, Vec<OracleKind>), String> {
+ self.observe_target(target, true, action)
+ }
+
+ /// Observe a desktop-wide action against the foreground sentinel itself.
+ /// Launch and cursor-overlay cells have no pre-existing background target,
+ /// so they verify desktop stability without the target-occlusion precondition.
+ pub fn observe_desktop<R>(
+ &self,
+ action: impl FnOnce() -> R,
+ ) -> Result<(R, Vec<OracleKind>), String> {
+ self.observe_target(self.target, false, action)
+ }
+
+ fn observe_target<R>(
+ &self,
+ target: TargetWindow,
+ require_occluded_target: bool,
+ action: impl FnOnce() -> R,
+ ) -> Result<(R, Vec<OracleKind>), String> {
+ let mut observer = DesktopObserver::new(NativeObserver::new(), target);
+ let before = observer.snapshot().map_err(|error| error.to_string())?;
+ if require_occluded_target
+ && before.target_z != crate::observer::TargetZ::BackgroundOccluded
+ {
+ return Err(format!(
+ "background target was not fully occluded before dispatch: {:?}",
+ before.target_z
+ ));
+ }
+ let mut native_oracles = vec![OracleKind::Focus, OracleKind::ZOrder];
+ if std::env::var("XDG_SESSION_TYPE")
+ .map(|session| !session.eq_ignore_ascii_case("wayland"))
+ .unwrap_or(true)
+ {
+ native_oracles.push(OracleKind::Cursor);
+ }
+ let (result, delta) = observer
+ .observe(&native_oracles, action)
+ .map_err(|error| error.to_string())?;
+ if require_occluded_target
+ && delta.before.target_z != crate::observer::TargetZ::BackgroundOccluded
+ {
+ return Err(format!(
+ "background target was not fully occluded at dispatch: {:?}",
+ delta.before.target_z
+ ));
+ }
+ delta
+ .ensure_supported()
+ .map_err(|error| error.to_string())?;
+
+ let mut passed = delta.passed().to_vec();
+ let mut violations = delta.violations().to_vec();
+ let (sentinel_passed, sentinel_violations) = self.observe();
+ passed.extend(sentinel_passed);
+ violations.extend(sentinel_violations);
+ passed.sort();
+ passed.dedup();
+ if violations.is_empty() {
+ Ok((result, passed))
+ } else {
+ Err(violations.join("; "))
+ }
+ }
+}
+
+fn wait_for_journal(path: &std::path::Path, deadline: Instant, marker: &str, state: &str) {
+ loop {
+ let journal = fs::read_to_string(path).unwrap_or_default();
+ if journal.contains(marker) {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "foreground sentinel did not become {state}: {journal}"
+ );
+ std::thread::sleep(Duration::from_millis(100));
+ }
+}
+
+fn is_wayland_session() -> bool {
+ cfg!(target_os = "linux")
+ && std::env::var("XDG_SESSION_TYPE")
+ .is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
+}
+
+#[cfg(any(target_os = "windows", target_os = "linux"))]
+fn activate_native_foreground(driver: &mut impl Driver, target: TargetWindow) {
+ let response = driver.call(
+ "bring_to_front",
+ serde_json::json!({
+ "pid": target.pid,
+ "window_id": target.native_id,
+ }),
+ );
+ assert!(
+ !response.is_error(),
+ "could not activate foreground sentinel: {}",
+ response.text()
+ );
+ #[cfg(target_os = "windows")]
+ physically_focus_windows_sentinel(target);
+}
+
+#[cfg(target_os = "windows")]
+fn physically_focus_windows_sentinel(target: TargetWindow) {
+ use windows::Win32::Foundation::{HWND, POINT, RECT};
+ use windows::Win32::UI::Input::KeyboardAndMouse::{
+ SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP,
+ MOUSEINPUT,
+ };
+ use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect, SetCursorPos};
+
+ let hwnd = HWND(target.native_id as *mut _);
+ let mut rect = RECT::default();
+ let mut original_cursor = POINT::default();
+ unsafe {
+ GetWindowRect(hwnd, &mut rect).expect("read foreground sentinel bounds");
+ GetCursorPos(&mut original_cursor).expect("read cursor before focusing sentinel");
+ }
+ let x = (rect.left + rect.right) / 2;
+ let y = (rect.top + rect.bottom) / 2;
+ assert!(
+ rect.right > rect.left && rect.bottom > rect.top,
+ "foreground sentinel has invalid bounds: {rect:?}"
+ );
+
+ let inputs = [
+ INPUT {
+ r#type: INPUT_MOUSE,
+ Anonymous: INPUT_0 {
+ mi: MOUSEINPUT {
+ dwFlags: MOUSEEVENTF_LEFTDOWN,
+ ..Default::default()
+ },
+ },
+ },
+ INPUT {
+ r#type: INPUT_MOUSE,
+ Anonymous: INPUT_0 {
+ mi: MOUSEINPUT {
+ dwFlags: MOUSEEVENTF_LEFTUP,
+ ..Default::default()
+ },
+ },
+ },
+ ];
+ unsafe {
+ SetCursorPos(x, y).expect("move cursor onto foreground sentinel");
+ let sent = SendInput(&inputs, std::mem::size_of::<INPUT>() as i32);
+ assert_eq!(sent, inputs.len() as u32, "click foreground sentinel");
+ SetCursorPos(original_cursor.x, original_cursor.y)
+ .expect("restore cursor after focusing sentinel");
+ }
+}
+
+#[cfg(not(any(target_os = "windows", target_os = "linux")))]
+fn activate_native_foreground(_driver: &mut impl Driver, _target: TargetWindow) {}
+
+#[cfg(any(target_os = "windows", target_os = "linux"))]
+fn wait_for_native_focus_stable(target: TargetWindow) {
+ use crate::observer::{ObserverBackend, TargetZ};
+
+ let backend = NativeObserver::new();
+ let deadline = Instant::now() + Duration::from_secs(3);
+ let mut stable_since = None;
+ loop {
+ let foreground = backend
+ .snapshot(target)
+ .map(|snapshot| snapshot.target_z == TargetZ::Foreground)
+ .unwrap_or(false);
+ if foreground {
+ let since = stable_since.get_or_insert_with(Instant::now);
+ if since.elapsed() >= Duration::from_millis(300) {
+ return;
+ }
+ } else {
+ stable_since = None;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "foreground sentinel did not remain natively focused"
+ );
+ std::thread::sleep(Duration::from_millis(20));
+ }
+}
+
+#[cfg(not(any(target_os = "windows", target_os = "linux")))]
+fn wait_for_native_focus_stable(_target: TargetWindow) {}
+
+pub fn run_with_background_oracles<D: Driver + BehaviorRecording, R>(
+ driver: &mut D,
+ target: TargetWindow,
+ action: impl FnOnce(&mut D) -> R,
+) -> Result<(R, Vec<OracleKind>), String> {
+ let sentinel = ForegroundSentinel::launch(driver);
+ sentinel.assert_background_posture(target)?;
+ driver.start_behavior_recording();
+ sentinel.observe_background(target, || action(driver))
+}
+
+struct ElectronFixture {
+ path: std::path::PathBuf,
+ args: Vec<&'static str>,
+}
+
+fn electron_fixture() -> ElectronFixture {
+ #[cfg(target_os = "windows")]
+ {
+ ElectronFixture {
+ path: harness_app("harness-electron", "CuaTestHarness.Electron.exe"),
+ args: vec![
+ "--no-sandbox",
+ "--disable-gpu",
+ "--force-renderer-accessibility",
+ ],
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ ElectronFixture {
+ path: harness_app(
+ "harness-electron",
+ "CuaTestHarness.Electron.app/Contents/MacOS/Electron",
+ ),
+ args: vec!["--force-renderer-accessibility"],
+ }
+ }
+ #[cfg(target_os = "linux")]
+ {
+ ElectronFixture {
+ path: harness_app("harness-electron", "CuaTestHarness.Electron"),
+ args: vec![
+ "--no-sandbox",
+ "--disable-gpu",
+ "--force-renderer-accessibility",
+ ],
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs
new file mode 100644
index 0000000000..3425190602
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/windows_setup.rs
@@ -0,0 +1,122 @@
+//! Windows hosted-runner desktop cleanup performed before behavioral capture.
+
+#[cfg(any(target_os = "windows", test))]
+fn is_hosted_runner_console(title: &str, class_name: &str) -> bool {
+ let title = title.to_ascii_lowercase();
+ let console_class = matches!(
+ class_name,
+ "ConsoleWindowClass" | "CASCADIA_HOSTING_WINDOW_CLASS"
+ );
+ console_class
+ && [
+ "hostedcomputeagent",
+ "hosted-compute-agent",
+ "runner.worker",
+ "github actions runner",
+ ]
+ .iter()
+ .any(|marker| title.contains(marker))
+}
+
+#[cfg(target_os = "windows")]
+pub fn minimize_hosted_runner_console() -> Result<&'static str, String> {
+ if std::env::var("RUNNER_ENVIRONMENT").as_deref() != Ok("github-hosted") {
+ return Ok("not_applicable");
+ }
+
+ use windows::core::BOOL;
+ use windows::Win32::Foundation::{HWND, LPARAM, TRUE};
+ use windows::Win32::UI::WindowsAndMessaging::{
+ EnumWindows, GetClassNameW, GetWindowTextLengthW, GetWindowTextW, IsIconic,
+ IsWindowVisible, ShowWindow, SW_MINIMIZE,
+ };
+
+ unsafe fn identity(hwnd: HWND) -> (String, String) {
+ let title_len = GetWindowTextLengthW(hwnd);
+ let mut title = vec![0u16; title_len.max(0) as usize + 1];
+ let copied = GetWindowTextW(hwnd, &mut title);
+ let title = String::from_utf16_lossy(&title[..copied.max(0) as usize]);
+ let mut class_name = [0u16; 256];
+ let class_len = GetClassNameW(hwnd, &mut class_name);
+ let class_name = String::from_utf16_lossy(&class_name[..class_len.max(0) as usize]);
+ (title, class_name)
+ }
+
+ unsafe extern "system" fn collect(hwnd: HWND, state: LPARAM) -> BOOL {
+ if IsWindowVisible(hwnd).as_bool() {
+ let (title, class_name) = identity(hwnd);
+ if is_hosted_runner_console(&title, &class_name) {
+ let windows = &mut *(state.0 as *mut Vec<HWND>);
+ windows.push(hwnd);
+ }
+ }
+ TRUE
+ }
+
+ let mut windows: Vec<HWND> = Vec::new();
+ unsafe {
+ let _ = EnumWindows(
+ Some(collect),
+ LPARAM(&mut windows as *mut Vec<HWND> as isize),
+ );
+ }
+ windows.sort_by_key(|hwnd| hwnd.0 as usize);
+ windows.dedup_by_key(|hwnd| hwnd.0 as usize);
+ if windows.is_empty() {
+ return Ok("not_present");
+ }
+
+ let mut changed = false;
+ for &hwnd in &windows {
+ if !unsafe { IsIconic(hwnd) }.as_bool() {
+ let _ = unsafe { ShowWindow(hwnd, SW_MINIMIZE) };
+ changed = true;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ if windows
+ .iter()
+ .any(|&hwnd| !unsafe { IsIconic(hwnd) }.as_bool())
+ {
+ return Err("HostedComputeAgent console did not enter the minimized state".to_owned());
+ }
+ Ok(if changed {
+ "minimized"
+ } else {
+ "already_minimized"
+ })
+}
+
+#[cfg(not(target_os = "windows"))]
+pub fn minimize_hosted_runner_console() -> Result<&'static str, String> {
+ Ok("not_applicable")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::is_hosted_runner_console;
+
+ #[test]
+ fn matches_only_named_runner_console_windows() {
+ assert!(is_hosted_runner_console(
+ "Administrator: HostedComputeAgent.exe",
+ "ConsoleWindowClass"
+ ));
+ assert!(is_hosted_runner_console(
+ "GitHub Actions Runner",
+ "CASCADIA_HOSTING_WINDOW_CLASS"
+ ));
+ assert!(is_hosted_runner_console(
+ r"C:\ProgramData\GitHub\HostedComputeAgent\hosted-compute-agent",
+ "ConsoleWindowClass"
+ ));
+ assert!(!is_hosted_runner_console(
+ "CuaTestHarness Sentinel",
+ "Chrome_WidgetWin_1"
+ ));
+ assert!(!is_hosted_runner_console(
+ "HostedComputeAgent status",
+ "Chrome_WidgetWin_1"
+ ));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index d867f4dfdc..1cb5d0abfb 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -730,17 +730,9 @@ pub async fn run_serve(
if let Some(sc) = result.structured_content {
result_obj["structuredContent"] = sc;
}
- let resp = if is_err {
- DaemonResponse::err(
- result.content.iter()
- .filter_map(|c| if let cua_driver_core::protocol::Content::Text { text, .. } = c { Some(text.as_str()) } else { None })
- .collect::<Vec<_>>()
- .join("\n"),
- 1
- )
- } else {
- DaemonResponse::ok(result_obj)
- };
+ // Preserve tool-level `isError` and structured
+ // content inside a successful daemon transport.
+ let resp = DaemonResponse::ok(result_obj);
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -1256,16 +1248,9 @@ pub async fn run_serve(
if let Some(sc) = result.structured_content {
result_obj["structuredContent"] = sc;
}
- let resp = if is_err {
- DaemonResponse::err(
- result.content.iter()
- .filter_map(|c| if let cua_driver_core::protocol::Content::Text { text, .. } = c { Some(text.as_str()) } else { None })
- .collect::<Vec<_>>().join("\n"),
- 1
- )
- } else {
- DaemonResponse::ok(result_obj)
- };
+ // Preserve tool-level `isError` and structured
+ // content inside a successful daemon transport.
+ let resp = DaemonResponse::ok(result_obj);
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/README.md b/libs/cua-driver/rust/crates/cua-driver/tests/README.md
index 58c97352fc..021cb339d8 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/README.md
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/README.md
@@ -1,9 +1,17 @@
# cua-driver Rust integration tests
Tests in this directory exercise the public driver interface. Headless protocol
-tests run by default; GUI and modality tests are marked `#[ignore]` because they
+tests run by default; harness E2E tests are marked `#[ignore]` because they
need staged harness apps and an interactive desktop.
+Start with the contributor overview in
+`../../../../docs/test-harnesses-guide.md`, then use the matrix below as the
+coverage map.
+
+The cross-OS ownership map is maintained in
+`../../../../docs/test-matrix.md`. Update that matrix when adding a harness,
+action, addressing mode, delivery mode, or OS-specific window-system case.
+
## Naming
| Prefix | Runs by default | Purpose |
@@ -11,8 +19,7 @@ need staged harness apps and an interactive desktop.
| `protocol_*_test.rs` | yes | MCP/CLI protocol and schema behavior |
| `schema_*_test.rs` | yes | Generated schema consistency |
| `harness_<toolkit>_test.rs` | no, `#[ignore]` | Toolkit-specific harness apps |
-| `modality_<area>[_<os>]_test.rs` | no, `#[ignore]` | Background input, capture, desktop scope |
-| `guard_*_test.rs` | usually ignored or self-skipping | UX guard and interactive desktop checks |
+| `desktop_scope_<os>_test.rs` | no, `#[ignore]` | Platform window/desktop scope contract |
## Harness Requirements
@@ -35,32 +42,45 @@ Staged outputs are read from `../../test-apps/harness-<name>/`.
The canonical cross-platform matrix is
`cross_platform_behavior_test.rs`. It runs the same external-state scenarios
-against Electron and Tauri on each supported host. CI and VM runners set
+against Electron and Tauri on each supported host, plus the native WKWebView
+host on macOS. CI and VM runners set
`CUA_TEST_DRIVER_BIN`, `CUA_TEST_APPS_ROOT`, and
`CUA_TEST_WORKSPACE_ROOT` when artifacts are built outside Cargo's default
workspace paths. They also set `CUA_TEST_REQUIRE_FIXTURES=1`, turning a missing
fixture into a failure instead of a silent skip.
-The canonical Windows and Linux runners also set
+Each matrix row declares its action, AX/PX targeting, foreground or background
+delivery, scope, driver route, external oracles, and required behavior in
+`cases.jsonl`. `results.jsonl` records the observed behavior and derived test
+status. The Rust reporter validates both files and renders `summary.md`.
+
+The canonical OS runners also set
`CUA_E2E_RECORDINGS_ROOT`. Every testkit `McpDriver` then records its full
desktop trajectory to a unique directory containing `recording.mp4`, cursor
samples, action JSON, per-turn screenshots, and a `trajectory.json` test-label
manifest. Windows and Linux require
FFmpeg; macOS uses the installed driver's ScreenCaptureKit backend. The runner
-validates each MP4 with `ffprobe` before reporting success.
+validates each MP4 with `ffprobe` before reporting success. A separate Rust
+preflight verifies the desktop, fixture, AX tree, screenshot, and video
+lifecycle once before behavioral cells run.
## Running
```bash
cargo test -p cua-driver --test protocol_handshake_test
cargo test -p cua-driver --test harness_appkit_test -- --ignored --nocapture
-cargo test -p cua-driver --test modality_desktop_scope_macos_test -- --ignored --nocapture
+cargo test -p cua-driver --test desktop_scope_macos_test -- --ignored --nocapture
```
-Windows Rust run-all uses
-`../../../../tests/runners/windows/run-all.ps1`. It builds repo-local fixtures
-and runs the default, guard, harness, and modality suites. It intentionally
-excludes optional external-app suites.
+The canonical Windows E2E entrypoint is
+`scripts/ci/windows/run-rust-e2e.ps1 -RequireGui`.
+It runs the complete Rust harness matrix; internal lane selectors are retained
+only for focused diagnosis. Optional
+external-app suites remain separate.
+
+The canonical macOS E2E entrypoint is
+`scripts/ci/macos/run-rust-e2e.sh`. It requires a logged-in user session and an
+installed driver with Accessibility and Screen Recording grants.
Legacy Windows Sandbox runs use
`../../../../tests/runners/windows-sandbox/run-tests-in-sandbox.ps1`, which
@@ -68,21 +88,17 @@ builds selected Windows harness apps and maps them into the sandbox. The current
Windows GUI validation path should use a real user desktop session through RDP
or an interactive scheduled task.
-Windows GUI modality tests require a user desktop where the focus sentinel can
-become the foreground window. SSH-launched commands start in Session 0 and
+Windows GUI tests require a usable interactive desktop. SSH-launched commands start in Session 0 and
cannot drive the user's desktop directly; launch GUI tests through an
interactive scheduled task (`/IT`) or equivalent so they run in the logged-on
user session.
-The Windows probe distinguishes two no-foreground states:
-
-- `input_desktop=Default, foreground_hwnd=0`: the desktop is usable but idle.
- Tests now launch `focus-monitor-win` and require that sentinel HWND to become
- foreground before assertions start.
-- `input_desktop` is not `Default` or cannot be opened: the session is usually
- locked/disconnected, for example after an RDP client drops. Reconnect, use
- `tscon /dest:console` on a disposable GUI VM, or boot the VM into an unlocked
- console session before running ignored GUI tests.
+The testkit's native `DesktopObserver` records foreground-window, z-order,
+cursor, and leaked-input state around rows that promise no desktop side effects.
+If the input desktop is not `Default` or cannot be opened, the session is
+usually locked or disconnected. Reconnect, use `tscon /dest:console` on a
+disposable GUI VM, or boot the VM into an unlocked console session before
+running ignored GUI tests.
Set `CUA_REQUIRE_GUI=1` on dedicated GUI runners to turn these desktop
self-skips into hard failures with the full desktop-state diagnostic.
@@ -91,11 +107,11 @@ The repository-level runners are the preferred entrypoints for the canonical
matrix:
```bash
-scripts/ci/linux/run-rust-e2e.sh --suite shared
+scripts/ci/linux/run-rust-e2e.sh
```
```powershell
-.\scripts\ci\windows\run-rust-e2e.ps1 -Suite shared -RequireGui
+.\scripts\ci\windows\run-rust-e2e.ps1 -RequireGui
```
## Optional External Apps
@@ -107,5 +123,7 @@ desktop state outside the repo-local fixtures:
- `harness_libreoffice_test.rs`: Windows LibreOffice Writer/Calc. Requires
LibreOffice installed, or `LO_SWRITER_EXE` / `LO_SCALC_EXE` pointing at the
executables.
-- `modality_launch_focus_macos_test.rs`: macOS Calculator/TextEdit launch focus
+- `installed_app_launch_macos_test.rs`: macOS Calculator/TextEdit launch focus
checks. Requires a logged-in GUI session and usable System Events scripting.
+- `installed_app_textedit_macos_test.rs`: real TextEdit background AX write and
+ verification. Requires a logged-in GUI session and Accessibility permission.
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_capture_mode_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
similarity index 55%
rename from libs/cua-driver/rust/crates/cua-driver/tests/modality_capture_mode_test.rs
rename to libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
index feec766cbc..d5d8b64a20 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_capture_mode_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/capture_contract_test.rs
@@ -1,4 +1,4 @@
-//! modality_capture_mode_test — the get_window_state **perception** contract,
+//! `get_window_state` perception contract,
//! asserted on each platform's native controlled-harness app.
//!
//! get_window_state is perception-mode-agnostic now: it ALWAYS returns BOTH the
@@ -11,36 +11,66 @@
//! * `include_screenshot:false` → tree present, NO `image` (the cheap path).
//! * `capture_mode:"vision"` (deprecated) → IGNORED; still returns both.
//!
-//! Caveats handled as graceful skips (these are `#[ignore]` interactive tests,
-//! consistent with the rest of the harness suite):
-//! * The screenshot needs a screen-capture grant (Screen Recording on macOS).
-//! Without it the driver returns a tree but no PNG, so the image assertions
-//! skip-with-note rather than false-fail.
-//! * The tree needs the platform accessibility grant (TCC on macOS, AT-SPI bus
-//! on Linux). An empty tree skips the tree assertion.
-//!
//! Run explicitly:
-//! cargo test -p cua-driver --test modality_capture_mode_test -- --ignored --nocapture --test-threads=1
+//! cargo test -p cua-driver --test capture_contract_test -- --ignored --nocapture --test-threads=1
#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
+use cua_driver_testkit::e2e::{
+ execute_case, native_readonly_case, recording_evidence, DriverRoute, Evidence, Observation,
+ OracleKind, Targeting,
+};
+#[cfg(target_os = "windows")]
+use cua_driver_testkit::e2e::{CaseSpec, Delivery, Scope};
+#[cfg(target_os = "windows")]
+use cua_driver_testkit::observer::TargetWindow;
+#[cfg(target_os = "windows")]
+use cua_driver_testkit::sentinel::ForegroundSentinel;
use cua_driver_testkit::{harness_app, Driver, McpDriver, ToolResponse};
/// The aid every harness exposes on its increment button — the tree marker
/// (WPF AutomationId / AppKit AX identifier / GTK3 AT-SPI accessible name).
const TREE_MARKER: &str = "btn-increment";
+fn strict() -> bool {
+ std::env::var_os("CUA_TEST_REQUIRE_FIXTURES").is_some()
+}
+
#[cfg(target_os = "macos")]
-fn spawn_driver() -> Option<McpDriver> {
- McpDriver::spawn_macos_daemon_proxy()
+fn spawn_driver(label: &str) -> Option<McpDriver> {
+ McpDriver::spawn_macos_daemon_proxy_named(label)
}
#[cfg(not(target_os = "macos"))]
-fn spawn_driver() -> Option<McpDriver> {
- McpDriver::spawn()
+fn spawn_driver(label: &str) -> Option<McpDriver> {
+ McpDriver::spawn_named(label)
+}
+
+fn test_driver(label: &str) -> Option<McpDriver> {
+ let driver = spawn_driver(label);
+ assert!(
+ driver.is_some() || !strict(),
+ "required source-built driver did not start"
+ );
+ driver
+}
+
+fn capture_toolkit() -> &'static str {
+ #[cfg(target_os = "windows")]
+ {
+ "wpf"
+ }
+ #[cfg(target_os = "macos")]
+ {
+ "appkit"
+ }
+ #[cfg(target_os = "linux")]
+ {
+ "gtk3"
+ }
}
/// Does the response carry a screenshot? Checks both the MCP `image` content
@@ -171,18 +201,24 @@ fn launch_new_instance(
title: &str,
) -> Option<(u32, u64)> {
if !exe.exists() {
- eprintln!("[capture_mode] harness not built ({exe:?}) — skipping");
+ if strict() {
+ panic!("required capture harness is missing: {exe:?}");
+ }
+ eprintln!("[capture] optional harness not built: {exe:?}");
return None;
}
let before = harness_pids(driver, title);
- driver
- .reaper()
- .spawn(
- Command::new(exe)
- .stdout(Stdio::null())
- .stderr(Stdio::null()),
- )
- .ok()?;
+ let spawned = driver.reaper().spawn(
+ Command::new(exe)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null()),
+ );
+ if let Err(error) = spawned {
+ if strict() {
+ panic!("failed to launch required capture harness {exe:?}: {error}");
+ }
+ return None;
+ }
resolve_new_window(driver, title, &before)
}
@@ -227,47 +263,65 @@ fn resolve_new_window(
}
std::thread::sleep(Duration::from_millis(400));
}
- eprintln!("[capture_mode] new harness window {title:?} never appeared — is a graphical session available? skipping");
+ if strict() {
+ panic!("required capture harness window {title:?} never appeared");
+ }
+ eprintln!("[capture] optional harness window {title:?} never appeared");
None
}
+fn run_capture_case(
+ action: &str,
+ oracles: Vec<OracleKind>,
+ test: impl FnOnce(u32, u64, &mut McpDriver),
+) {
+ let case = native_readonly_case(
+ capture_toolkit(),
+ action,
+ Targeting::NotApplicable,
+ DriverRoute::WindowState,
+ oracles.clone(),
+ );
+ let cell_id = case.cell_id.clone();
+ execute_case(case, |evidence| {
+ let mut driver = test_driver(&cell_id).expect("required capture driver did not start");
+ *evidence = recording_evidence(driver.recording_dir());
+ let (pid, wid) = launch(&mut driver).expect("required capture harness did not launch");
+ driver.start_behavior_recording();
+ test(pid, wid, &mut driver);
+ Observation::delivered(oracles, Evidence::default())
+ });
+}
+
// ── tests ───────────────────────────────────────────────────────────────────────
/// DEFAULT: get_window_state returns BOTH the tree AND a screenshot — grounding
-/// on both is the whole point. Each half is asserted only when its OS grant is
-/// available (accessibility for the tree, screen-recording for the image), so a
-/// missing grant skips-with-note rather than false-failing.
+/// on both is the whole point.
#[test]
#[ignore]
fn default_returns_tree_and_screenshot() {
- let Some(mut driver) = spawn_driver() else {
- return;
- };
- let Some((pid, wid)) = launch(&mut driver) else {
- return;
- };
-
- let resp = snapshot_settled_default(&mut driver, pid, wid);
- assert!(
- !resp.is_error(),
- "get_window_state(default) errored: {}",
- resp.text()
- );
+ run_capture_case(
+ "tree_and_screenshot",
+ vec![OracleKind::AxState, OracleKind::Pixels],
+ |pid, wid, driver| {
+ let resp = snapshot_settled_default(driver, pid, wid);
+ assert!(
+ !resp.is_error(),
+ "get_window_state(default) errored: {}",
+ resp.text()
+ );
- let tree = tree_has_marker(&resp);
- let img = has_image(&resp);
- assert!(
- tree || img,
- "default returned neither tree nor image — both grants missing? {}",
- resp.text().chars().take(160).collect::<String>()
+ assert!(
+ tree_has_marker(&resp),
+ "default response is missing the required tree marker: {}",
+ resp.text().chars().take(160).collect::<String>()
+ );
+ assert!(
+ has_image(&resp),
+ "default response is missing its screenshot"
+ );
+ },
);
- // When BOTH grants are present, BOTH must be returned (the contract).
- if tree && !img {
- eprintln!("[capture_mode] default: tree present, no image (screen-capture grant likely missing) — partial check");
- } else if img && !tree {
- eprintln!("[capture_mode] default: image present, no tree (accessibility grant likely missing) — partial check");
- }
- println!("✅ default: tree={tree} image={img} (both expected when grants present)");
}
/// `include_screenshot:false` is the perf opt-out: tree present, NO image. This
@@ -275,30 +329,28 @@ fn default_returns_tree_and_screenshot() {
#[test]
#[ignore]
fn include_screenshot_false_returns_tree_only() {
- let Some(mut driver) = spawn_driver() else {
- return;
- };
- let Some((pid, wid)) = launch(&mut driver) else {
- return;
- };
+ run_capture_case(
+ "tree_only",
+ vec![OracleKind::AxState],
+ |pid, wid, driver| {
+ let resp = snapshot_settled_tree_only(driver, pid, wid);
+ assert!(
+ !resp.is_error(),
+ "get_window_state(include_screenshot:false) errored: {}",
+ resp.text()
+ );
- let resp = snapshot_settled_tree_only(&mut driver, pid, wid);
- assert!(
- !resp.is_error(),
- "get_window_state(include_screenshot:false) errored: {}",
- resp.text()
+ assert!(
+ tree_has_marker(&resp),
+ "tree-only response is missing {TREE_MARKER:?}"
+ );
+ assert!(
+ !has_image(&resp),
+ "include_screenshot:false must NOT return an image content entry: {}",
+ resp.text().chars().take(160).collect::<String>()
+ );
+ },
);
-
- if !tree_has_marker(&resp) {
- eprintln!("[capture_mode] tree-only: no {TREE_MARKER:?} — accessibility grant likely missing; skipping");
- return;
- }
- assert!(
- !has_image(&resp),
- "include_screenshot:false must NOT return an image content entry: {}",
- resp.text().chars().take(160).collect::<String>()
- );
- println!("✅ include_screenshot:false: tree present ({TREE_MARKER}), no image");
}
/// `capture_mode` is DEPRECATED and ignored: passing `vision` (which used to
@@ -306,33 +358,104 @@ fn include_screenshot_false_returns_tree_only() {
#[test]
#[ignore]
fn deprecated_capture_mode_is_ignored() {
- let Some(mut driver) = spawn_driver() else {
- return;
- };
- let Some((pid, wid)) = launch(&mut driver) else {
- return;
- };
+ run_capture_case(
+ "deprecated_mode_ignored",
+ vec![OracleKind::AxState, OracleKind::Pixels],
+ |pid, wid, driver| {
+ let resp = snapshot_settled(driver, pid, wid, "vision");
+ assert!(
+ !resp.is_error(),
+ "get_window_state(capture_mode=vision) errored: {}",
+ resp.text()
+ );
- let resp = snapshot_settled(&mut driver, pid, wid, "vision");
- assert!(
- !resp.is_error(),
- "get_window_state(capture_mode=vision) errored: {}",
- resp.text()
+ assert!(
+ tree_has_marker(&resp),
+ "deprecated capture_mode=vision suppressed the tree"
+ );
+ assert!(
+ has_image(&resp),
+ "deprecated capture_mode=vision suppressed the screenshot"
+ );
+ },
);
+}
- // The legacy "vision" value must NOT suppress the tree anymore.
- if has_image(&resp) && tree_has_marker(&resp) {
- println!("✅ capture_mode=vision ignored: BOTH tree and image returned");
- return;
- }
- // Tolerate a missing grant, but the deprecated arg must never make the
- // present half disappear: if the tree marker shows, that already proves
- // "vision" didn't suppress it.
- if tree_has_marker(&resp) {
- println!("✅ capture_mode=vision ignored: tree still present (image grant may be missing)");
- } else {
- eprintln!(
- "[capture_mode] vision: no tree marker — accessibility grant likely missing; skipping"
+/// Capturing an occluded background window is a read-only operation: it must
+/// return pixels without disturbing the user's foreground desktop.
+#[cfg(target_os = "windows")]
+#[test]
+#[ignore]
+fn background_screenshot_preserves_desktop() {
+ let case = CaseSpec::delivered(
+ "windows-wpf-screenshot-px-background",
+ "wpf",
+ "wpf",
+ "screenshot",
+ Targeting::Px,
+ Delivery::Background,
+ Scope::Window,
+ DriverRoute::WindowsPrintWindow,
+ vec![
+ OracleKind::Pixels,
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::Cursor,
+ OracleKind::NoLeakedInput,
+ ],
+ );
+ execute_case(case, |evidence| {
+ let mut driver = McpDriver::spawn_named("windows-wpf-screenshot-px-background")
+ .expect("required source-built driver did not start");
+ *evidence = recording_evidence(driver.recording_dir());
+ let (pid, wid) = launch(&mut driver).expect("required WPF capture harness did not start");
+ let sentinel = ForegroundSentinel::launch(&mut driver);
+ sentinel
+ .assert_background_posture(TargetWindow {
+ pid,
+ native_id: wid,
+ })
+ .expect("establish capture background posture before recording");
+ driver.start_behavior_recording();
+ let (response, mut passed) = sentinel
+ .observe_background(
+ TargetWindow {
+ pid,
+ native_id: wid,
+ },
+ || {
+ driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": wid,
+ "capture_mode": "vision"
+ }),
+ )
+ },
+ )
+ .unwrap_or_else(|error| panic!("background screenshot disturbed the desktop: {error}"));
+ assert!(
+ !response.is_error(),
+ "background screenshot failed: {}",
+ response.text()
);
- }
+ assert!(
+ has_image(&response),
+ "background screenshot returned no image"
+ );
+ for required in [
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::Cursor,
+ OracleKind::NoLeakedInput,
+ ] {
+ assert!(
+ passed.contains(&required),
+ "background screenshot omitted required {required:?} oracle"
+ );
+ }
+ passed.push(OracleKind::Pixels);
+ Observation::delivered(passed, Evidence::default())
+ });
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
index 8865d1edc3..49c617b949 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs
@@ -3,8 +3,9 @@
//! These are source-owned Rust tests, not a copy of a partner test runner. The
//! shared web fixture is loaded by Electron and Tauri on every supported OS;
//! Windows also has WebView2 coverage in `harness_web_test.rs`. Assertions read
-//! the fixture's mutated application state from a fresh accessibility snapshot.
-//! A successful driver response alone is never sufficient.
+//! mutated application state from a fixture-owned loopback journal, independently
+//! of the driver's accessibility snapshot. A successful response alone is never
+//! sufficient.
//!
//! Run after building the shared fixtures:
//!
@@ -16,8 +17,6 @@
#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
use std::any::Any;
-use std::fs::OpenOptions;
-use std::io::Write;
use std::panic::{self, AssertUnwindSafe};
use std::path::PathBuf;
use std::process::{Command, Stdio};
@@ -25,7 +24,16 @@ use std::thread;
use std::time::{Duration, Instant};
use cua_driver_testkit::ax::{element_index_by_id, element_index_containing};
-use cua_driver_testkit::{harness_app, spawn_in_job, Driver, McpDriver, ToolResponse};
+use cua_driver_testkit::e2e::{
+ recording_evidence, shared_web_route, write_declaration_from_env, write_result_from_env,
+ CaseResult, CaseSpec, Delivery, Evidence, Observation, OracleKind, RefusalCode, Scope,
+ Targeting,
+};
+use cua_driver_testkit::observer::TargetWindow;
+use cua_driver_testkit::sentinel::ForegroundSentinel;
+use cua_driver_testkit::{
+ harness_app, spawn_in_job, Driver, FixtureJournal, McpDriver, ToolResponse,
+};
struct HostSpec {
name: &'static str,
@@ -77,6 +85,15 @@ fn host_specs() -> Vec<HostSpec> {
args: Vec::new(),
title: "CuaTestHarness Tauri",
});
+ hosts.push(HostSpec {
+ name: "wkwebview",
+ path: harness_app(
+ "harness-wkwebview",
+ "CuaTestHarness.WKWebView.app/Contents/MacOS/CuaTestHarness.WKWebView",
+ ),
+ args: Vec::new(),
+ title: "CuaTestHarness WKWebView",
+ });
}
#[cfg(target_os = "linux")]
@@ -91,18 +108,22 @@ fn host_specs() -> Vec<HostSpec> {
],
title: "CuaTestHarness Electron",
});
- // WebKitGTK's AT-SPI tree is exposed through a separate WebProcess;
- // the Rust walker handles that reference shape, but headless Xvfb
- // still does not provide a reliable input-delivery contract for the
- // Tauri renderer. Keep this strict lane opt-in until that renderer
- // path is fixed, while the Electron matrix remains deterministic.
- if std::env::var_os("CUA_INCLUDE_TAURI_LINUX").is_some() {
- hosts.push(HostSpec {
- name: "tauri",
- path: harness_app("harness-tauri", "CuaTestHarness.Tauri"),
- args: Vec::new(),
- title: "CuaTestHarness Tauri",
- });
+ hosts.push(HostSpec {
+ name: "tauri",
+ path: harness_app("harness-tauri", "CuaTestHarness.Tauri"),
+ args: Vec::new(),
+ title: "CuaTestHarness Tauri",
+ });
+ }
+
+ if let Ok(filter) = std::env::var("CUA_E2E_HARNESS_FILTER") {
+ let selected = filter
+ .split(',')
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .collect::<std::collections::HashSet<_>>();
+ if !selected.is_empty() {
+ hosts.retain(|host| selected.contains(host.name));
}
}
@@ -121,83 +142,71 @@ fn panic_message(payload: &Box<dyn Any + Send>) -> String {
.unwrap_or_else(|| "test panicked without a string payload".to_owned())
}
-fn escape_markdown(value: &str) -> String {
- value
- .replace('|', "\\|")
- .replace('\r', "")
- .replace('\n', " ")
-}
-
-fn append_result_line(path: &str, line: &str) {
- let Some(parent) = std::path::Path::new(path).parent() else {
- return;
- };
- let _ = std::fs::create_dir_all(parent);
- if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
- let _ = writeln!(file, "{line}");
- }
-}
-
-fn record_result(scenario: &str, host: &str, status: &str, message: &str, duration: Duration) {
- let message = escape_markdown(message);
- if let Ok(path) = std::env::var("CUA_E2E_RESULTS_FILE") {
- let line = serde_json::json!({
- "schema": "cua-e2e-result/v1",
- "platform": std::env::consts::OS,
- "host": host,
- "scenario": scenario,
- "status": status,
- "message": message,
- "duration_ms": duration.as_millis(),
- });
- append_result_line(&path, &line.to_string());
- }
- if let Ok(path) = std::env::var("CUA_E2E_SUMMARY_FILE") {
- append_result_line(
- &path,
- &format!(
- "| {} | {} | {} | {} | {} ms | {} |",
- std::env::consts::OS,
- escape_markdown(host),
- escape_markdown(scenario),
- status,
- duration.as_millis(),
- if message.is_empty() { "-" } else { &message },
- ),
- );
- }
-}
-
-fn run_host_case<F>(scenario: &str, spec: &HostSpec, test: F) -> Option<Box<dyn Any + Send>>
+fn run_host_case_with_outcome<F>(
+ case: CaseSpec,
+ spec: &HostSpec,
+ test: F,
+) -> Option<Box<dyn Any + Send>>
where
- F: FnOnce(Fixture),
+ F: FnOnce(&mut Fixture) -> Observation,
{
+ write_declaration_from_env(&case).expect("write E2E case declaration");
let started = Instant::now();
+ let mut evidence = Evidence::default();
+ let delivery = case.delivery;
let outcome = panic::catch_unwind(AssertUnwindSafe(|| {
- let Some(fixture) = launch_host(spec, scenario) else {
- return false;
+ let mut fixture = launch_host_with_evidence(spec, &case.cell_id, &mut evidence);
+ let sentinel = if delivery == Delivery::Background {
+ Some(ForegroundSentinel::launch(&mut fixture.driver))
+ } else {
+ None
};
- test(fixture);
- true
+ if let Some(sentinel) = &sentinel {
+ sentinel
+ .assert_background_posture(TargetWindow {
+ pid: fixture.pid,
+ native_id: fixture.wid,
+ })
+ .expect("establish background posture before recording");
+ }
+ fixture.driver.start_behavior_recording();
+ let mut observation = if delivery == Delivery::Background {
+ let sentinel = sentinel.as_ref().expect("background sentinel");
+ let (mut observation, passed) = sentinel
+ .observe_background(
+ TargetWindow {
+ pid: fixture.pid,
+ native_id: fixture.wid,
+ },
+ || test(&mut fixture),
+ )
+ .expect("observe background desktop side effects");
+ observation.passed_oracles.extend(passed);
+ observation
+ } else {
+ test(&mut fixture)
+ };
+ drop(sentinel);
+ observation.evidence = evidence.clone();
+ observation
}));
match outcome {
- Ok(true) => {
- record_result(scenario, spec.name, "PASS", "", started.elapsed());
- None
- }
- Ok(false) => {
- record_result(
- scenario,
- spec.name,
- "SKIP",
- "fixture unavailable",
- started.elapsed(),
- );
+ Ok(observation) => {
+ let result = CaseResult::evaluate(case, observation, started.elapsed());
+ write_result_from_env(&result).expect("write E2E case result");
+ if result.test_status == cua_driver_testkit::e2e::TestStatus::Fail {
+ return Some(Box::new(result.message));
+ }
None
}
Err(payload) => {
let message = panic_message(&payload);
- record_result(scenario, spec.name, "FAIL", &message, started.elapsed());
+ let result = CaseResult::evaluate(
+ case,
+ Observation::error(&message, evidence),
+ started.elapsed(),
+ );
+ write_result_from_env(&result).expect("write failed E2E case result");
Some(payload)
}
}
@@ -212,7 +221,7 @@ fn resume_first_failure(failure: Option<Box<dyn Any + Send>>) {
fn spawn_driver(recording_label: &str) -> Option<McpDriver> {
#[cfg(target_os = "macos")]
{
- return McpDriver::spawn_macos_daemon_proxy_named(recording_label);
+ McpDriver::spawn_macos_daemon_proxy_named(recording_label)
}
#[cfg(not(target_os = "macos"))]
{
@@ -227,38 +236,48 @@ struct Fixture {
window_x: f64,
window_y: f64,
name: &'static str,
+ journal: FixtureJournal,
}
-fn launch_host(spec: &HostSpec, scenario: &str) -> Option<Fixture> {
+fn evidence_for_driver(driver: &McpDriver) -> Evidence {
+ recording_evidence(driver.recording_dir())
+}
+
+fn allocate_loopback_port() -> u16 {
+ let listener =
+ std::net::TcpListener::bind(("127.0.0.1", 0)).expect("allocate an ephemeral fixture port");
+ listener.local_addr().expect("read fixture port").port()
+}
+
+fn launch_host_with_evidence(spec: &HostSpec, scenario: &str, evidence: &mut Evidence) -> Fixture {
if !spec.path.exists() {
- if std::env::var_os("CUA_TEST_REQUIRE_FIXTURES").is_some() {
- panic!(
- "{} fixture is required but was not staged at {:?}",
- spec.name, spec.path
- );
- }
- eprintln!(
- "[{}] fixture not staged at {:?}; skipping",
+ panic!(
+ "{} fixture is required but was not staged at {:?}",
spec.name, spec.path
);
- return None;
}
- let recording_label = format!("{scenario}-{}", spec.name);
- let Some(mut driver) = spawn_driver(&recording_label) else {
- if std::env::var_os("CUA_TEST_REQUIRE_FIXTURES").is_some() {
- panic!(
- "cua-driver could not be started for the required {} fixture",
- spec.name
- );
- }
- return None;
- };
+ let recording_label = scenario.to_owned();
+ let mut driver = spawn_driver(&recording_label).unwrap_or_else(|| {
+ panic!(
+ "cua-driver could not be started for the required {} fixture",
+ spec.name
+ )
+ });
+ *evidence = evidence_for_driver(&driver);
+ let journal = FixtureJournal::start();
let mut command = Command::new(&spec.path);
command
.args(&spec.args)
- .stdout(Stdio::null())
- .stderr(Stdio::null());
+ .env("CUA_E2E_FIXTURE_JOURNAL_URL", journal.url())
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit());
+ if spec.name == "electron" {
+ command.env(
+ "CUA_ELECTRON_CDP_PORT",
+ allocate_loopback_port().to_string(),
+ );
+ }
let before_windows = driver
.call("list_windows", serde_json::json!({}))
.structured()["windows"]
@@ -270,7 +289,8 @@ fn launch_host(spec: &HostSpec, scenario: &str) -> Option<Fixture> {
.collect::<std::collections::HashSet<_>>()
})
.unwrap_or_default();
- let child = spawn_in_job(&mut command).ok()?;
+ let child = spawn_in_job(&mut command)
+ .unwrap_or_else(|error| panic!("failed to launch {} fixture: {error}", spec.name));
let pid = child.id();
driver.reaper().push(child);
@@ -296,20 +316,24 @@ fn launch_host(spec: &HostSpec, scenario: &str) -> Option<Fixture> {
window_x: bounds["x"].as_f64().unwrap_or(0.0),
window_y: bounds["y"].as_f64().unwrap_or(0.0),
name: spec.name,
+ journal,
};
let ax_deadline = Instant::now() + Duration::from_secs(10);
+ let mut last_tree = String::new();
while Instant::now() < ax_deadline {
- if snapshot(&mut fixture)
- .tree_text()
- .contains("WEB_HARNESS_MARKER_v1")
+ let state = snapshot(&mut fixture);
+ last_tree.clear();
+ last_tree.push_str(state.tree_text());
+ if last_tree.contains("WEB_HARNESS_MARKER_v1")
+ && fixture.journal.contains("WEB_HARNESS_MARKER_v1")
{
- return Some(fixture);
+ return fixture;
}
thread::sleep(Duration::from_millis(250));
}
panic!(
- "{} fixture accessibility tree did not become ready",
- spec.name
+ "{} fixture accessibility tree did not become ready; last tree:\n{}",
+ spec.name, last_tree
);
}
}
@@ -366,7 +390,7 @@ fn screenshot_scale(state: &ToolResponse) -> f64 {
})
.and_then(|window| window["frame"]["w"].as_f64())
.unwrap_or(0.0);
- if window_width > 0.0 && width > window_width {
+ if window_width > 0.0 && width > 0.0 {
width / window_width
} else {
1.0
@@ -375,18 +399,27 @@ fn screenshot_scale(state: &ToolResponse) -> f64 {
fn require_element(snapshot: &ToolResponse, id: &str) -> u64 {
// Some WebKit/Chromium AX adapters preserve the DOM id as an annotation
- // (`(calc-1 1)`) instead of emitting the common `id=...` form. Searching
- // the visible label fallback handles adapters that omit both forms.
+ // instead of emitting the common `id=...` form. Searching the visible
+ // label fallback handles adapters that omit both forms.
let visible_label = match id {
- "calc-1" | "calc-2" | "calc-4" | "calc-plus" | "calc-equals" | "editor-document"
- | "editor-save" | "scroll-tall" => id,
+ "editor-document" | "editor-save" | "scroll-tall" => id,
+ "border-click-target" => "Click target (left / right / double)",
+ "txt-input" => "type here",
"keyboard-input" => "keyboard-input",
"drag-source" => "Drag source",
"drop-target" => "Drop target",
"btn-open-child-window" => "Open child window",
_ => id,
};
+ let platform_id = match id {
+ // Chromium exposes the DOM id through AX, while data-cua-id is the
+ // canonical identifier shared with the native harnesses.
+ "border-click-target" => "click-target",
+ _ => id,
+ };
element_index_by_id(snapshot.tree_text(), id)
+ .or_else(|| element_index_by_id(snapshot.tree_text(), platform_id))
+ .or_else(|| element_index_containing(snapshot.tree_text(), id))
.or_else(|| element_index_containing(snapshot.tree_text(), visible_label))
.unwrap_or_else(|| {
panic!(
@@ -413,352 +446,622 @@ fn element_center(snapshot: &ToolResponse, element_index: u64) -> (f64, f64) {
)
}
-fn assert_tree_contains(fixture: &mut Fixture, marker: &str) {
- let post = snapshot(fixture);
+fn assert_fixture_contains(fixture: &Fixture, marker: &str) {
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ if fixture.journal.contains(marker) {
+ return;
+ }
+ if Instant::now() >= deadline {
+ panic!(
+ "{}: fixture journal did not reach {marker:?}: {}",
+ fixture.name,
+ fixture.journal.snapshot()
+ );
+ }
+ thread::sleep(Duration::from_millis(100));
+ }
+}
+
+fn action_target_args(
+ fixture: &Fixture,
+ state: &ToolResponse,
+ id: &str,
+ addressing: &str,
+ delivery: &str,
+) -> serde_json::Value {
+ let index = require_element(state, id);
+ let mut args = serde_json::json!({
+ "pid": fixture.pid as i64,
+ "window_id": fixture.wid,
+ "delivery_mode": delivery,
+ });
+ let object = args.as_object_mut().expect("action arguments object");
+ if addressing == "ax" {
+ object.insert("element_index".to_owned(), serde_json::json!(index));
+ } else {
+ let origin = window_origin(fixture, state);
+ let scale = screenshot_scale(state);
+ let (x, y) = element_center(state, index);
+ let local_x = (x - origin.0) * scale;
+ let local_y = (y - origin.1) * scale;
+ let width = state.structured()["screenshot_width"]
+ .as_f64()
+ .expect("PX action requires screenshot_width");
+ let height = state.structured()["screenshot_height"]
+ .as_f64()
+ .expect("PX action requires screenshot_height");
+ eprintln!(
+ "[shared-px] {} target={id} screen=({x:.1},{y:.1}) origin=({:.1},{:.1}) scale={scale:.3} local=({local_x:.1},{local_y:.1}) capture=({width:.1}x{height:.1})",
+ fixture.name, origin.0, origin.1
+ );
+ assert!(
+ local_x >= 0.0 && local_x < width && local_y >= 0.0 && local_y < height,
+ "{}: PX target {id:?} center ({local_x:.1}, {local_y:.1}) is outside the captured window ({width:.1}x{height:.1}); fix the harness layout",
+ fixture.name
+ );
+ object.insert("x".to_owned(), serde_json::json!(local_x));
+ object.insert("y".to_owned(), serde_json::json!(local_y));
+ }
+ args
+}
+
+fn run_pointer_action(
+ fixture: &mut Fixture,
+ tool: &str,
+ addressing: &str,
+ delivery: &str,
+ expected_marker: &str,
+) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let args = action_target_args(fixture, &pre, "border-click-target", addressing, delivery);
+ let response = fixture.driver.call(tool, args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: {tool} {addressing}/{delivery} failed: {}",
+ fixture.name,
+ response.text()
+ );
+ assert_fixture_contains(fixture, expected_marker);
+ delivered_observation()
+}
+
+fn delivered_observation() -> Observation {
+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())
+}
+
+fn refused_without_fixture_mutation(
+ fixture: &Fixture,
+ before: &serde_json::Value,
+ code: RefusalCode,
+ response: &ToolResponse,
+) -> Observation {
+ thread::sleep(Duration::from_millis(150));
+ let after = fixture.journal.snapshot();
+ assert_eq!(
+ &after, before,
+ "{}: refused action mutated fixture state: before={before}, after={after}",
+ fixture.name
+ );
+ Observation::refused(
+ code,
+ vec![OracleKind::FixtureState],
+ response.text(),
+ Evidence::default(),
+ )
+}
+
+fn unverified_background_protocol_oracle(
+ response: &ToolResponse,
+ delivery: &str,
+) -> Vec<OracleKind> {
+ if !cfg!(target_os = "windows") || delivery != "background" {
+ return Vec::new();
+ }
+ assert_eq!(
+ response.verified(),
+ Some(false),
+ "background dispatch without independent read-back must remain unverified: {}",
+ response.text()
+ );
+ assert_ne!(
+ response.structured()["verify"].as_str(),
+ Some("confirmed"),
+ "background dispatch overclaimed a confirmed read-back: {}",
+ response.text()
+ );
+ vec![OracleKind::Protocol]
+}
+
+fn background_refusal_code(response: &ToolResponse, delivery: &str) -> Option<RefusalCode> {
+ if delivery != "background" || !response.is_error() {
+ return None;
+ }
+ response.structured()["code"]
+ .as_str()
+ .and_then(RefusalCode::from_driver_code)
+}
+
+fn run_text_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let text = format!("cua-{addressing}-{delivery}");
+ let mut args = action_target_args(fixture, &pre, "txt-input", addressing, delivery);
+ args.as_object_mut()
+ .expect("type_text arguments object")
+ .insert("text".to_owned(), serde_json::json!(text));
+ let response = fixture.driver.call("type_text", args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: type_text {addressing}/{delivery} failed: {}",
+ fixture.name,
+ response.text()
+ );
+ let mut passed = vec![OracleKind::FixtureState];
+ if addressing == "px" {
+ passed.extend(unverified_background_protocol_oracle(&response, delivery));
+ }
+ thread::sleep(Duration::from_millis(250));
+ assert_fixture_contains(fixture, &format!("mirror={text}"));
+ Observation::delivered(passed, Evidence::default())
+}
+
+fn run_press_key_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let mut press_args = action_target_args(fixture, &pre, "keyboard-input", addressing, delivery);
+ press_args
+ .as_object_mut()
+ .expect("press_key arguments object")
+ .insert("key".to_owned(), serde_json::json!("return"));
+ let response = fixture.driver.call("press_key", press_args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: press_key {addressing}/{delivery} failed: {}",
+ fixture.name,
+ response.text()
+ );
+ let mut passed = vec![OracleKind::FixtureState];
+ passed.extend(unverified_background_protocol_oracle(&response, delivery));
+ assert_fixture_contains(fixture, "key_state=enter");
+
+ Observation::delivered(passed, Evidence::default())
+}
+
+fn run_hotkey_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let mut hotkey_args = action_target_args(fixture, &pre, "keyboard-input", addressing, delivery);
+ hotkey_args
+ .as_object_mut()
+ .expect("hotkey arguments object")
+ .insert("keys".to_owned(), serde_json::json!(["ctrl", "shift", "7"]));
+ let response = fixture.driver.call("hotkey", hotkey_args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: hotkey {addressing}/{delivery} failed: {}",
+ fixture.name,
+ response.text()
+ );
+ assert_fixture_contains(fixture, "key_state=hotkey");
+ let passed = unverified_background_protocol_oracle(&response, delivery);
+ Observation::delivered_with_fixture_state(passed)
+}
+
+fn run_scroll_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let mut args = action_target_args(fixture, &pre, "scroll-tall", addressing, delivery);
+ let object = args.as_object_mut().expect("scroll arguments object");
+ object.insert("direction".to_owned(), serde_json::json!("down"));
+ object.insert("by".to_owned(), serde_json::json!("page"));
+ object.insert("amount".to_owned(), serde_json::json!(2));
+ let response = fixture.driver.call("scroll", args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
assert!(
- post.tree_text().contains(marker),
- "{}: application state did not reach {marker:?}: {}",
+ !response.is_error(),
+ "{}: scroll {addressing}/{delivery} failed: {}; raw={}",
fixture.name,
- post.tree_text()
+ response.text(),
+ response.raw
);
+ thread::sleep(Duration::from_millis(250));
+ let offset = fixture
+ .journal
+ .text("lbl-scroll-offset")
+ .and_then(|text| text.split("scroll_offset=").nth(1).map(str::to_owned))
+ .and_then(|tail| {
+ tail.split(|ch: char| !ch.is_ascii_digit())
+ .next()
+ .map(str::to_owned)
+ })
+ .and_then(|value| value.parse::<u64>().ok())
+ .unwrap_or(0);
+ assert!(
+ offset > 0,
+ "{}: scroll did not advance the external oracle: {}; response={}; raw={}",
+ fixture.name,
+ fixture.journal.snapshot(),
+ response.text(),
+ response.raw
+ );
+ delivered_observation()
}
-fn click_ax(fixture: &mut Fixture, id: &str) {
+fn run_drag_action(fixture: &mut Fixture, delivery: &str) -> Observation {
let pre = snapshot(fixture);
- let element_index = require_element(&pre, id);
+ let journal_before = fixture.journal.snapshot();
+ let source = require_element(&pre, "drag-source");
+ let target = require_element(&pre, "drop-target");
+ let origin = window_origin(fixture, &pre);
+ let scale = screenshot_scale(&pre);
+ let point = |index: u64| {
+ let (x, y) = element_center(&pre, index);
+ ((x - origin.0) * scale, (y - origin.1) * scale)
+ };
+ let (from_x, from_y) = point(source);
+ let (to_x, to_y) = point(target);
let response = fixture.driver.call(
- "click",
+ "drag",
serde_json::json!({
"pid": fixture.pid as i64,
"window_id": fixture.wid,
- "element_index": element_index,
- "delivery_mode": "background"
+ "from_x": from_x,
+ "from_y": from_y,
+ "to_x": to_x,
+ "to_y": to_y,
+ "duration_ms": 400,
+ "steps": 20,
+ "delivery_mode": delivery,
}),
);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
assert!(
!response.is_error(),
- "{}: AX click {id} failed: {}",
+ "{}: drag PX/{delivery} failed: {}; raw={}",
+ fixture.name,
+ response.text(),
+ response.raw
+ );
+ assert_fixture_contains(fixture, "drag_status=dropped");
+ delivered_observation()
+}
+
+fn run_child_window_action(fixture: &mut Fixture, addressing: &str, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let args = action_target_args(fixture, &pre, "btn-open-child-window", addressing, delivery);
+ let response = fixture.driver.call("click", args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: child-window click {addressing}/{delivery} failed: {}",
fixture.name,
response.text()
);
+ assert_fixture_contains(fixture, "child_windows=1");
+ delivered_observation()
}
-#[test]
-#[ignore]
-fn shared_web_calculator_ax_route_is_state_verified() {
- let mut failure = None;
- for spec in host_specs() {
- let result = run_host_case("calculator_ax", &spec, |mut fixture| {
- click_ax(&mut fixture, "calc-1");
- click_ax(&mut fixture, "calc-2");
- click_ax(&mut fixture, "calc-plus");
- click_ax(&mut fixture, "calc-4");
- click_ax(&mut fixture, "calc-equals");
- assert_tree_contains(&mut fixture, "display=16");
- println!("✅ {} calculator AX route", fixture.name);
- });
- if failure.is_none() {
- failure = result;
- }
+fn run_editor_save_action(fixture: &mut Fixture, delivery: &str) -> Observation {
+ let pre = snapshot(fixture);
+ let journal_before = fixture.journal.snapshot();
+ let text = format!("cua-editor-{delivery}");
+ let mut text_args = action_target_args(fixture, &pre, "editor-document", "ax", delivery);
+ text_args
+ .as_object_mut()
+ .expect("editor type_text arguments object")
+ .insert("text".to_owned(), serde_json::json!(text));
+ let response = fixture.driver.call("type_text", text_args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before, code, &response);
}
- resume_first_failure(failure);
+ assert!(
+ !response.is_error(),
+ "{}: editor type_text failed: {}",
+ fixture.name,
+ response.text()
+ );
+
+ let post_text = snapshot(fixture);
+ let journal_before_save = fixture.journal.snapshot();
+ let save_args = action_target_args(fixture, &post_text, "editor-save", "ax", delivery);
+ let response = fixture.driver.call("click", save_args);
+ if let Some(code) = background_refusal_code(&response, delivery) {
+ return refused_without_fixture_mutation(fixture, &journal_before_save, code, &response);
+ }
+ assert!(
+ !response.is_error(),
+ "{}: editor save failed: {}",
+ fixture.name,
+ response.text()
+ );
+ assert_fixture_contains(fixture, "editor_status=saved:");
+ delivered_observation()
}
-#[test]
-#[ignore]
-fn shared_web_keyboard_routes_are_state_verified() {
- let mut failure = None;
- for spec in host_specs() {
- let result = run_host_case("keyboard", &spec, |mut fixture| {
- let pre = snapshot(&mut fixture);
- let input = require_element(&pre, "keyboard-input");
- let (origin_x, origin_y) = window_origin(&fixture, &pre);
- let scale = screenshot_scale(&pre);
- let (screen_x, screen_y) = element_center(&pre, input);
- let focus = fixture.driver.call(
- "click",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "x": (screen_x - origin_x) * scale,
- "y": (screen_y - origin_y) * scale,
- "delivery_mode": "background"
- }),
- );
- assert!(
- !focus.is_error(),
- "{}: keyboard input focus click failed: {}",
- fixture.name,
- focus.text()
- );
- thread::sleep(Duration::from_millis(150));
- let enter = fixture.driver.call(
- "press_key",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "element_index": input,
- "key": "return",
- "delivery_mode": "background"
- }),
- );
- assert!(
- !enter.is_error(),
- "{}: return failed: {}",
- fixture.name,
- enter.text()
- );
- assert_tree_contains(&mut fixture, "key_state=enter");
+#[cfg(target_os = "linux")]
+fn linux_real_pointer_input_available() -> bool {
+ platform_linux::input::real_pointer_input_available()
+}
- let hotkey = fixture.driver.call(
- "hotkey",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "keys": ["ctrl", "shift", "7"],
- "x": (screen_x - origin_x) * scale,
- "y": (screen_y - origin_y) * scale,
- "delivery_mode": "background"
- }),
- );
- #[cfg(target_os = "windows")]
- {
- if hotkey.is_error()
- || hotkey
- .text()
- .contains("Background delivery is not available")
- {
- println!(
- "✅ {} keyboard AX route: background hotkey refused honestly",
- fixture.name
- );
- return;
- }
+#[cfg(not(target_os = "linux"))]
+fn linux_real_pointer_input_available() -> bool {
+ false
+}
+
+fn shared_case(spec: &HostSpec, action: &str, addressing: &str, delivery: &str) -> CaseSpec {
+ let targeting = match addressing {
+ "ax" => Targeting::Ax,
+ "px" => Targeting::Px,
+ _ => Targeting::NotApplicable,
+ };
+ let delivery_kind = match delivery {
+ "background" => Delivery::Background,
+ "foreground" => Delivery::Foreground,
+ _ => Delivery::NotApplicable,
+ };
+ let scenario = format!("{action}_{addressing}_{delivery}");
+ let cell_id = format!("{}-{}-{scenario}", std::env::consts::OS, spec.name).replace('_', "-");
+ let expected_refusals = if cfg!(target_os = "windows") && delivery_kind == Delivery::Background
+ {
+ match (spec.name, action, targeting) {
+ ("electron", "right_click" | "double_click" | "drag", _) => {
+ vec![RefusalCode::BackgroundOccluded]
+ }
+ ("electron", "type_text" | "press_key" | "hotkey" | "scroll" | "editor_save", _) => {
+ vec![RefusalCode::BackgroundUnavailable]
+ }
+ ("tauri", "hotkey", _) | ("tauri", "scroll", Targeting::Px) => {
+ vec![RefusalCode::BackgroundUnavailable]
+ }
+ ("tauri", "drag", Targeting::Px) => vec![RefusalCode::BackgroundOccluded],
+ _ => Vec::new(),
+ }
+ } else if cfg!(target_os = "macos") && delivery_kind == Delivery::Background {
+ match (spec.name, action, targeting) {
+ ("electron", "scroll", _) | (_, "drag", Targeting::Px) => {
+ vec![RefusalCode::BackgroundUnavailable]
}
- #[cfg(target_os = "linux")]
+ _ => Vec::new(),
+ }
+ } else if cfg!(target_os = "linux")
+ && spec.name == "electron"
+ && delivery_kind == Delivery::Background
+ {
+ // Chromium's X11 renderer drops synthetic input addressed to a fully
+ // occluded, unfocused toplevel. Focus-free AT-SPI button actions are
+ // the exception: they are externally verified by the fixture and the
+ // focus/z-order/leak sentinels.
+ if std::env::var_os("CUA_INJECT_SOCKET").is_some() {
+ Vec::new()
+ } else {
+ match (action, targeting) {
+ ("left_click" | "child_window", Targeting::Ax) => Vec::new(),
+ _ => vec![RefusalCode::BackgroundUnavailable],
+ }
+ }
+ } else if cfg!(target_os = "linux")
+ && spec.name == "tauri"
+ && delivery_kind == Delivery::Background
+ {
+ // WebKitGTK accepts AT-SPI text writes without emitting the renderer's
+ // user-input event, and its keyboard channel is focus-bound. The driver
+ // must refuse those background keyboard composites instead of reporting
+ // a successful write that the page never observes.
+ match (action, targeting) {
+ ("type_text", _) | ("editor_save", Targeting::Ax) | ("press_key" | "hotkey", _) => {
+ vec![RefusalCode::BackgroundUnavailable]
+ }
+ ("right_click" | "double_click" | "scroll", _) | ("drag", Targeting::Px)
+ if !linux_real_pointer_input_available() =>
{
- if hotkey.is_error()
- && hotkey.structured()["code"].as_str() == Some("background_unavailable")
- {
- println!(
- "✅ {} keyboard AX route: background hotkey refused honestly",
- fixture.name
- );
- return;
- }
+ vec![RefusalCode::BackgroundUnavailable]
}
- assert!(
- !hotkey.is_error(),
- "{}: Ctrl+Shift+7 failed: {}",
- fixture.name,
- hotkey.text()
- );
- assert_tree_contains(&mut fixture, "key_state=hotkey");
- println!("✅ {} keyboard AX routes", fixture.name);
- });
- if failure.is_none() {
- failure = result;
+ _ => Vec::new(),
+ }
+ } else {
+ Vec::new()
+ };
+ let expected_background_refusal = !expected_refusals.is_empty();
+ let mut oracles = if expected_background_refusal {
+ vec![OracleKind::FixtureState]
+ } else {
+ vec![OracleKind::FixtureState]
+ };
+ if delivery_kind == Delivery::Background {
+ oracles.extend([
+ OracleKind::Focus,
+ OracleKind::ZOrder,
+ OracleKind::NoLeakedInput,
+ ]);
+ if cua_driver_testkit::e2e::DisplayServer::current()
+ != cua_driver_testkit::e2e::DisplayServer::Wayland
+ {
+ oracles.push(OracleKind::Cursor);
+ }
+ if !expected_background_refusal
+ && cfg!(target_os = "windows")
+ && (matches!(action, "press_key" | "hotkey")
+ || (action == "type_text" && targeting == Targeting::Px))
+ {
+ oracles.push(OracleKind::Protocol);
}
}
- resume_first_failure(failure);
+ let mut route = shared_web_route(
+ cua_driver_testkit::e2e::Platform::current(),
+ cua_driver_testkit::e2e::DisplayServer::current(),
+ action,
+ targeting,
+ delivery_kind,
+ )
+ .unwrap_or_else(|error| panic!("{error}"));
+ if cfg!(target_os = "windows")
+ && spec.name == "electron"
+ && action == "left_click"
+ && delivery_kind == Delivery::Background
+ {
+ route = cua_driver_testkit::e2e::DriverRoute::PostMessage;
+ } else if cfg!(target_os = "macos")
+ && targeting == Targeting::Px
+ && delivery_kind == Delivery::Background
+ && matches!(action, "left_click" | "child_window")
+ {
+ route = cua_driver_testkit::e2e::DriverRoute::MacosAxAction;
+ }
+ let case = CaseSpec::delivered(
+ cell_id,
+ spec.name,
+ if spec.name == "electron" {
+ "chromium"
+ } else {
+ "platform-webview"
+ },
+ action,
+ targeting,
+ delivery_kind,
+ Scope::Window,
+ route,
+ oracles,
+ );
+ if expected_background_refusal {
+ case.expecting_refusal(expected_refusals)
+ } else {
+ case
+ }
}
-#[test]
-#[ignore]
-fn shared_web_calculator_pixel_route_is_state_verified() {
- let mut failure = None;
- for spec in host_specs() {
- let result = run_host_case("calculator_pixel", &spec, |mut fixture| {
- for id in ["calc-1", "calc-2", "calc-plus", "calc-4", "calc-equals"] {
- let pre = snapshot(&mut fixture);
- let origin = window_origin(&fixture, &pre);
- let scale = screenshot_scale(&pre);
- let index = require_element(&pre, id);
- let (screen_x, screen_y) = element_center(&pre, index);
- let response = fixture.driver.call(
- "click",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "x": (screen_x - origin.0) * scale,
- "y": (screen_y - origin.1) * scale,
- "delivery_mode": "background"
- }),
- );
- assert!(
- !response.is_error(),
- "{}: pixel click {id} failed: {}",
- fixture.name,
- response.text()
- );
- }
- assert_tree_contains(&mut fixture, "display=16");
- println!("✅ {} calculator pixel route", fixture.name);
- });
- if failure.is_none() {
- failure = result;
- }
- }
- resume_first_failure(failure);
+fn cell_selected(case: &CaseSpec) -> bool {
+ let Ok(filter) = std::env::var("CUA_E2E_CELL_FILTER") else {
+ return true;
+ };
+ let mut parts = filter
+ .split(',')
+ .map(str::trim)
+ .filter(|part| !part.is_empty())
+ .peekable();
+ parts.peek().is_none() || parts.any(|part| case.cell_id == part || case.cell_id.contains(part))
+}
+
+fn cell_filter_active() -> bool {
+ std::env::var("CUA_E2E_CELL_FILTER")
+ .map(|filter| filter.split(',').any(|part| !part.trim().is_empty()))
+ .unwrap_or(false)
}
#[test]
#[ignore]
-fn shared_web_editor_and_scroll_are_state_verified() {
+fn shared_web_action_matrix_is_state_verified() {
let mut failure = None;
+ let mut selected = 0usize;
for spec in host_specs() {
- let result = run_host_case("editor_scroll", &spec, |mut fixture| {
- let pre = snapshot(&mut fixture);
- let editor = require_element(&pre, "editor-document");
- let text = fixture.driver.call(
+ for (action, tool, marker) in [
+ ("left_click", "click", "last_action=left_click"),
+ ("right_click", "right_click", "last_action=right_click"),
+ ("double_click", "double_click", "last_action=double_click"),
+ ] {
+ for addressing in ["ax", "px"] {
+ for delivery in ["background", "foreground"] {
+ let case = shared_case(&spec, action, addressing, delivery);
+ if !cell_selected(&case) {
+ continue;
+ }
+ selected += 1;
+ let result = run_host_case_with_outcome(case, &spec, |fixture| {
+ run_pointer_action(fixture, tool, addressing, delivery, marker)
+ });
+ if failure.is_none() {
+ failure = result;
+ }
+ }
+ }
+ }
+ for (action, run) in [
+ (
"type_text",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "element_index": editor,
- "text": "CUA saved this note.",
- "delivery_mode": "background"
- }),
- );
- assert!(
- !text.is_error(),
- "{}: editor type_text failed: {}",
- fixture.name,
- text.text()
- );
- click_ax(&mut fixture, "editor-save");
- assert_tree_contains(&mut fixture, "editor_status=saved:");
-
- let scroll = require_element(&snapshot(&mut fixture), "scroll-tall");
- let response = fixture.driver.call(
+ run_text_action as fn(&mut Fixture, &str, &str) -> Observation,
+ ),
+ (
+ "press_key",
+ run_press_key_action as fn(&mut Fixture, &str, &str) -> Observation,
+ ),
+ (
+ "hotkey",
+ run_hotkey_action as fn(&mut Fixture, &str, &str) -> Observation,
+ ),
+ (
"scroll",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "element_index": scroll,
- "direction": "down",
- "by": "page",
- "amount": 4,
- "delivery_mode": "background"
- }),
- );
- #[cfg(target_os = "windows")]
- {
- if response.is_error()
- || response
- .text()
- .contains("Background delivery is not available")
- {
- println!(
- "✅ {} editor + scroll: background scroll refused honestly",
- fixture.name
- );
- return;
+ run_scroll_action as fn(&mut Fixture, &str, &str) -> Observation,
+ ),
+ (
+ "child_window",
+ run_child_window_action as fn(&mut Fixture, &str, &str) -> Observation,
+ ),
+ ] {
+ for addressing in ["ax", "px"] {
+ for delivery in ["background", "foreground"] {
+ let case = shared_case(&spec, action, addressing, delivery);
+ if !cell_selected(&case) {
+ continue;
+ }
+ selected += 1;
+ let result = run_host_case_with_outcome(case, &spec, |fixture| {
+ run(fixture, addressing, delivery)
+ });
+ if failure.is_none() {
+ failure = result;
+ }
}
}
- assert!(
- !response.is_error(),
- "{}: scroll failed: {}",
- fixture.name,
- response.text()
- );
- let post = snapshot(&mut fixture);
- let offset = post
- .tree_text()
- .lines()
- .find_map(|line| line.split("scroll_offset=").nth(1))
- .and_then(|tail| tail.split(|ch: char| !ch.is_ascii_digit()).next())
- .and_then(|value| value.parse::<u64>().ok())
- .unwrap_or(0);
- assert!(
- offset > 0,
- "{}: successful background scroll did not advance the external scroll oracle: {}",
- fixture.name,
- post.tree_text()
- );
- println!("✅ {} editor + scroll state oracles", fixture.name);
- });
- if failure.is_none() {
- failure = result;
}
- }
- resume_first_failure(failure);
-}
-
-#[test]
-#[ignore]
-fn shared_web_child_window_and_drag_have_external_oracles() {
- let mut failure = None;
- for spec in host_specs() {
- let result = run_host_case("child_window_drag", &spec, |mut fixture| {
- let pre = snapshot(&mut fixture);
- let (window_x, window_y) = window_origin(&fixture, &pre);
- let scale = screenshot_scale(&pre);
- let source = require_element(&pre, "drag-source");
- let frame = pre.structured()["elements"]
- .as_array()
- .and_then(|elements| {
- elements
- .iter()
- .find(|element| element["element_index"].as_u64() == Some(source))
- })
- .and_then(|element| element["frame"].as_object())
- .unwrap_or_else(|| panic!("{}: drag-source has no frame", fixture.name));
- let x = (frame["x"].as_f64().unwrap_or(0.0) - window_x
- + frame["w"].as_f64().unwrap_or(0.0) / 2.0)
- * scale;
- let y = (frame["y"].as_f64().unwrap_or(0.0) - window_y
- + frame["h"].as_f64().unwrap_or(0.0) / 2.0)
- * scale;
- let target_index = require_element(&pre, "drop-target");
- let target = pre.structured()["elements"]
- .as_array()
- .and_then(|elements| {
- elements
- .iter()
- .find(|element| element["element_index"].as_u64() == Some(target_index))
- })
- .and_then(|element| element["frame"].as_object())
- .unwrap_or_else(|| panic!("{}: drop-target has no frame", fixture.name));
- let tx = (target["x"].as_f64().unwrap_or(0.0) - window_x
- + target["w"].as_f64().unwrap_or(0.0) / 2.0)
- * scale;
- let ty = (target["y"].as_f64().unwrap_or(0.0) - window_y
- + target["h"].as_f64().unwrap_or(0.0) / 2.0)
- * scale;
- #[cfg(not(target_os = "macos"))]
- let _ = (x, y, tx, ty);
- #[cfg(target_os = "macos")]
- {
- let drag = fixture.driver.call(
- "drag",
- serde_json::json!({
- "pid": fixture.pid as i64,
- "window_id": fixture.wid,
- "from_x": x,
- "from_y": y,
- "to_x": tx,
- "to_y": ty,
- "duration_ms": 500,
- "delivery_mode": "foreground"
- }),
- );
- assert!(
- !drag.is_error(),
- "{}: drag failed: {}",
- fixture.name,
- drag.text()
- );
- assert_tree_contains(&mut fixture, "drag_status=dropped");
+ for delivery in ["background", "foreground"] {
+ let case = shared_case(&spec, "drag", "px", delivery);
+ if !cell_selected(&case) {
+ continue;
+ }
+ selected += 1;
+ let result = run_host_case_with_outcome(case, &spec, |fixture| {
+ run_drag_action(fixture, delivery)
+ });
+ if failure.is_none() {
+ failure = result;
+ }
+ }
+ for delivery in ["background", "foreground"] {
+ let case = shared_case(&spec, "editor_save", "ax", delivery);
+ if cell_selected(&case) {
+ selected += 1;
+ let result = run_host_case_with_outcome(case, &spec, |fixture| {
+ run_editor_save_action(fixture, delivery)
+ });
+ if failure.is_none() {
+ failure = result;
+ }
}
-
- click_ax(&mut fixture, "btn-open-child-window");
- assert_tree_contains(&mut fixture, "child_windows=1");
- println!("✅ {} child-window + drag state oracles", fixture.name);
- });
- if failure.is_none() {
- failure = result;
}
}
+ assert!(
+ !cell_filter_active() || selected > 0,
+ "CUA_E2E_CELL_FILTER matched no shared E2E cells"
+ );
resume_first_failure(failure);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs
new file mode 100644
index 0000000000..4666962983
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/e2e_environment_preflight_test.rs
@@ -0,0 +1,356 @@
+//! One strict GUI/recording preflight before a canonical E2E lane runs.
+
+#![cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
+
+use std::any::Any;
+use std::collections::HashSet;
+use std::panic::{self, AssertUnwindSafe};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+#[cfg(target_os = "linux")]
+use cua_driver_testkit::e2e::DisplayServer;
+use cua_driver_testkit::e2e::{write_environment_from_env, EnvironmentRecord};
+use cua_driver_testkit::{driver_binary, harness_app, spawn_in_job, Driver, McpDriver};
+
+struct PreflightFixture {
+ path: std::path::PathBuf,
+ args: Vec<&'static str>,
+ title: &'static str,
+ ax_marker: &'static str,
+}
+
+fn preflight_fixture() -> PreflightFixture {
+ #[cfg(target_os = "windows")]
+ {
+ PreflightFixture {
+ path: harness_app("harness-electron", "CuaTestHarness.Electron.exe"),
+ args: vec![
+ "--no-sandbox",
+ "--disable-gpu",
+ "--force-renderer-accessibility",
+ ],
+ title: "CuaTestHarness Electron",
+ ax_marker: "WEB_HARNESS_MARKER_v1",
+ }
+ }
+ #[cfg(target_os = "macos")]
+ {
+ PreflightFixture {
+ path: harness_app(
+ "harness-electron",
+ "CuaTestHarness.Electron.app/Contents/MacOS/Electron",
+ ),
+ args: vec!["--force-renderer-accessibility"],
+ title: "CuaTestHarness Electron",
+ ax_marker: "WEB_HARNESS_MARKER_v1",
+ }
+ }
+ #[cfg(target_os = "linux")]
+ {
+ if std::env::var("CUA_E2E_INTERNAL_LANE").as_deref() == Ok("native") {
+ PreflightFixture {
+ path: harness_app("harness-gtk3", "CuaTestHarness.Gtk3"),
+ args: Vec::new(),
+ title: "CuaTestHarness GTK3",
+ ax_marker: "HARNESS_TEXT_MARKER_v1",
+ }
+ } else {
+ PreflightFixture {
+ path: harness_app("harness-electron", "CuaTestHarness.Electron"),
+ args: vec![
+ "--no-sandbox",
+ "--disable-gpu",
+ "--force-renderer-accessibility",
+ ],
+ title: "CuaTestHarness Electron",
+ ax_marker: "WEB_HARNESS_MARKER_v1",
+ }
+ }
+ }
+}
+
+fn spawn_driver() -> McpDriver {
+ #[cfg(target_os = "macos")]
+ {
+ McpDriver::spawn_macos_daemon_proxy_named("environment-preflight")
+ .expect("installed CuaDriver daemon is not available")
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ McpDriver::spawn_named("environment-preflight")
+ .expect("source-built cua-driver could not be started")
+ }
+}
+
+fn has_image(response: &cua_driver_testkit::ToolResponse) -> bool {
+ response.raw["result"]["content"]
+ .as_array()
+ .map(|content| {
+ content
+ .iter()
+ .any(|item| item["type"].as_str() == Some("image"))
+ })
+ .unwrap_or(false)
+ || response.structured()["screenshot_png_base64"]
+ .as_str()
+ .map(|png| !png.is_empty())
+ .unwrap_or(false)
+}
+
+fn run_preflight() {
+ if let Ok(expected_sha) = std::env::var("CUA_E2E_SOURCE_SHA") {
+ assert!(
+ expected_sha.len() == 40 && expected_sha.chars().all(|ch| ch.is_ascii_hexdigit()),
+ "CUA_E2E_SOURCE_SHA must be a full commit SHA"
+ );
+ let source = Command::new("git").args(["rev-parse", "HEAD"]).output();
+ let actual_sha = source
+ .ok()
+ .filter(|source| source.status.success())
+ .map(|source| String::from_utf8_lossy(&source.stdout).trim().to_owned())
+ .or_else(|| {
+ let marker = std::env::var_os("CUA_E2E_SOURCE_MARKER")
+ .map(std::path::PathBuf::from)
+ .unwrap_or_else(|| std::path::PathBuf::from(".cua-e2e-source-sha"));
+ std::fs::read_to_string(marker)
+ .ok()
+ .map(|source| source.trim().to_owned())
+ })
+ .expect("neither git HEAD nor .cua-e2e-source-sha identifies the synced source");
+ assert_eq!(
+ actual_sha.to_ascii_lowercase(),
+ expected_sha.to_ascii_lowercase(),
+ "checked-out source does not match the workflow's resolved SHA"
+ );
+ }
+
+ let driver_path = driver_binary();
+ assert!(
+ driver_path.is_file(),
+ "source-built driver is missing at {}",
+ driver_path.display()
+ );
+ let version = Command::new(&driver_path)
+ .arg("--version")
+ .output()
+ .expect("source-built driver --version failed");
+ assert!(
+ version.status.success(),
+ "source-built driver is not runnable"
+ );
+ let version = String::from_utf8_lossy(&version.stdout);
+ assert!(
+ version.contains(env!("CARGO_PKG_VERSION")),
+ "driver version mismatch: {version}"
+ );
+
+ let fixture = preflight_fixture();
+ assert!(
+ fixture.path.exists(),
+ "required preflight fixture is missing at {}",
+ fixture.path.display()
+ );
+ let recordings_root = std::env::var_os("CUA_E2E_RECORDINGS_ROOT")
+ .expect("CUA_E2E_RECORDINGS_ROOT is required for canonical E2E");
+
+ let mut driver = spawn_driver();
+ let config = driver.call("get_config", serde_json::json!({}));
+ assert!(
+ !config.is_error(),
+ "connected driver get_config failed: {}",
+ config.text()
+ );
+ assert_eq!(
+ config.structured()["version"].as_str(),
+ Some(env!("CARGO_PKG_VERSION")),
+ "connected driver version does not match the source build"
+ );
+ let recording_dir = driver
+ .recording_dir()
+ .expect("preflight evidence directory was not prepared")
+ .to_path_buf();
+ assert!(
+ recording_dir.starts_with(&recordings_root),
+ "preflight recording escaped the artifact root"
+ );
+
+ let before = driver.call("list_windows", serde_json::json!({}));
+ assert!(!before.is_error(), "list_windows failed: {}", before.text());
+ let before_ids = before.structured()["windows"]
+ .as_array()
+ .map(|windows| {
+ windows
+ .iter()
+ .filter_map(|window| window["window_id"].as_u64())
+ .collect::<HashSet<_>>()
+ })
+ .unwrap_or_default();
+
+ let mut command = Command::new(&fixture.path);
+ command
+ .args(&fixture.args)
+ .stdout(Stdio::null())
+ .stderr(Stdio::inherit());
+ let mut child = spawn_in_job(&mut command).expect("preflight fixture failed to launch");
+ let launched_pid = child.id() as i64;
+
+ let deadline = Instant::now() + Duration::from_secs(20);
+ let (pid, window_id) = loop {
+ if let Some(status) = child
+ .try_wait()
+ .expect("could not inspect preflight fixture process")
+ {
+ panic!("preflight fixture exited before mapping a window: {status}");
+ }
+ let response = driver.call("list_windows", serde_json::json!({}));
+ if let Some(window) = response.structured()["windows"]
+ .as_array()
+ .and_then(|windows| {
+ windows.iter().find(|window| {
+ window["window_id"]
+ .as_u64()
+ .map(|id| !before_ids.contains(&id))
+ .unwrap_or(false)
+ && window["title"]
+ .as_str()
+ .unwrap_or("")
+ .contains(fixture.title)
+ })
+ })
+ {
+ if let Some(window_id) = window["window_id"].as_u64() {
+ break (window["pid"].as_i64().unwrap_or(launched_pid), window_id);
+ }
+ }
+ if Instant::now() >= deadline {
+ let _ = child.kill();
+ let _ = child.wait();
+ panic!("preflight fixture window did not appear");
+ }
+ std::thread::sleep(Duration::from_millis(200));
+ };
+ driver.reaper().push(child);
+
+ #[cfg(target_os = "linux")]
+ {
+ if DisplayServer::current() == DisplayServer::X11 {
+ let activated = driver.call(
+ "bring_to_front",
+ serde_json::json!({ "pid": pid, "window_id": window_id }),
+ );
+ assert!(
+ !activated.is_error(),
+ "preflight fixture could not be placed on the Linux desktop: {}",
+ activated.text()
+ );
+ std::thread::sleep(Duration::from_millis(300));
+ }
+ }
+
+ let deadline = Instant::now() + Duration::from_secs(15);
+ loop {
+ let state = driver.call(
+ "get_window_state",
+ serde_json::json!({
+ "pid": pid,
+ "window_id": window_id,
+ "capture_mode": "ax"
+ }),
+ );
+ if !state.is_error() && state.tree_text().contains(fixture.ax_marker) && has_image(&state) {
+ break;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "preflight could not read both AX state and screenshot: {}",
+ state.text()
+ );
+ std::thread::sleep(Duration::from_millis(200));
+ }
+
+ driver.start_behavior_recording();
+
+ drop(driver);
+ let video = recording_dir.join("recording.mp4");
+ assert!(
+ std::fs::metadata(&video)
+ .map(|metadata| metadata.len() > 0)
+ .unwrap_or(false),
+ "preflight video is missing or empty at {}",
+ video.display()
+ );
+ assert!(
+ !recording_dir.join("recording-error.txt").exists(),
+ "preflight recording reported an error"
+ );
+ let probe = Command::new("ffprobe")
+ .args([
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "default=noprint_wrappers=1:nokey=1",
+ ])
+ .arg(&video)
+ .status()
+ .expect("ffprobe is required for canonical E2E");
+ assert!(probe.success(), "ffprobe rejected the preflight video");
+
+ let frame = recording_dir.join("preflight-frame.png");
+ let extracted = Command::new("ffmpeg")
+ .args(["-y", "-sseof", "-0.2", "-i"])
+ .arg(&video)
+ .args(["-frames:v", "1"])
+ .arg(&frame)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .expect("ffmpeg is required for canonical E2E");
+ assert!(
+ extracted.success(),
+ "could not extract preflight video frame"
+ );
+ let frame = image::open(&frame)
+ .expect("preflight video frame is not a readable image")
+ .to_rgb8();
+ let non_dark_pixels = frame
+ .pixels()
+ .filter(|pixel| pixel.0.iter().copied().max().unwrap_or(0) > 30)
+ .count();
+ assert!(
+ non_dark_pixels * 1_000 >= frame.pixels().len(),
+ "preflight video is effectively blank: {non_dark_pixels}/{} non-dark pixels",
+ frame.pixels().len()
+ );
+}
+
+fn panic_message(payload: &Box<dyn Any + Send>) -> String {
+ payload
+ .downcast_ref::<String>()
+ .cloned()
+ .or_else(|| {
+ payload
+ .downcast_ref::<&str>()
+ .map(|message| (*message).to_owned())
+ })
+ .unwrap_or_else(|| "preflight panicked without a string payload".to_owned())
+}
+
+#[test]
+#[ignore]
+fn canonical_e2e_environment_is_ready() {
+ let started = Instant::now();
+ let outcome = panic::catch_unwind(AssertUnwindSafe(run_preflight));
+ match outcome {
+ Ok(()) => write_environment_from_env(&EnvironmentRecord::ready(started.elapsed()))
+ .expect("write environment record"),
+ Err(payload) => {
+ let message = panic_message(&payload);
+ write_environment_from_env(&EnvironmentRecord::error(started.elapsed(), message))
+ .expect("write failed environment record");
+ panic::resume_unwind(payload);
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_background_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_background_test.rs
deleted file mode 100644
index da1f125b40..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_background_test.rs
+++ /dev/null
@@ -1,398 +0,0 @@
-//! Background-modality + capture-mode tests for the CuaTestHarness.Wpf
-//! harness.
-//!
-//! These verify the **core cua-driver promise**: background automation
-//! must not steal foreground from the user's active window. The harness
-//! window is at z+0 when shown (whatever WPF gives it), the
-//! focus-monitor-win sentinel is then activated to z+0 (displacing the
-//! harness to z+1), and cua-driver actions targeting the harness must
-//! NOT make the harness regain foreground.
-//!
-//! Sentinel: `focus-monitor-win` (already part of the workspace; built by
-//! `cargo build`). It writes `focus_monitor_losses.txt` to %TEMP% — the
-//! count of times its window lost activation. We snapshot before / after
-//! each action and assert delta == 0.
-//!
-//! Also covers **capture_mode ax** (UIA-only, no screenshot — the default) and
-//! **capture_mode vision** (screenshot-only, no UIA tree). (`som` is a
-//! deprecated alias for `ax`.)
-
-#![cfg(target_os = "windows")]
-
-use std::path::PathBuf;
-use std::process::{Command, Stdio};
-use std::time::Duration;
-
-use cua_driver_testkit::ax::element_index_by_id;
-use cua_driver_testkit::{harness_app, workspace_root, Driver, McpDriver};
-
-// ── paths ────────────────────────────────────────────────────────────────────
-
-fn focus_monitor_binary() -> PathBuf { workspace_root().join("target/debug/focus-monitor-win.exe") }
-fn harness_wpf_exe() -> PathBuf {
- if let Ok(p) = std::env::var("HARNESS_WPF_EXE") {
- let pb = PathBuf::from(p);
- if pb.exists() { return pb; }
- }
- harness_app("harness-wpf", "CuaTestHarness.Wpf.exe")
-}
-
-fn loss_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_losses.txt") }
-fn gain_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_gains.txt") }
-fn key_loss_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_key_losses.txt") }
-fn key_gain_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_key_gains.txt") }
-fn focus_pid_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_pid.txt") }
-fn focus_hwnd_file() -> PathBuf { std::env::temp_dir().join("focus_monitor_hwnd.txt") }
-
-fn read_count(p: &std::path::Path) -> u32 {
- // Surface read / parse errors instead of swallowing them as 0 — a silent
- // 0 would mask actual focus-steal regressions by making delta computation
- // look "no change" when really the sentinel file is unreadable.
- let raw = std::fs::read_to_string(p)
- .unwrap_or_else(|e| panic!("failed reading sentinel counter {p:?}: {e}"));
- raw.trim()
- .parse::<u32>()
- .unwrap_or_else(|e| panic!("failed parsing sentinel counter {p:?} as u32: {e}"))
-}
-
-// ── shared fixture ───────────────────────────────────────────────────────────
-
-/// Launch sequence:
-/// 0. cua-driver MCP server (headless stdio; its reaper owns the harness +
-/// sentinel below, so any early-return or panic reaps the whole tree).
-/// 1. WPF harness (becomes foreground briefly on its own activation).
-/// 2. focus-monitor-win sentinel — its OnLoad SetForegroundWindow displaces
-/// the harness; sentinel is now z+0, harness z+1.
-/// 3. Reset losses.txt to 0 (sentinel may have logged its own startup activate)
-/// and resolve the harness window (pid + window_id).
-fn setup() -> Option<(McpDriver, u32, u64)> {
- let fm_bin = focus_monitor_binary();
- if !fm_bin.exists() {
- eprintln!("focus-monitor-win.exe not built — skipping"); return None;
- }
- let h_exe = harness_wpf_exe();
- if !h_exe.exists() {
- eprintln!("harness WPF exe not built — skipping"); return None;
- }
-
- // Reset sentinel files so we start from a known baseline.
- let _ = std::fs::write(loss_file(), "0");
- let _ = std::fs::write(gain_file(), "0");
- let _ = std::fs::write(key_loss_file(), "0");
- let _ = std::fs::write(key_gain_file(), "0");
- let _ = std::fs::remove_file(focus_pid_file());
- let _ = std::fs::remove_file(focus_hwnd_file());
-
- // Spawn the cua-driver MCP server (skips if the binary isn't built).
- let mut driver = McpDriver::spawn()?;
-
- // 1. WPF harness, launched through the reaper so it can't outlive the test.
- driver
- .reaper()
- .spawn(Command::new(&h_exe).stdout(Stdio::null()).stderr(Stdio::null()))
- .ok()?;
- std::thread::sleep(Duration::from_secs(1));
-
- // 2. Launch sentinel. focus-monitor-win activates its own window which
- // displaces the harness.
- if driver
- .reaper()
- .spawn(Command::new(&fm_bin).stdout(Stdio::null()).stderr(Stdio::null()))
- .is_err()
- {
- eprintln!("focus-monitor-win spawn failed");
- return None;
- }
-
- // Wait for sentinel to publish its pid+hwnd files (so we know it's up and
- // has claimed foreground). On timeout we return None; dropping `driver`
- // reaps the harness + sentinel so they don't poison subsequent tests.
- let deadline = std::time::Instant::now() + Duration::from_secs(10);
- loop {
- let pid_ok = std::fs::read_to_string(focus_pid_file()).ok()
- .and_then(|s| s.trim().parse::<u32>().ok()).unwrap_or(0) != 0;
- let hwnd_ok = std::fs::read_to_string(focus_hwnd_file()).ok()
- .and_then(|s| s.trim().parse::<u64>().ok()).unwrap_or(0) != 0;
- if pid_ok && hwnd_ok { break; }
- if std::time::Instant::now() > deadline {
- eprintln!("focus-monitor sentinel never published pid/hwnd files");
- return None;
- }
- std::thread::sleep(Duration::from_millis(100));
- }
- std::thread::sleep(Duration::from_millis(400)); // sentinel-active settle
-
- // Reset losses again now that sentinel has settled. Any prior loss
- // counts (e.g. from harness coming up after the sentinel did) shouldn't
- // count against the test.
- let _ = std::fs::write(loss_file(), "0");
- let _ = std::fs::write(gain_file(), "0");
- let _ = std::fs::write(key_loss_file(), "0");
- let _ = std::fs::write(key_gain_file(), "0");
-
- // Resolve the harness window (pid + window_id) by title. The WPF harness is
- // its own window process, so list_windows surfaces it directly.
- let resp = driver.call("list_windows", serde_json::json!({}));
- let (harness_pid, harness_wid) = resp.structured()["windows"].as_array()
- .and_then(|a| a.iter().find_map(|w| {
- let title = w["title"].as_str().unwrap_or("");
- if title.contains("CuaTestHarness WPF") {
- Some((w["pid"].as_u64()? as u32, w["window_id"].as_u64()?))
- } else {
- None
- }
- }))
- .expect("harness window not found");
-
- Some((driver, harness_pid, harness_wid))
-}
-
-/// Strict mode: action must not generate ANY sentinel-loss event.
-fn assert_no_focus_steal<F>(label: &str, f: F)
-where F: FnOnce() {
- let before_act = read_count(&loss_file());
- let before_key = read_count(&key_loss_file());
- f();
- std::thread::sleep(Duration::from_millis(400));
- let after_act = read_count(&loss_file());
- let after_key = read_count(&key_loss_file());
- let d_act = after_act.saturating_sub(before_act);
- let d_key = after_key.saturating_sub(before_key);
- assert_eq!(d_act, 0,
- "{label}: sentinel act_losses went {before_act} -> {after_act} (delta={d_act}). \
- cua-driver's background action stole foreground from the user.");
- assert_eq!(d_key, 0,
- "{label}: sentinel key_losses went {before_key} -> {after_key} (delta={d_key}).");
- println!("✅ {label}: no focus steal (act_losses=0, key_losses=0)");
-}
-
-/// Relaxed mode: read GetForegroundWindow() after the action and assert
-/// it's still the sentinel HWND. Tolerates a transient blip during the
-/// action (which UIA Invoke against WPF Buttons creates unavoidably —
-/// the target's handler calls Focus() before cua-driver gets control).
-/// The cua-driver fg_bypass restores foreground after, and this check
-/// asserts that restoration actually worked.
-// Documented oracle kept for the foreground-restore scenarios; not currently
-// wired to a live test (preserved verbatim from before the testkit migration).
-#[allow(dead_code)]
-fn assert_foreground_restored<F>(label: &str, f: F)
-where F: FnOnce() {
- let sentinel_hwnd: u64 = std::fs::read_to_string(focus_hwnd_file())
- .ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
- assert!(sentinel_hwnd != 0, "{label}: sentinel hwnd unknown (file missing)");
-
- let before_loss = read_count(&loss_file());
- f();
- std::thread::sleep(Duration::from_millis(500));
- let after_loss = read_count(&loss_file());
- let d_loss = after_loss.saturating_sub(before_loss);
-
- // Read current foreground via Win32 directly.
- let now_fg: u64 = unsafe {
- let h = windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow();
- h.0 as u64
- };
- assert_eq!(now_fg, sentinel_hwnd,
- "{label}: GetForegroundWindow={now_fg:#x} but sentinel hwnd={sentinel_hwnd:#x}. \
- Foreground was NOT restored to the user's window after the action.");
- if d_loss == 0 {
- println!("✅ {label}: no focus blip at all (losses=0)");
- } else {
- println!("✅ {label}: foreground restored after {d_loss} blip(s) — sentinel HWND={sentinel_hwnd:#x} matches GetForegroundWindow");
- }
-}
-
-// ── BACKGROUND MODALITY: cua-driver must keep harness at z+1 ────────────────
-
-#[test]
-#[ignore]
-fn bg_modality_get_window_state_no_focus_steal() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- // Exercise the screenshot-bearing path (`vision`) — screen capture is the
- // focus-sensitive operation; `ax` no longer grabs a frame at all.
- assert_no_focus_steal("get_window_state(vision)", || {
- let _ = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "vision"}));
- });
-}
-
-/// Documents the cua-driver focus-steal gap for UIA Invoke on a WPF
-/// Button. Root cause: WPF's ButtonBase.OnClick handler synchronously
-/// calls `UIElement.Focus()` which routes through `SetForegroundWindow`
-/// and is NOT gated by the EnableWindow(false) bypass used for UWP
-/// hosts. The daemon CAN'T restore foreground reliably either, because
-/// non-UIAccess processes are subject to the foreground-lock.
-///
-/// **Mitigation**: route UIA activations through `cua-driver-uia.exe`
-/// (UIAccess-manifested worker). With UIAccess, the worker can both
-/// suppress the self-foreground and restore the user's foreground if
-/// it leaked through.
-///
-/// This test ASSERTS the gap currently exists. When cua-driver gains
-/// the UIAccess worker path, flip this assertion to `delta == 0` and
-/// rename to `..._no_focus_steal`.
-#[test]
-#[ignore]
-// Name intentionally documents a KNOWN focus-steal (see doc comment above).
-#[allow(non_snake_case)]
-fn bg_modality_uia_invoke_click_DOCUMENTED_steals_focus() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- let _ = driver.call("set_agent_cursor_enabled",
- serde_json::json!({"enabled": false}));
- std::thread::sleep(Duration::from_millis(200));
-
- let snap = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "ax"}));
- let idx = element_index_by_id(snap.text(), "btn-increment").expect("btn-increment");
-
- let before = read_count(&loss_file());
- let _ = driver.call("click",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "element_index": idx}));
- std::thread::sleep(Duration::from_millis(500));
- let after = read_count(&loss_file());
- let delta = after.saturating_sub(before);
- assert!(delta >= 1,
- "Expected the documented focus-steal gap (delta>=1). Got delta={delta}. \
- If this now passes, cua-driver has fixed UIA Invoke focus-steal — \
- flip this assertion to delta==0 and update the docstring.");
- println!("⚠️ bg_modality_uia_invoke_click: gap confirmed (delta={delta}). \
- Mitigation = route UIA via cua-driver-uia.exe (UIAccess worker).");
-}
-
-/// Companion gap: UIA ValuePattern.SetValue on WPF TextBox.
-/// Same root cause and mitigation path as
-/// bg_modality_uia_invoke_click_DOCUMENTED_steals_focus.
-#[test]
-#[ignore]
-// Name intentionally documents a KNOWN focus-steal (see doc comment above).
-#[allow(non_snake_case)]
-fn bg_modality_set_value_DOCUMENTED_steals_focus() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- let _ = driver.call("set_agent_cursor_enabled",
- serde_json::json!({"enabled": false}));
- std::thread::sleep(Duration::from_millis(200));
-
- let snap = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "ax"}));
- let idx = element_index_by_id(snap.text(), "txt-input").expect("txt-input");
-
- let before = read_count(&loss_file());
- let _ = driver.call("set_value",
- serde_json::json!({
- "pid": pid as i64, "window_id": wid, "element_index": idx,
- "value": "via-uia-no-focus-steal"
- }));
- std::thread::sleep(Duration::from_millis(500));
- let after = read_count(&loss_file());
- let delta = after.saturating_sub(before);
- assert!(delta >= 1,
- "Expected the documented SetValue focus-steal gap. delta={delta}.");
- println!("⚠️ bg_modality_set_value: gap confirmed (delta={delta})");
-}
-
-#[test]
-#[ignore]
-fn bg_modality_press_key_no_focus_steal() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- // F5 fires the harness accelerator (KeyBinding) via PostMessage
- // WM_KEYDOWN — background path, no foreground swap.
- assert_no_focus_steal("press_key(f5, PostMessage)", || {
- let _ = driver.call("press_key",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "key": "f5"}));
- });
-}
-
-#[test]
-#[ignore]
-fn bg_modality_scroll_no_focus_steal() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- assert_no_focus_steal("scroll(down, PostMessage WM_VSCROLL)", || {
- let _ = driver.call("scroll",
- serde_json::json!({
- "pid": pid as i64, "window_id": wid,
- "direction": "down", "by": "line", "amount": 3
- }));
- });
-}
-
-// ── PERCEPTION: returns both tree + screenshot, with an opt-out ─────────────
-
-#[test]
-#[ignore]
-fn default_returns_tree_and_image() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- // Default (no capture_mode): BOTH the tree AND a screenshot.
- let resp = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid}));
- assert!(resp.text().contains("id=btn-increment"),
- "default tree missing btn-increment AID");
- let has_image = resp.raw["result"]["content"].as_array()
- .map(|a| a.iter().any(|c| c["type"].as_str() == Some("image")))
- .unwrap_or(false);
- assert!(has_image, "default get_window_state must return a screenshot alongside the tree");
- println!("✅ default_returns_tree_and_image: tree + image both present");
-
- assert_no_focus_steal("get_window_state(default)", || {
- let _ = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid}));
- });
-}
-
-#[test]
-#[ignore]
-fn include_screenshot_false_returns_tree_only() {
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- // The perf opt-out: tree present, NO image (the cheap re-index path).
- let resp = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "include_screenshot": false}));
- assert!(resp.text().contains("id=btn-increment"),
- "tree-only snapshot missing btn-increment AID");
- let has_image = resp.raw["result"]["content"].as_array()
- .map(|a| a.iter().any(|c| c["type"].as_str() == Some("image")))
- .unwrap_or(false);
- assert!(!has_image,
- "include_screenshot:false should NOT return image content (got one anyway)");
- println!("✅ include_screenshot_false_returns_tree_only: tree present, no image");
-}
-
-#[test]
-#[ignore]
-fn deprecated_capture_mode_is_ignored() {
- // The legacy `capture_mode:"vision"` used to suppress the tree. It is now
- // ignored — both halves must still come back.
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- let resp = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "vision"}));
- assert!(resp.text().contains("id=btn-increment"),
- "capture_mode=vision must NOT suppress the tree (it is deprecated/ignored)");
- let has_image = resp.raw["result"]["content"].as_array()
- .map(|a| a.iter().any(|c| c["type"].as_str() == Some("image")))
- .unwrap_or(false);
- assert!(has_image, "capture_mode=vision must NOT suppress the screenshot either");
- println!("✅ deprecated_capture_mode_is_ignored: both tree and image returned");
-}
-
-#[test]
-#[ignore]
-fn ground_invoke_reground_roundtrip() {
- // Ground (both tree + image) → find element → element ax action (Invoke) →
- // re-ground and confirm the post-action state. Mirrors how an agent works.
- let (mut driver, pid, wid) = match setup() { Some(x) => x, None => return };
- let snap = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid}));
- let idx = element_index_by_id(snap.text(), "btn-increment").expect("btn-increment");
-
- let _ = driver.call("click",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "element_index": idx}));
- std::thread::sleep(Duration::from_millis(300));
-
- let snap2 = driver.call("get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid}));
- let has_image = snap2.raw["result"]["content"].as_array()
- .map(|a| a.iter().any(|c| c["type"].as_str() == Some("image")))
- .unwrap_or(false);
- assert!(has_image, "re-ground snapshot didn't return an image");
- assert!(snap2.text().contains("counter=1"),
- "counter didn't advance after UIA Invoke");
- println!("✅ ground_invoke_reground_roundtrip: ground→invoke→reground (tree+image) green");
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_desktop_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_desktop_scope_test.rs
deleted file mode 100644
index 1ca79a9989..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_desktop_scope_test.rs
+++ /dev/null
@@ -1,152 +0,0 @@
-//! Harness integration test for the **desktop-scope** modality (#1968 / #2019).
-//!
-//! Desktop-scope is cua-driver's *foreground*, vision-only, **screen-absolute**
-//! loop (the "Computer-Use 1.0" mode), the complement to the default per-window
-//! background model that `harness_bg_modality_test` / `e2e_windows_bg_input_test`
-//! cover. This test exercises the Windows Phase-1 actuator end-to-end against a
-//! real harness app:
-//!
-//! 1. `set_config capture_scope=desktop` → `get_desktop_state` returns a
-//! full-display capture with true `screen_width/height` (no downscale).
-//! 2. A **window-less** screen-absolute `click` / `scroll` (no pid/window_id)
-//! lands via `WindowFromPoint` while in desktop scope.
-//! 3. Negative gate: the same window-less `click` under `capture_scope=window`
-//! is rejected with the structured `desktop_scope_disabled` error.
-//!
-//! Note: `set_config` is a *session* override — it persists for the lifetime of
-//! the one MCP server we spawn here (not across separate `cua-driver call`
-//! processes), which is exactly why this test drives a single long-lived server.
-//!
-//! All tests are `#[ignore]` (need a real desktop session). Run explicitly:
-//! cargo test -p cua-driver --test harness_desktop_scope_test -- --ignored --nocapture --test-threads=1
-
-#![cfg(target_os = "windows")]
-
-use std::process::{Command, Stdio};
-use std::time::{Duration, Instant};
-
-use cua_driver_testkit::{harness_app, Driver, McpDriver};
-
-/// WPF harness app (built by `tests/fixtures/build/windows.ps1`). Path mirrors
-/// `shared/scenarios.json`'s `wpf.exe_relative_path`.
-fn harness_wpf_exe() -> std::path::PathBuf {
- harness_app("harness-wpf", "CuaTestHarness.Wpf.exe")
-}
-
-/// Launch the WPF harness app and return (pid, window center in screen px).
-/// Skips (returns None) if the harness app isn't built.
-fn launch_wpf_and_center(driver: &mut McpDriver) -> Option<(u32, i32, i32)> {
- let exe = harness_wpf_exe();
- if !exe.exists() {
- eprintln!("[desktop-scope] WPF harness not built ({exe:?}) — skipping window-target tests");
- return None;
- }
- driver
- .reaper()
- .spawn(Command::new(&exe).stdout(Stdio::null()).stderr(Stdio::null()))
- .ok()?;
-
- let deadline = Instant::now() + Duration::from_secs(15);
- while Instant::now() < deadline {
- let r = driver.call("list_windows", serde_json::json!({}));
- if let Some(arr) = r.structured()["windows"].as_array() {
- for w in arr {
- let title = w["title"].as_str().unwrap_or("");
- if !title.contains("CuaTestHarness") {
- continue;
- }
- let pid = w["pid"].as_u64().unwrap_or(0) as u32;
- // #2018: bounds is nested {x,y,width,height} on Windows.
- let b = &w["bounds"];
- let (x, y, ww, h) = (
- b["x"].as_i64().unwrap_or(0) as i32,
- b["y"].as_i64().unwrap_or(0) as i32,
- b["width"].as_i64().unwrap_or(0) as i32,
- b["height"].as_i64().unwrap_or(0) as i32,
- );
- if pid != 0 && ww > 0 && h > 0 {
- driver.reaper().track_pid(pid);
- return Some((pid, x + ww / 2, y + h / 2));
- }
- }
- }
- std::thread::sleep(Duration::from_millis(500));
- }
- eprintln!("[desktop-scope] WPF harness window never appeared — skipping");
- None
-}
-
-fn set_scope(driver: &mut McpDriver, scope: &str) {
- let r = driver.call(
- "set_config",
- serde_json::json!({ "key": "capture_scope", "value": scope }),
- );
- assert!(!r.is_error(), "set_config capture_scope={scope} failed: {}", r.text());
- assert_eq!(
- r.structured()["capture_scope"].as_str(),
- Some(scope),
- "set_config did not report capture_scope={scope}: {}",
- r.text()
- );
-}
-
-// ── tests ─────────────────────────────────────────────────────────────────────
-
-/// `get_desktop_state` in desktop scope returns a full-display capture with
-/// real screen dimensions (the Session-0 `handle is invalid` case is only the
-/// service-session wall; this needs a real interactive desktop).
-#[test]
-#[ignore]
-fn desktop_scope_capture_returns_screen_dims() {
- let Some(mut driver) = McpDriver::spawn() else { return };
- set_scope(&mut driver, "desktop");
- let r = driver.call("get_desktop_state", serde_json::json!({}));
- assert!(!r.is_error(), "get_desktop_state errored: {}", r.text());
- let sw = r.structured()["screen_width"].as_u64().unwrap_or(0);
- let sh = r.structured()["screen_height"].as_u64().unwrap_or(0);
- assert!(sw > 0 && sh > 0, "get_desktop_state returned no/zero screen size: {}", r.text());
- eprintln!("[desktop-scope] get_desktop_state OK — screen {sw}x{sh}");
-}
-
-/// In desktop scope, a window-less screen-absolute click + scroll succeed and
-/// resolve a real window via WindowFromPoint (no pid/window_id supplied).
-#[test]
-#[ignore]
-fn desktop_scope_windowless_click_and_scroll_land() {
- let Some(mut driver) = McpDriver::spawn() else { return };
- set_scope(&mut driver, "desktop");
- let Some((_pid, cx, cy)) = launch_wpf_and_center(&mut driver) else { return };
-
- let clicked = driver.call("click", serde_json::json!({ "x": cx, "y": cy }));
- assert!(!clicked.is_error(), "desktop-scope click errored: {}", clicked.text());
- let ct = clicked.text().to_lowercase();
- assert!(ct.contains("desktop scope"), "click not reported as desktop-scope: {}", clicked.text());
- assert!(ct.contains("hwnd"), "click did not resolve a window via WindowFromPoint: {}", clicked.text());
-
- let scrolled = driver.call(
- "scroll",
- serde_json::json!({ "x": cx, "y": cy, "direction": "down" }),
- );
- assert!(!scrolled.is_error(), "desktop-scope scroll errored: {}", scrolled.text());
- assert!(
- scrolled.text().to_lowercase().contains("desktop scope"),
- "scroll not reported as desktop-scope: {}",
- scrolled.text()
- );
-}
-
-/// Negative gate: a window-less screen-absolute click under `capture_scope=window`
-/// must be rejected (the `desktop_scope_disabled` contract), not silently retargeted.
-#[test]
-#[ignore]
-fn window_scope_rejects_windowless_click() {
- let Some(mut driver) = McpDriver::spawn() else { return };
- set_scope(&mut driver, "window");
- let r = driver.call("click", serde_json::json!({ "x": 100, "y": 100 }));
- let txt = r.text().to_lowercase();
- assert!(
- r.is_error() || txt.contains("desktop scope") || txt.contains("desktop_scope_disabled"),
- "window-scope window-less click was NOT rejected: {}",
- r.text()
- );
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_dispatch_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_dispatch_test.rs
deleted file mode 100644
index e9332c5cfa..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_dispatch_test.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-//! Modality axis: the best-effort-background dispatch ladder (macOS).
-//!
-//! Covers the contract introduced by the modality-ladder work:
-//! - `delivery_mode` (background | foreground) on the input tools,
-//! - `scope` (window | desktop) as a per-call param on `click`,
-//! - the `{path, verified}` structured outcome,
-//! - `bring_to_front` as a real macOS activation (no longer a Windows-only stub).
-//!
-//! The schema assertions are deterministic and run in CI (they only inspect
-//! `tools/list`). The end-to-end ladder behavior is `#[ignore]` — it needs a
-//! real focus-sensitive app + a GUI session, so it runs interactively / on the
-//! VMs, asserting per-rung outcomes via the testkit `path()` / `verified()`
-//! accessors instead of scraping result text.
-
-#![cfg(target_os = "macos")]
-
-use cua_driver_testkit::RawDriver;
-
-/// `delivery_mode` (type_text + click) and `scope` (click) are advertised with
-/// their enums in `tools/list`. Consumers branch on these being present.
-#[test]
-fn dispatch_and_scope_schema_advertised() {
- let Some(mut d) = RawDriver::spawn() else { return };
- d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- d.recv();
- d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
- let resp = d.recv();
- let tools = resp["result"]["tools"].as_array().expect("tools array");
-
- let props = |name: &str| {
- tools.iter().find(|t| t["name"] == name)
- .unwrap_or_else(|| panic!("{name} not in tools/list"))
- ["inputSchema"]["properties"].clone()
- };
-
- let enum_values = |v: &serde_json::Value| -> Vec<String> {
- v["enum"].as_array()
- .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect())
- .unwrap_or_default()
- };
-
- for tool in ["type_text", "click"] {
- let dm = props(tool)["delivery_mode"].clone();
- let en = enum_values(&dm);
- assert!(
- en.iter().any(|s| s == "background") && en.iter().any(|s| s == "foreground"),
- "{tool}.delivery_mode enum should be [background, foreground], got {dm:?}"
- );
- }
-
- let scope = props("click")["scope"].clone();
- let sen = enum_values(&scope);
- assert!(
- sen.iter().any(|s| s == "window") && sen.iter().any(|s| s == "desktop"),
- "click.scope enum should be [window, desktop], got {scope:?}"
- );
-}
-
-/// `bring_to_front` is a real macOS activation now (the user's change), not the
-/// old "Windows-only" error stub — its description must reflect that.
-#[test]
-fn bring_to_front_is_macos_native_not_windows_only() {
- let Some(mut d) = RawDriver::spawn() else { return };
- d.send(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}));
- d.recv();
- d.send(&serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}));
- let resp = d.recv();
- let tools = resp["result"]["tools"].as_array().expect("tools array");
- let btf = tools.iter().find(|t| t["name"] == "bring_to_front")
- .expect("bring_to_front not in tools/list");
- let desc = btf["description"].as_str().unwrap_or("");
- assert!(
- !desc.contains("Windows-only"),
- "bring_to_front should be a real macOS activation now, not Windows-only: {desc}"
- );
-}
-
-// ── End-to-end ladder behavior (interactive; needs a GUI session) ────────────
-
-/// On a NATIVE Cocoa field (TextEdit), `delivery_mode:"background"` lands via the
-/// AX value-write and the driver confirms it: `path:"ax", verified:true`. This is
-/// the driver-verifiable happy path — no foreground needed, no screenshot needed.
-#[test]
-#[ignore]
-fn background_type_on_native_cocoa_is_ax_verified() {
- use cua_driver_testkit::{Driver, McpDriver};
- let Some(mut driver) = McpDriver::spawn() else { return };
-
- // Launch TextEdit and open a blank document.
- let launch = driver.call("launch_app", serde_json::json!({ "bundle_id": "com.apple.TextEdit" }));
- if launch.is_error() {
- eprintln!("[dispatch] could not launch TextEdit — skipping");
- return;
- }
- let pid = launch.structured()["pid"].as_i64().expect("pid");
- let windows = launch.structured()["windows"].as_array().cloned().unwrap_or_default();
- let Some(wid) = windows.first().and_then(|w| w["window_id"].as_u64()) else {
- eprintln!("[dispatch] TextEdit opened no window — skipping");
- return;
- };
-
- // Find the AXTextArea.
- let state = driver.call("get_window_state",
- serde_json::json!({ "pid": pid, "window_id": wid, "capture_mode": "ax" }));
- let el = state.structured()["elements"].as_array().and_then(|els| {
- els.iter().find(|e| e["role"] == "AXTextArea").and_then(|e| e["element_index"].as_u64())
- });
- let Some(el) = el else {
- eprintln!("[dispatch] no AXTextArea in TextEdit (AX permission?) — skipping");
- return;
- };
-
- let typed = driver.call("type_text", serde_json::json!({
- "pid": pid, "window_id": wid, "element_index": el,
- "text": "ladder", "delivery_mode": "background"
- }));
- assert!(!typed.is_error(), "type_text errored: {}", typed.text());
- assert_eq!(typed.path(), Some("ax"), "native Cocoa field should land via AX: {}", typed.text());
- assert_eq!(typed.verified(), Some(true), "AX write should read back as verified: {}", typed.text());
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_focus_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_focus_test.rs
deleted file mode 100644
index c6d6eda124..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_focus_test.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-//! Integration test: verify that background automation does NOT steal focus.
-//!
-//! Test strategy:
-//! 1. Open a "focus check window" (Terminal) and confirm it is focused.
-//! 2. Start a cua-driver MCP server (via the shared `McpDriver` testkit).
-//! 3. Send automation actions (click, type_text) to Calculator (a different app).
-//! 4. After each action, verify the Terminal window is STILL the active window.
-//!
-//! Requires: macOS, Calculator (com.apple.calculator), Accessibility permission,
-//! and a built `cua-driver` (`cargo build` first).
-//!
-//! Run with: cargo test --test focus_check_test focus_not_stolen -- --ignored --nocapture
-
-#[cfg(target_os = "macos")]
-mod macos_focus_tests {
- use cua_driver_testkit::{Driver, McpDriver};
- use std::process::Command;
- use std::thread;
- use std::time::Duration;
-
- /// Get the bundle ID of the current frontmost app via osascript.
- fn frontmost_bundle_id() -> String {
- let out = Command::new("osascript")
- .arg("-e")
- .arg(r#"tell application "System Events" to bundle identifier of first application process whose frontmost is true"#)
- .output()
- .expect("osascript");
- String::from_utf8_lossy(&out.stdout).trim().to_owned()
- }
-
- /// Bring Terminal to the front (our "focus check window").
- fn focus_terminal() {
- let _ = Command::new("osascript")
- .arg("-e")
- .arg(r#"tell application "Terminal" to activate"#)
- .output();
- thread::sleep(Duration::from_millis(300));
- }
-
- /// Open Calculator in background.
- fn open_calculator_background() {
- let _ = Command::new("open")
- .args(["-g", "-b", "com.apple.calculator"])
- .output();
- thread::sleep(Duration::from_secs(1));
- }
-
- fn find_calculator_pid(driver: &mut McpDriver) -> Option<i32> {
- let resp = driver.call("list_apps", serde_json::json!({}));
- // Use structuredContent.apps array (preferred over text parsing).
- if let Some(apps) = resp.structured()["apps"].as_array() {
- for app in apps {
- let bundle = app["bundle_id"].as_str().unwrap_or("");
- let name = app["name"].as_str().unwrap_or("");
- if bundle.contains("calculator") || name.eq_ignore_ascii_case("calculator") {
- if let Some(pid) = app["pid"].as_i64() {
- return Some(pid as i32);
- }
- }
- }
- }
- // Fallback: parse text content for older binary versions.
- for line in resp.text().lines() {
- if line.contains("com.apple.calculator") || line.contains("Calculator") {
- if let Some(pid_str) = line.split("(pid ").nth(1).and_then(|s| s.split(')').next()) {
- return pid_str.trim().parse().ok();
- }
- }
- }
- None
- }
-
- #[test]
- #[ignore] // Run explicitly: cargo test --test focus_check_test focus_not_stolen -- --ignored --nocapture
- fn focus_not_stolen_during_calculator_click() {
- // Setup: open Calculator in background, bring Terminal to front.
- open_calculator_background();
- focus_terminal();
-
- let initial_focus = frontmost_bundle_id();
- println!("Initial focus: {}", initial_focus);
-
- // Precondition: the decoy (Terminal) must REALLY be the frontmost,
- // non-harness window before we touch the background app. Without this
- // guard the test passes vacuously: if `focus_terminal()` silently
- // failed (Terminal not installed / activation blocked) and Calculator
- // were frontmost instead, every "focus unchanged" assertion below would
- // still hold — even though the harness owns the foreground, which is
- // exactly the regression these tests exist to catch. Mirrors the
- // sentinel-is-up precondition the Windows background tests get for free
- // from the focus-monitor-win pid/hwnd files.
- assert!(
- !initial_focus.is_empty()
- && !initial_focus.eq_ignore_ascii_case("com.apple.calculator"),
- "decoy precondition failed: frontmost app is {initial_focus:?}, expected a \
- non-harness control window (Terminal) to hold the foreground before the \
- background action. Calculator (the harness) must NOT be frontmost, otherwise \
- the no-focus-steal assertions below are vacuous."
- );
-
- // Start the MCP driver (skips if the binary isn't built).
- let Some(mut driver) = McpDriver::spawn() else { return };
-
- // Find Calculator.
- let calc_pid = match find_calculator_pid(&mut driver) {
- Some(p) => p,
- None => {
- eprintln!("Calculator not found in running apps");
- return;
- }
- };
- println!("Calculator pid: {}", calc_pid);
-
- // Get Calculator's window.
- let resp = driver.call("list_windows", serde_json::json!({ "pid": calc_pid }));
- let windows = resp.structured()["windows"].as_array().expect("windows array");
- if windows.is_empty() {
- eprintln!("No windows for Calculator");
- return;
- }
- let window_id = windows[0]["window_id"].as_u64().unwrap() as u32;
- println!("Calculator window_id: {}", window_id);
-
- // Walk AX tree.
- let resp = driver.call(
- "get_window_state",
- serde_json::json!({ "pid": calc_pid, "window_id": window_id, "capture_mode": "ax" }),
- );
- println!(
- "get_window_state: {}",
- resp.text().chars().take(200).collect::<String>()
- );
-
- // Verify focus hasn't been stolen yet.
- let focus_after_get = frontmost_bundle_id();
- println!("Focus after get_window_state: {}", focus_after_get);
- assert_eq!(
- focus_after_get, initial_focus,
- "get_window_state STOLE FOCUS! Was: {}, now: {}", initial_focus, focus_after_get
- );
-
- // Click element_index 1 (a Calculator button supporting AXPress; [0] is
- // the AXWindow itself, which only raises).
- let resp = driver.call(
- "click",
- serde_json::json!({ "pid": calc_pid, "window_id": window_id, "element_index": 1 }),
- );
- println!("click result: {}", resp.text());
- thread::sleep(Duration::from_millis(200));
-
- // CRITICAL: verify focus was not stolen.
- let focus_after_click = frontmost_bundle_id();
- println!("Focus after click: {}", focus_after_click);
- assert_eq!(
- focus_after_click, initial_focus,
- "click() STOLE FOCUS! Expected {} to remain focused, got {}", initial_focus, focus_after_click
- );
-
- // type_text also must not steal focus.
- let resp = driver.call("type_text", serde_json::json!({ "pid": calc_pid, "text": "5" }));
- println!("type_text result: {}", resp.text());
- thread::sleep(Duration::from_millis(200));
- let focus_after_type = frontmost_bundle_id();
- println!("Focus after type_text: {}", focus_after_type);
- assert_eq!(
- focus_after_type, initial_focus,
- "type_text() STOLE FOCUS! Expected {} to remain focused, got {}", initial_focus, focus_after_type
- );
-
- println!("✅ Focus was NOT stolen by click or type_text. Background automation confirmed.");
- }
-}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/modality_input_e2e_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/modality_input_e2e_test.rs
deleted file mode 100644
index 006bde69a1..0000000000
--- a/libs/cua-driver/rust/crates/cua-driver/tests/modality_input_e2e_test.rs
+++ /dev/null
@@ -1,579 +0,0 @@
-//! End-to-end Windows test for the **unified background input interface**:
-//! a caller targets an app and plays click/key actions WITHOUT knowing the
-//! app's internals (Electron/Chromium, Tauri/WebView2, classic Win32) and
-//! WITHOUT the target window ever being raised to the foreground.
-//!
-//! Verified two ways per action:
-//! 1. The tool succeeds in the DEFAULT dispatch mode — no
-//! `background_unavailable` error, no `dispatch:"foreground"` needed.
-//! 2. The `focus-monitor-win` sentinel records ZERO foreground losses across
-//! the action == the target window was not z-raised over the user's
-//! window (same oracle as `harness_bg_modality_test`).
-//!
-//! ## Process hygiene
-//! The driver, target app, and sentinel are all owned by the shared testkit
-//! `ChildReaper` (via `McpDriver`), which on Windows assigns them to a
-//! kill-on-close Job Object — the OS reaps the whole tree when the test process
-//! exits for ANY reason (normal, panic, SIGKILL), so no orphaned windows or
-//! held ports. Broker-spawned window pids (packaged apps / Electron) are
-//! tree-killed via `reaper().track_pid`.
-//!
-//! Targets (repo-local harness apps staged by `tests/fixtures/build/windows.ps1`):
-//! - Electron (Chromium content) — `CuaTestHarness.Electron.exe`.
-//! - Tauri (WebView2 content) — `CuaTestHarness.Tauri.exe`.
-//! - Win32 baseline — `notepad.exe`.
-//! Override with `HARNESS_ELECTRON_EXE` / `HARNESS_TAURI_EXE`
-//! (or legacy `CUA_ELECTRON_EXE` / `CUA_TAURI_EXE`).
-//!
-//! All tests are `#[ignore]` (GUI, real desktop session). Run explicitly,
-//! serially (GUI focus oracle, so never in parallel):
-//! cargo test -p cua-driver --test e2e_windows_bg_input_test -- --ignored --nocapture --test-threads=1
-
-#![cfg(target_os = "windows")]
-
-use std::collections::HashSet;
-use std::fs;
-use std::path::{Path, PathBuf};
-use std::process::{Command, Stdio};
-use std::time::{Duration, Instant};
-
-use cua_driver_testkit::{ax, workspace_root, Driver, McpDriver};
-
-// ── paths ────────────────────────────────────────────────────────────────────
-
-fn focus_monitor_binary() -> PathBuf {
- workspace_root().join("target/debug/focus-monitor-win.exe")
-}
-
-/// Best-effort kill of any prior instance of `exe` by basename, so a leftover
-/// from an earlier (e.g. force-killed) run can't hold the app's fixed HTTP port.
-fn kill_prior_by_name(exe: &Path) {
- if let Some(name) = exe.file_name().and_then(|n| n.to_str()) {
- let _ = Command::new("taskkill")
- .args(["/F", "/T", "/IM", name])
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status();
- }
-}
-
-fn resolve_harness(primary_env: &str, legacy_env: &str, rel_path: &str) -> Option<PathBuf> {
- for env_var in [primary_env, legacy_env] {
- if let Ok(p) = std::env::var(env_var) {
- let pb = PathBuf::from(p);
- if pb.exists() {
- return Some(pb);
- }
- }
- }
- let pb = workspace_root().join(rel_path);
- pb.exists().then_some(pb)
-}
-fn electron_exe() -> Option<PathBuf> {
- resolve_harness(
- "HARNESS_ELECTRON_EXE",
- "CUA_ELECTRON_EXE",
- "test-apps/harness-electron/CuaTestHarness.Electron.exe",
- )
-}
-fn tauri_exe() -> Option<PathBuf> {
- resolve_harness(
- "HARNESS_TAURI_EXE",
- "CUA_TAURI_EXE",
- "test-apps/harness-tauri/CuaTestHarness.Tauri.exe",
- )
-}
-
-fn loss_file() -> PathBuf {
- std::env::temp_dir().join("focus_monitor_losses.txt")
-}
-fn key_loss_file() -> PathBuf {
- std::env::temp_dir().join("focus_monitor_key_losses.txt")
-}
-fn focus_pid_file() -> PathBuf {
- std::env::temp_dir().join("focus_monitor_pid.txt")
-}
-fn focus_hwnd_file() -> PathBuf {
- std::env::temp_dir().join("focus_monitor_hwnd.txt")
-}
-fn read_count(p: &Path) -> u32 {
- fs::read_to_string(p)
- .ok()
- .and_then(|s| s.trim().parse::<u32>().ok())
- .unwrap_or(0)
-}
-fn read_focus_hwnd() -> u64 {
- fs::read_to_string(focus_hwnd_file())
- .ok()
- .and_then(|s| s.trim().parse::<u64>().ok())
- .unwrap_or(0)
-}
-
-fn window_ids(driver: &mut McpDriver) -> HashSet<u64> {
- let r = driver.call("list_windows", serde_json::json!({}));
- r.structured()["windows"]
- .as_array()
- .map(|a| a.iter().filter_map(|w| w["window_id"].as_u64()).collect())
- .unwrap_or_default()
-}
-
-fn gui_required() -> bool {
- std::env::var("CUA_REQUIRE_GUI")
- .ok()
- .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
- .unwrap_or(false)
-}
-
-fn skip_desktop(context: &str, reason: String) -> bool {
- let msg = format!("{context}: {reason}; skipping GUI modality e2e");
- if gui_required() {
- panic!("{msg}");
- }
- eprintln!("{msg}");
- false
-}
-
-fn require_seedable_desktop(context: &str) -> bool {
- let state = platform_windows::diagnostics::desktop_state();
- if state.session_id == Some(0) {
- return skip_desktop(
- context,
- format!(
- "running in Windows Session 0 ({}) - re-run from RDP/console/scheduled task in user session",
- state.summary()
- ),
- );
- }
- if !state.has_process_window_station {
- return skip_desktop(
- context,
- format!("no attached process window station ({})", state.summary()),
- );
- }
- if !state.input_desktop_is_default() {
- return skip_desktop(
- context,
- format!(
- "input desktop is not the user Default desktop ({})",
- state.summary()
- ),
- );
- }
- true
-}
-
-fn require_focus_monitor_foreground(context: &str, expected_hwnd: u64) -> bool {
- let deadline = Instant::now() + Duration::from_secs(2);
- loop {
- let state = platform_windows::diagnostics::desktop_state();
- if state.foreground_hwnd == Some(expected_hwnd as usize) {
- return true;
- }
- if Instant::now() >= deadline {
- return skip_desktop(
- context,
- format!(
- "focus monitor did not become foreground (expected HWND 0x{expected_hwnd:x}; {})",
- state.summary()
- ),
- );
- }
- std::thread::sleep(Duration::from_millis(100));
- }
-}
-
-// ── fixture ───────────────────────────────────────────────────────────────────
-
-struct E2eFixture {
- driver: McpDriver, // owns + reaps target+sentinel+driver on drop
- pid: u32,
- wid: u64,
-}
-
-/// Launch order: driver (no window) → snapshot windows → app → discover the
-/// app's NEW window (works for multi-process apps like Electron whose window
-/// belongs to a child pid) → sentinel (grabs foreground, pushing the app to
-/// the background) → reset counters.
-fn setup(target_exe: &Path, _title_hint: &str) -> Option<E2eFixture> {
- if !require_seedable_desktop("modality_input_e2e_test") {
- return None;
- }
-
- let fm_bin = focus_monitor_binary();
- if !fm_bin.exists() {
- eprintln!("[e2e] focus-monitor-win.exe not built — skipping");
- return None;
- }
- if target_exe.is_absolute() && !target_exe.exists() {
- eprintln!("[e2e] target {target_exe:?} missing — skipping");
- return None;
- }
-
- // Defensive: clear any leftover instance holding the app's fixed port.
- kill_prior_by_name(target_exe);
- let _ = fs::write(loss_file(), "0");
- let _ = fs::write(key_loss_file(), "0");
- let _ = fs::remove_file(focus_pid_file());
- let _ = fs::remove_file(focus_hwnd_file());
-
- // 1. Driver (daemon, no visible window) — spawned + initialized by the testkit.
- let mut driver = McpDriver::spawn()?;
-
- // 2. Snapshot existing windows, then launch the target app into the reaper.
- let before = window_ids(&mut driver);
- if driver
- .reaper()
- .spawn(
- Command::new(target_exe)
- .stdout(Stdio::null())
- .stderr(Stdio::null()),
- )
- .is_err()
- {
- eprintln!("[e2e] target spawn failed"); // driver drops → kills itself
- return None;
- }
-
- // 3. Discover the app's NEW window (its pid may be a child of the launched
- // process — Electron/WebView2 are multi-process).
- let deadline = Instant::now() + Duration::from_secs(15);
- let mut found: Option<(u32, u64)> = None;
- while Instant::now() < deadline {
- let r = driver.call("list_windows", serde_json::json!({}));
- if let Some(arr) = r.structured()["windows"].as_array() {
- for w in arr {
- let Some(wid) = w["window_id"].as_u64() else {
- continue;
- };
- let pid = w["pid"].as_u64().unwrap_or(0) as u32;
- let title = w["title"].as_str().unwrap_or("");
- if !before.contains(&wid) && !title.is_empty() && pid != 0 {
- found = Some((pid, wid));
- break;
- }
- }
- }
- if found.is_some() {
- break;
- }
- std::thread::sleep(Duration::from_millis(500));
- }
- let (pid, wid) = match found {
- Some(p) => p,
- None => {
- eprintln!("[e2e] app window never appeared — skipping");
- return None;
- }
- };
- // The window's process is often broker-spawned (packaged apps, Electron),
- // i.e. NOT our direct child. track_pid job-assigns it (hard-kill safety) and
- // tree-kills it on teardown so it can't orphan.
- driver.reaper().track_pid(pid);
-
- // 4. Sentinel grabs foreground; app drops to z+1 (the background target).
- if driver
- .reaper()
- .spawn(
- Command::new(&fm_bin)
- .stdout(Stdio::null())
- .stderr(Stdio::null()),
- )
- .is_err()
- {
- eprintln!("[e2e] sentinel spawn failed — skipping");
- return None;
- }
- let sdeadline = Instant::now() + Duration::from_secs(10);
- loop {
- let ok = read_count(&focus_pid_file()) != 0 && read_focus_hwnd() != 0;
- if ok {
- break;
- }
- if Instant::now() > sdeadline {
- eprintln!("[e2e] sentinel never published — skipping");
- return None;
- }
- std::thread::sleep(Duration::from_millis(100));
- }
- std::thread::sleep(Duration::from_millis(400));
- if !require_focus_monitor_foreground("modality_input_e2e_test sentinel", read_focus_hwnd()) {
- return None;
- }
- let _ = fs::write(loss_file(), "0");
- let _ = fs::write(key_loss_file(), "0");
-
- Some(E2eFixture { driver, pid, wid })
-}
-
-// ── DOM registration oracle (trycua test apps serve an event log on 6769) ─────
-
-const APP_API: &str = "http://127.0.0.1:6769";
-
-fn http_reset() {
- let _ = Command::new("curl.exe")
- .args(["-s", "-m", "3", "-X", "POST", &format!("{APP_API}/reset")])
- .stdout(Stdio::null())
- .stderr(Stdio::null())
- .status();
-}
-/// Returns the `/events` body, or None if the app isn't serving the API.
-fn http_events() -> Option<String> {
- let out = Command::new("curl.exe")
- .args(["-s", "-m", "3", &format!("{APP_API}/events")])
- .output()
- .ok()?;
- if !out.status.success() {
- return None;
- }
- let body = String::from_utf8_lossy(&out.stdout).into_owned();
- if body.trim_start().starts_with('[') {
- Some(body)
- } else {
- None
- }
-}
-/// True if the event log recorded at least one DOM event since the last reset.
-fn registered_since_reset() -> Option<bool> {
- http_events().map(|b| b.trim() != "[]" && !b.trim().is_empty())
-}
-
-fn foreground_pid() -> u32 {
- use windows::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
- unsafe {
- let h = GetForegroundWindow();
- let mut pid = 0u32;
- GetWindowThreadProcessId(h, Some(&mut pid));
- pid
- }
-}
-
-/// The reliable "no z-raise / no foreground steal" oracle, independent of the
-/// machine's foreground-lock setting: after acting on a BACKGROUND target, the
-/// target's process must never become the foreground window. Polls for ~1.2s
-/// to also catch async self-reactivation (Chromium).
-fn assert_target_stays_background<F: FnOnce()>(label: &str, target_pid: u32, action: F) {
- let user_pid = read_count(&focus_pid_file());
- let fg_before = foreground_pid();
- if fg_before == target_pid {
- eprintln!("[e2e] WARN {label}: target pid {target_pid} was already foreground before the action (setup couldn't background it)");
- }
- action();
- let deadline = Instant::now() + Duration::from_millis(1200);
- let mut stole = false;
- let mut last_fg = fg_before;
- while Instant::now() < deadline {
- last_fg = foreground_pid();
- if last_fg == target_pid {
- stole = true;
- break;
- }
- std::thread::sleep(Duration::from_millis(80));
- }
- assert!(
- !stole,
- "{label}: target pid {target_pid} BECAME the foreground window — z-raise / foreground steal. \
- (expected user pid {user_pid}, fg_before={fg_before})"
- );
- println!("✅ {label}: target pid {target_pid} stayed background (foreground pid={last_fg}, user={user_pid})");
-}
-
-/// Shared body: default-mode left click into a webview target.
-fn webview_click_case(label: &str, exe: PathBuf) {
- let mut fx = match setup(&exe, "") {
- Some(f) => f,
- None => return,
- };
- let (pid, wid) = (fx.pid, fx.wid);
- let snap = fx.driver.call(
- "get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "ax"}),
- );
- let elem = ax::element_index_containing(snap.text(), "button")
- .or_else(|| ax::element_index_containing(snap.text(), "click"));
-
- http_reset();
- let mut delivered = String::new();
- let mut errored = false;
- let mut needs_foreground = false;
- assert_target_stays_background(label, pid, || {
- let args = match elem {
- Some(idx) => {
- serde_json::json!({"pid": pid as i64, "window_id": wid, "element_index": idx})
- }
- None => serde_json::json!({"pid": pid as i64, "window_id": wid, "x": 200, "y": 200}),
- };
- let last = fx.driver.call("click", args);
- errored = last.is_error();
- needs_foreground = last.text().contains("background_unavailable");
- delivered = last.text().to_string();
- });
- assert!(!errored, "{label}: default-mode click errored: {delivered}");
- assert!(
- !needs_foreground,
- "{label}: click should not need dispatch:foreground, got {delivered:?}"
- );
- // Delivery is confirmed by the driver's own ✅ result (UIA Invoke fires the
- // element's default action / DOM `click`). The /events pointer-log is info
- // only — it does NOT capture accessibility-driven UIA Invoke, so a `[]`
- // there is expected for the UIA path. The hard invariant is no-foreground-steal.
- std::thread::sleep(Duration::from_millis(300));
- let reg = registered_since_reset()
- .map(|b| b.to_string())
- .unwrap_or_else(|| "n/a".into());
- println!("{label}: delivered={delivered:?} pointer-events-logged={reg}");
-}
-
-// ── tests ─────────────────────────────────────────────────────────────────────
-
-#[test]
-#[ignore]
-fn e2e_electron_background_click_no_z_raise() {
- let Some(exe) = electron_exe() else {
- eprintln!("[e2e] no electron app — skipping");
- return;
- };
- webview_click_case("electron click (default dispatch)", exe);
-}
-
-#[test]
-#[ignore]
-fn e2e_tauri_background_click_no_z_raise() {
- let Some(exe) = tauri_exe() else {
- eprintln!("[e2e] no tauri app — skipping");
- return;
- };
- webview_click_case("tauri click (default dispatch)", exe);
-}
-
-#[test]
-#[ignore]
-fn e2e_win32_notepad_background_click_no_z_raise() {
- let mut fx = match setup(Path::new(r"C:\Windows\System32\notepad.exe"), "") {
- Some(f) => f,
- None => return,
- };
- let (pid, wid) = (fx.pid, fx.wid);
- let mut last_text = String::new();
- let mut errored = false;
- assert_target_stays_background("notepad click (default dispatch)", pid, || {
- let r = fx.driver.call(
- "click",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "x": 120, "y": 120}),
- );
- errored = r.is_error();
- last_text = r.text().to_string();
- });
- assert!(!errored, "notepad click errored: {last_text}");
- println!("notepad click result: {last_text:?}");
-}
-
-/// Electron right-click (pen-barrel injection): no raise. Pen→right promotion
-/// is app-dependent, so landing is best-effort; the hard invariant is no
-/// z-raise + no background_unavailable.
-#[test]
-#[ignore]
-fn e2e_electron_background_right_click_no_z_raise() {
- let Some(exe) = electron_exe() else {
- eprintln!("[e2e] no electron app — skipping");
- return;
- };
- let mut fx = match setup(&exe, "") {
- Some(f) => f,
- None => return,
- };
- let (pid, wid) = (fx.pid, fx.wid);
- let mut last_text = String::new();
- assert_target_stays_background("electron right-click (default dispatch)", pid, || {
- let r = fx.driver.call(
- "click",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "x": 200, "y": 200, "button": "right"}),
- );
- last_text = r.text().to_string();
- });
- println!("electron right-click result: {last_text:?}");
-}
-
-/// Electron TEXT typing: focus a field, then type — must register the text in
-/// the DOM AND never steal foreground / move the cursor.
-#[test]
-#[ignore]
-fn e2e_electron_background_type_text_no_z_raise() {
- let Some(exe) = electron_exe() else {
- eprintln!("[e2e] no electron app — skipping");
- return;
- };
- let mut fx = match setup(&exe, "") {
- Some(f) => f,
- None => return,
- };
- let (pid, wid) = (fx.pid, fx.wid);
-
- // Focus a text field if the page exposes one (so the chars have a sink).
- let snap = fx.driver.call(
- "get_window_state",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "capture_mode": "ax"}),
- );
- let field = ax::element_index_containing(snap.text(), "edit")
- .or_else(|| ax::element_index_containing(snap.text(), "text"))
- .or_else(|| ax::element_index_containing(snap.text(), "input"));
- if let Some(idx) = field {
- let _ = fx.driver.call(
- "click",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "element_index": idx}),
- );
- std::thread::sleep(Duration::from_millis(200));
- }
-
- http_reset();
- let mut last_text = String::new();
- let mut errored = false;
- assert_target_stays_background("electron type_text (default dispatch)", pid, || {
- let r = fx.driver.call(
- "type_text",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "text": "cuatest"}),
- );
- errored = r.is_error();
- last_text = r.text().to_string();
- });
- assert!(!errored, "type_text errored: {last_text}");
- std::thread::sleep(Duration::from_millis(300));
- if let Some(reg) = registered_since_reset() {
- println!("electron type_text: registered={reg} result={last_text:?}");
- } else {
- println!("electron type_text result: {last_text:?}");
- }
-}
-
-/// Electron key-combo (Ctrl+A): background Chromium key-combos are currently
-/// outside the safe delivery capability. The contract is an explicit refusal,
-/// with no z-raise or silent partial chord.
-#[test]
-#[ignore]
-fn e2e_electron_background_keycombo_no_z_raise() {
- let Some(exe) = electron_exe() else {
- eprintln!("[e2e] no electron app — skipping");
- return;
- };
- let mut fx = match setup(&exe, "") {
- Some(f) => f,
- None => return,
- };
- let (pid, wid) = (fx.pid, fx.wid);
- let mut last_text = String::new();
- let mut errored = false;
- assert_target_stays_background("electron Ctrl+A (default dispatch)", pid, || {
- let r = fx.driver.call(
- "press_key",
- serde_json::json!({"pid": pid as i64, "window_id": wid, "key": "a", "modifiers": ["control"]}),
- );
- errored = r.is_error();
- last_text = r.text().to_string();
- });
- // W2: refuse honestly instead of claiming delivery through a route that
- // cannot preserve the background/no-focus contract for Chromium.
- assert!(
- !errored && last_text.contains("Background delivery is not available"),
- "Ctrl+A must return a structured background capability refusal, got: {last_text:?}"
- );
- println!("electron Ctrl+A refused honestly: {last_text:?}");
-}
diff --git a/libs/cua-driver/scripts/_install-local-rust.sh b/libs/cua-driver/scripts/_install-local-rust.sh
index 69f1bfd2bd..dd6c9d6d3d 100755
--- a/libs/cua-driver/scripts/_install-local-rust.sh
+++ b/libs/cua-driver/scripts/_install-local-rust.sh
@@ -71,6 +71,7 @@ NORMAL=$(tput sgr0 2>/dev/null || true)
RED=$(tput setaf 1 2>/dev/null || true)
GREEN=$(tput setaf 2 2>/dev/null || true)
BLUE=$(tput setaf 4 2>/dev/null || true)
+YELLOW=$(tput setaf 3 2>/dev/null || true)
if [ "$(id -u)" -eq 0 ] || [ -n "${SUDO_USER:-}" ]; then
echo "${RED}Error: do not run this script with sudo or as root.${NORMAL}"
@@ -307,6 +308,32 @@ ensure_local_signing_identity() {
printf -- '-'
}
+# Keychain-backed codesign can wait forever for a GUI authorization prompt when
+# install-local is launched from a headless shell. Keep the install bounded;
+# ad-hoc signing remains a usable fallback for local development.
+codesign_bounded() {
+ local timeout_seconds="$1"
+ shift
+ if command -v gtimeout >/dev/null 2>&1; then
+ gtimeout "$timeout_seconds" codesign "$@"
+ elif command -v perl >/dev/null 2>&1; then
+ perl -e 'alarm shift; exec @ARGV' "$timeout_seconds" codesign "$@"
+ else
+ codesign "$@"
+ fi
+}
+
+clean_partial_bundle_signature() {
+ local app="$1"
+ # A certificate-backed codesign killed by the timeout can leave both a
+ # partial resource seal and `<executable>.cstemp`. Signing over that state
+ # seals the transient file; when the interrupted signer removes it later,
+ # the fallback bundle becomes invalid. Always restart fallback signing from
+ # the unsigned staged bundle.
+ rm -rf "$app/Contents/_CodeSignature"
+ find "$app" -type f -name '*.cstemp' -delete
+}
+
# --- macOS: wrap the binary in CuaDriver.app for a stable TCC identity ---
#
# TCC keys Accessibility / Screen-Recording grants on the bundle
@@ -339,27 +366,57 @@ if [ "$OS" = "Darwin" ]; then
plutil -replace CFBundleVersion -string "$VERSION_TAG" \
"$APP_STAGE/Contents/Info.plist" 2>/dev/null || true
fi
- # Install to /Applications (user-writable for admins; no sudo — same
- # as install.sh). Replace any prior bundle wholesale.
- rm -rf "$APP_DEST"
- ditto "$APP_STAGE" "$APP_DEST"
- # Re-sign the whole bundle (--deep covers the inner binary). Required on
+ # Sign the staged bundle before touching the live installation. Required on
# macOS 26+ where Taskgated rejects a copied binary's stale signature.
# Prefer the STABLE self-signed identity so TCC grants survive rebuilds;
- # fall back to ad-hoc (which works but resets grants on the next rebuild).
+ # never downgrade an existing certificate-signed installation to ad-hoc,
+ # because that would invalidate its working TCC grants.
if command -v codesign >/dev/null 2>&1; then
SIGN_ID="$(ensure_local_signing_identity)"
if [ "$SIGN_ID" != "-" ] \
- && codesign --force --deep --sign "$SIGN_ID" "$APP_DEST" 2>/dev/null; then
- echo "${GREEN}signed $APP_DEST with a stable local identity — TCC grants survive future install-local rebuilds${NORMAL}"
- elif codesign --force --deep --sign - "$APP_DEST" 2>/dev/null; then
- if [ "$SIGN_ID" != "-" ]; then
- echo "${YELLOW}note: stable-identity signing failed; signed ad-hoc instead (Accessibility/Screen Recording will reset on the next rebuild)${NORMAL}" >&2
- fi
+ && codesign_bounded 20 --force --deep --sign "$SIGN_ID" "$APP_STAGE" 2>/dev/null; then
+ echo "${GREEN}signed staged app with a stable local identity — TCC grants survive future install-local rebuilds${NORMAL}"
+ elif [ -d "$APP_DEST" ] \
+ && codesign -d -r- "$APP_DEST" 2>&1 | grep -q 'certificate leaf'; then
+ echo "${RED}Error: stable signing failed; preserving the existing certificate-signed $APP_DEST and its TCC grants.${NORMAL}" >&2
+ echo "Unlock/authorize the login-keychain signing key, then rerun install-local." >&2
+ exit 1
else
- echo "${YELLOW}warning: codesign of $APP_DEST failed; first run may hit a Gatekeeper/Taskgated prompt${NORMAL}" >&2
+ clean_partial_bundle_signature "$APP_STAGE"
+ if codesign_bounded 20 --force --deep --sign - "$APP_STAGE" 2>/dev/null; then
+ if [ "$SIGN_ID" != "-" ]; then
+ echo "${YELLOW}note: stable-identity signing failed; signed ad-hoc instead (Accessibility/Screen Recording will reset on the next rebuild)${NORMAL}" >&2
+ fi
+ else
+ clean_partial_bundle_signature "$APP_STAGE"
+ echo "${RED}Error: codesign of staged CuaDriver.app failed; live installation was not changed.${NORMAL}" >&2
+ exit 1
+ fi
+ fi
+ if ! codesign --verify --deep --strict "$APP_STAGE" 2>/dev/null; then
+ echo "${RED}Error: staged CuaDriver.app failed signature verification; live installation was not changed.${NORMAL}" >&2
+ exit 1
fi
fi
+
+ # Install to /Applications (user-writable for admins; no sudo — same as
+ # install.sh). Keep the prior bundle available until the copy completes so
+ # an interrupted install cannot leave a corrupt live app.
+ APP_BACKUP="${APP_DEST}.install-backup.$$"
+ rm -rf "$APP_BACKUP"
+ if [ -d "$APP_DEST" ]; then
+ mv "$APP_DEST" "$APP_BACKUP"
+ fi
+ if ditto "$APP_STAGE" "$APP_DEST"; then
+ rm -rf "$APP_BACKUP"
+ else
+ rm -rf "$APP_DEST"
+ if [ -d "$APP_BACKUP" ]; then
+ mv "$APP_BACKUP" "$APP_DEST"
+ fi
+ echo "${RED}Error: failed to install CuaDriver.app; restored the previous bundle.${NORMAL}" >&2
+ exit 1
+ fi
echo "${GREEN}installed $APP_DEST${NORMAL}"
# --- Clear a TCC grant pinned to a PREVIOUS signing identity -----------
diff --git a/libs/cua-driver/scripts/sync-vm-worktree.sh b/libs/cua-driver/scripts/sync-vm-worktree.sh
index c110abab30..cccc9e0966 100755
--- a/libs/cua-driver/scripts/sync-vm-worktree.sh
+++ b/libs/cua-driver/scripts/sync-vm-worktree.sh
@@ -50,20 +50,25 @@ remote_os="${REMOTE_OS:-posix}"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../../.." && pwd)"
+source_sha="$(git -C "$repo_root" rev-parse HEAD)"
artifact_root="$repo_root/libs/cua-driver/docs/vm-artifacts"
target_slug="$(printf '%s' "$target" | tr -c 'A-Za-z0-9_.-' '_')"
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
exclude_args=(
- --exclude=.git/
+ # A linked worktree stores `.git` as a file, while a normal checkout stores
+ # it as a directory. Neither host-specific form belongs on a verification VM.
+ --exclude=.git
--exclude=.DS_Store
--exclude='._*'
--exclude=target/
+ --exclude=libs/cua-driver/rust/test-apps/
--exclude=node_modules/
--exclude=.venv/
--exclude=__pycache__/
--exclude='*.pyc'
--exclude=dist/
+ --exclude=vm-out/
)
tar_exclude_args=(
@@ -71,11 +76,13 @@ tar_exclude_args=(
--exclude ./.DS_Store
--exclude '._*'
--exclude ./target
+ --exclude ./libs/cua-driver/rust/test-apps
--exclude ./node_modules
--exclude ./.venv
--exclude '*/__pycache__'
--exclude '*.pyc'
--exclude ./dist
+ --exclude ./vm-out
)
remote_mkdir() {
@@ -102,8 +109,37 @@ push_rsync() {
push_tar() {
remote_mkdir
- COPYFILE_DISABLE=1 tar "${tar_exclude_args[@]}" -czf - -C "$repo_root" . \
- | "$rsync_ssh" "$target" "tar -xzf - -C \"$remote_dir\""
+ remote_path=${remote_dir/#\~/'$HOME'}
+ COPYFILE_DISABLE=1 tar --no-xattrs "${tar_exclude_args[@]}" -czf - -C "$repo_root" . \
+ | "$rsync_ssh" "$target" "tar -xzf - -C \"$remote_path\""
+}
+
+write_source_marker() {
+ case "$remote_os" in
+ windows)
+ "$rsync_ssh" "$target" \
+ "powershell -NoProfile -Command \"Set-Content -NoNewline -Path '$remote_dir/.cua-e2e-source-sha' -Value '$source_sha'\""
+ ;;
+ posix)
+ marker_dir=${remote_dir/#\~/"\$HOME"}
+ printf '%s\n' "$source_sha" \
+ | "$rsync_ssh" "$target" "mkdir -p $marker_dir && tee $marker_dir/.cua-e2e-source-sha >/dev/null"
+ ;;
+ esac
+}
+
+ensure_remote_runtime_dirs() {
+ case "$remote_os" in
+ windows)
+ "$rsync_ssh" "$target" \
+ "powershell -NoProfile -Command \"New-Item -ItemType Directory -Force '$remote_dir/libs/cua-driver/rust/test-apps' | Out-Null\""
+ ;;
+ posix)
+ remote_path=${remote_dir/#\~/'$HOME'}
+ "$rsync_ssh" "$target" \
+ "mkdir -p \"$remote_path/libs/cua-driver/rust/test-apps\""
+ ;;
+ esac
}
pull_artifacts_rsync() {
@@ -111,7 +147,8 @@ pull_artifacts_rsync() {
}
pull_artifacts_tar() {
- "$rsync_ssh" "$target" "tar -czf - -C \"$remote_dir/$remote_artifact_dir\" ." \
+ remote_path=${remote_dir/#\~/'$HOME'}
+ "$rsync_ssh" "$target" "tar -czf - -C \"$remote_path/$remote_artifact_dir\" ." \
| tar -xzf - -C "$dest"
}
@@ -121,8 +158,9 @@ pull_code_rsync() {
}
pull_code_tar() {
- "$rsync_ssh" "$target" "tar -czf - -C \"$remote_dir\" ." \
- | COPYFILE_DISABLE=1 tar "${tar_exclude_args[@]}" -xzf - -C "$repo_root"
+ remote_path=${remote_dir/#\~/'$HOME'}
+ "$rsync_ssh" "$target" "tar -czf - -C \"$remote_path\" ." \
+ | COPYFILE_DISABLE=1 tar --no-xattrs "${tar_exclude_args[@]}" -xzf - -C "$repo_root"
}
case "$mode" in
@@ -132,6 +170,8 @@ case "$mode" in
tar) push_tar ;;
*) echo "SYNC_TRANSPORT must be rsync or tar, got: $transport" >&2; exit 2 ;;
esac
+ ensure_remote_runtime_dirs
+ write_source_marker
;;
pull-artifacts)
diff --git a/libs/cua-driver/tests/fixtures/shared/scenarios.json b/libs/cua-driver/tests/fixtures/shared/scenarios.json
index 564f7ba896..f1f4276c87 100644
--- a/libs/cua-driver/tests/fixtures/shared/scenarios.json
+++ b/libs/cua-driver/tests/fixtures/shared/scenarios.json
@@ -187,12 +187,6 @@
"btn-increment",
"btn-reset",
"lbl-counter",
- "calc-1",
- "calc-2",
- "calc-4",
- "calc-plus",
- "calc-equals",
- "calc-display",
"txt-input",
"lbl-input-mirror",
"editor-document",
diff --git a/libs/cua-driver/tests/fixtures/shared/web/index.html b/libs/cua-driver/tests/fixtures/shared/web/index.html
index b1f93c6944..f44e725425 100644
--- a/libs/cua-driver/tests/fixtures/shared/web/index.html
+++ b/libs/cua-driver/tests/fixtures/shared/web/index.html
@@ -7,16 +7,38 @@
:root { color-scheme: light dark; }
body {
font-family: 'Segoe UI', system-ui, sans-serif;
- max-width: 860px;
+ max-width: 980px;
margin: 0 auto;
- padding: 16px;
+ padding: 10px;
}
- fieldset { margin-bottom: 12px; padding: 10px 14px; border-radius: 6px; border: 1px solid #ccc; }
+ h2 { margin: 0 0 2px; }
+ body > p { margin: 0 0 8px; }
+ .harness-grid {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+ align-items: start;
+ }
+ .harness-grid h3 { margin: 8px 0; font-size: 14px; overflow-wrap: anywhere; }
+ fieldset { min-width: 0; margin: 0; padding: 6px 8px; border-radius: 6px; border: 1px solid #ccc; }
legend { font-weight: 600; padding: 0 6px; }
- label { display: inline-block; min-width: 120px; }
- .row { display: flex; align-items: center; gap: 10px; margin: 6px 0; flex-wrap: wrap; }
+ label { display: inline-block; min-width: 90px; }
+ .row { display: flex; align-items: center; gap: 8px; margin: 3px 0; flex-wrap: wrap; }
.mirror, .state { font-family: Consolas, monospace; color: #555; }
- input[type="range"] { width: 280px; }
+ input[type="range"] { width: 180px; }
+ textarea { max-width: 100%; }
+ #drag-source, #drop-target {
+ width: 110px;
+ height: 48px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: white;
+ user-select: none;
+ touch-action: none;
+ }
+ #drag-source { background: #1268d6; }
+ #drop-target { background: #178a38; }
#click-target {
display: inline-block;
padding: 8px 18px;
@@ -33,6 +55,7 @@
<h2 data-cua-id="page-heading">cua-driver Web Harness</h2>
<p data-cua-id="page-marker" class="marker">WEB_HARNESS_MARKER_v1</p>
+ <main class="harness-grid">
<fieldset>
<legend>counter</legend>
<div class="row">
@@ -42,22 +65,11 @@
</div>
</fieldset>
- <fieldset>
- <legend>calculator_task</legend>
- <div class="row">
- <button id="calc-1" data-cua-id="calc-1" aria-label="calc-1 1">1</button>
- <button id="calc-2" data-cua-id="calc-2" aria-label="calc-2 2">2</button>
- <button id="calc-4" data-cua-id="calc-4" aria-label="calc-4 4">4</button>
- <button id="calc-plus" data-cua-id="calc-plus" aria-label="calc-plus plus">+</button>
- <button id="calc-equals" data-cua-id="calc-equals" aria-label="calc-equals equals">=</button>
- <span class="mirror" id="calc-display" data-cua-id="calc-display">display=0</span>
- </div>
- </fieldset>
-
<fieldset>
<legend>text_input</legend>
<div class="row">
- <input type="text" id="txt-input" data-cua-id="txt-input" placeholder="type here" />
+ <input type="text" id="txt-input" data-cua-id="txt-input"
+ aria-label="txt-input" placeholder="type here" />
<span class="mirror" id="lbl-input-mirror" data-cua-id="lbl-input-mirror">mirror=</span>
</div>
</fieldset>
@@ -92,8 +104,8 @@
<fieldset>
<legend>drag_task</legend>
<div class="row">
- <div id="drag-source" data-cua-id="drag-source" aria-label="drag-source" style="position:fixed;left:40px;top:80px;width:220px;height:100px;display:flex;align-items:center;justify-content:center;background:#1268d6;color:white;user-select:none;touch-action:none;z-index:10;">Drag source</div>
- <div id="drop-target" data-cua-id="drop-target" aria-label="drop-target" style="position:fixed;left:520px;top:520px;width:220px;height:100px;display:flex;align-items:center;justify-content:center;background:#178a38;color:white;z-index:10;">Drop target</div>
+ <div id="drag-source" data-cua-id="drag-source" aria-label="drag-source">Drag source</div>
+ <div id="drop-target" data-cua-id="drop-target" aria-label="drop-target">Drop target</div>
<span class="mirror" id="drag-status" data-cua-id="drag-status">drag_status=idle</span>
</div>
</fieldset>
@@ -115,7 +127,8 @@
<fieldset>
<legend>click_target</legend>
<div class="row">
- <span id="click-target" data-cua-id="border-click-target">Click target (left / right / double)</span>
+ <span id="click-target" data-cua-id="border-click-target" role="button"
+ tabindex="0" aria-label="border-click-target">Click target (left / right / double)</span>
</div>
<div class="row">
<span class="mirror" id="lbl-last-action" data-cua-id="lbl-last-action">last_action=none</span>
@@ -157,7 +170,7 @@
<a id="lnk-anchor" data-cua-id="lnk-anchor" href="#section-target">Jump to section</a>
<span class="mirror" id="lbl-nav-state" data-cua-id="lbl-nav-state">hash=</span>
</div>
- <div style="height: 100px"></div>
+ <div style="height: 8px"></div>
<h3 id="section-target" data-cua-id="section-target">SECTION_TARGET_MARKER_v1</h3>
</fieldset>
@@ -168,12 +181,12 @@
<span class="mirror" id="lbl-child-window-state" data-cua-id="lbl-child-window-state">child_windows=0</span>
</div>
</fieldset>
+ </main>
<script>
// ----- state -----
let counter = 0;
let clickCount = 0;
- let calculatorExpression = '';
function $(id) { return document.getElementById(id); }
function updateChkState() {
@@ -191,26 +204,6 @@
$('lbl-counter').textContent = 'counter=0';
});
- // Calculator task oracle: the visible display is application state, not a
- // driver response. It intentionally uses separate buttons so both AX and
- // pixel-coordinate delivery can be tested against the same result.
- ['1', '2', '4'].forEach(digit => {
- $('calc-' + digit).addEventListener('click', () => {
- calculatorExpression += digit;
- $('calc-display').textContent = `display=${calculatorExpression}`;
- });
- });
- $('calc-plus').addEventListener('click', () => {
- calculatorExpression += '+';
- $('calc-display').textContent = `display=${calculatorExpression}`;
- });
- $('calc-equals').addEventListener('click', () => {
- const parts = calculatorExpression.split('+').map(Number);
- const result = parts.length === 2 && parts.every(Number.isFinite) ? parts[0] + parts[1] : 'error';
- calculatorExpression = String(result);
- $('calc-display').textContent = `display=${calculatorExpression}`;
- });
-
$('editor-save').addEventListener('click', () => {
const value = $('editor-document').value;
localStorage.setItem('cua-editor-document', value);
@@ -311,6 +304,57 @@
child.document.close();
}
});
+
+ // Publish fixture-owned state to the Rust harness over loopback. AX remains
+ // the targeting surface, but it is not a delivery oracle: embedded WebKit
+ // can retain stale accessible text after the DOM has already changed.
+ (function startFixtureJournal() {
+ const journalUrl = window.cuaE2E?.journalUrl ||
+ window.__CUA_E2E_FIXTURE_JOURNAL_URL || '';
+ if (!journalUrl) return;
+
+ let queued = false;
+ const publish = () => {
+ queued = false;
+ const state = {};
+ document.querySelectorAll('[data-cua-id]').forEach(element => {
+ const entry = { text: (element.textContent || '').trim() };
+ if ('value' in element) entry.value = element.value;
+ if ('checked' in element) entry.checked = element.checked;
+ state[element.dataset.cuaId] = entry;
+ });
+ if (window.cuaE2E?.publishFixtureState) {
+ window.cuaE2E.publishFixtureState(state);
+ return;
+ }
+ fetch(journalUrl, {
+ method: 'POST',
+ mode: 'no-cors',
+ headers: { 'Content-Type': 'text/plain' },
+ body: JSON.stringify(state),
+ keepalive: true,
+ }).catch(() => {});
+ };
+ const queuePublish = () => {
+ if (queued) return;
+ queued = true;
+ setTimeout(publish, 0);
+ };
+
+ new MutationObserver(queuePublish).observe(document.body, {
+ childList: true,
+ subtree: true,
+ characterData: true,
+ attributes: true,
+ });
+ for (const event of ['input', 'change', 'keydown', 'pointerup', 'scroll']) {
+ document.addEventListener(event, queuePublish, true);
+ }
+ // Keep the external oracle live even when its first loopback POST races
+ // fixture startup or a host bridge drops one fire-and-forget message.
+ setInterval(queuePublish, 250);
+ queuePublish();
+ })();
</script>
</body>
</html>
diff --git a/scripts/ci/link-e2e-evidence.sh b/scripts/ci/link-e2e-evidence.sh
new file mode 100755
index 0000000000..a295e049b4
--- /dev/null
+++ b/scripts/ci/link-e2e-evidence.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if (($# != 2)); then
+ echo "usage: link-e2e-evidence.sh <summary.md> <artifact-url>" >&2
+ exit 2
+fi
+
+summary_path="$1"
+artifact_url="$2"
+
+awk -F '|' -v artifact_url="${artifact_url}" '
+ BEGIN { OFS = "|" }
+ function trim(value) {
+ sub(/^[[:space:]]+/, "", value)
+ sub(/[[:space:]]+$/, "", value)
+ return value
+ }
+ /^\|/ && NF >= 16 {
+ cell = trim($2)
+ evidence = trim($15)
+ if (cell != "Cell" && cell !~ /^-+$/ && evidence != "" && evidence != "-" && evidence !~ /^\[/) {
+ $15 = " [" evidence "](" artifact_url ") "
+ }
+ }
+ { print }
+' "${summary_path}"