Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): recover owned orphaned X11 master devices (#3601)

Francesco Bonacci76e00c75e81b
diff --git a/libs/cua-driver/docs/linux-mpx-recovery.md b/libs/cua-driver/docs/linux-mpx-recovery.md
new file mode 100644
index 0000000000..868a42e9ed
--- /dev/null
+++ b/libs/cua-driver/docs/linux-mpx-recovery.md
@@ -0,0 +1,58 @@
+# Linux X11 MPX recovery
+
+Refs #3337.
+
+At main `130df4251e75f48bcbc43145b0cf7c7feac9ddc5`, a real Xorg 21.1.11
+desktop with libinput and `/dev/uinput` delivers a normal background scroll
+and removes its temporary master devices. SIGTERM during a longer scroll
+leaves its master pointer/keyboard pair after the owning process exits.
+The GTK keyboard fixture still accepts keys afterward in this environment;
+this does not reproduce the separate Chrome keyboard symptom reported in
+the issue.
+
+Recovery must distinguish a stale owner from a live process, PID reuse,
+inaccessible process metadata, and a different host or PID namespace using
+the same X server. A bare PID parsed from an old device name is insufficient.
+Unknown or legacy ownership must remain untouched by automatic recovery.
+
+The candidate will be checked on real Xorg for normal input, clean exit,
+SIGTERM and SIGKILL during an operation, restart cleanup, and live-peer
+preservation. Focused ownership tests and the canonical Linux desktop
+harness complement that native evidence. No Wayland behavior is changed.
+
+## Recovery contract
+
+New master names encode a versioned ownership domain (kernel boot, PID
+namespace, and effective user), PID, process start time, and unique nonce.
+Ownership is part of `XIAddMaster`, so SIGKILL cannot interrupt a separate
+ownership-property write. Startup of a standalone daemon removes a matching
+pair only when its owner is provably absent or that PID has been reused.
+Device-ID validation and removal run under the same X server grab.
+
+Live peers, inaccessible process metadata, foreign ownership domains, and
+legacy names are preserved. Older devices require deliberate manual recovery
+after their owner has been verified; parsing a legacy PID alone is unsafe.
+Direct embedded SDK startup does not perform recovery. SIGTERM and SIGKILL
+can still leave devices until the next standalone daemon starts.
+
+## Reproduce the focused native gate
+
+Use a disposable real Xorg desktop with libinput, readable/writable
+`/dev/uinput`, `xinput`, Python GTK3 bindings, and its session bus. Xvfb and
+TigerVNC do not support the needed device hotplug path.
+
+```sh
+cargo build --locked -p cua-driver --manifest-path libs/cua-driver/rust/Cargo.toml
+python3 libs/cua-driver/tests/linux-mpx-recovery.py \
+ --driver libs/cua-driver/rust/target/debug/cua-driver \
+ --output /tmp/mpx-recovery-evidence \
+ --source-sha "$(git rev-parse HEAD)"
+```
+
+The output directory must be new. The harness starts only its own daemons and
+fixture; it records native snapshots, fixture events, XInput inventories,
+and a final `proof.json`. It checks normal input and clean exit, both signal
+paths and restart recovery, preservation of a paused live peer followed by
+successful resumed input, and preservation of pre-existing unowned devices.
+It also verifies that read-only `describe` does not trigger recovery.
+Run the canonical Linux harness separately on the final candidate.
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 91491f5f02..56a6016a6a 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -3235,6 +3235,7 @@ dependencies = [
"reis",
"serde",
"serde_json",
+ "sha2",
"socket2",
"tempfile",
"thiserror 1.0.69",
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 aef5e68db1..d9e7f39535 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -970,6 +970,9 @@ pub async fn run_serve(
cua_driver_core::authorization::validate_startup_authorization()?;
+ #[cfg(target_os = "linux")]
+ platform_linux::recover_orphaned_mpx_devices();
+
// Create parent directory.
if let Some(dir) = std::path::Path::new(socket_path).parent() {
std::fs::create_dir_all(dir)?;
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index 35b526289d..4546945d67 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -17,6 +17,7 @@ cursor-overlay = { path = "../cursor-overlay" }
pip-preview = { path = "../pip-preview" }
zeroize = { workspace = true }
getrandom = { workspace = true }
+sha2 = { workspace = true }
# tiny-skia for cursor rendering (shared cross-platform)
tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
index 9377555006..d0fcdd5eee 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
@@ -14,6 +14,7 @@
/// Shared `delivery_mode` contract (background|foreground) — mirrors macOS
/// `tools::DeliveryMode` and Windows `input::delivery`.
pub mod delivery;
+mod mpx_owner;
use anyhow::{anyhow, bail, Context, Result};
use evdev::uinput::VirtualDevice;
@@ -149,6 +150,11 @@ fn uinput_pointers() -> &'static Mutex<HashMap<String, Arc<Mutex<VirtualDevice>>
fn master_pointer_name(cursor_id: &str) -> String {
let nonce = MPX_NAME_COUNTER.fetch_add(1, Ordering::Relaxed);
+ if let Ok(owner) = mpx_owner::Owner::current() {
+ return owner.master_name(nonce);
+ }
+ // Unknown procfs identity cannot safely participate in automatic recovery.
+ // Preserve ordinary operation, with the legacy name and cleanup behavior.
let prefix = "CUA ";
let suffix = format!(" mp-{}-{nonce}", std::process::id());
let max_cursor_bytes = EVDEV_UINPUT_NAME_MAX_BYTES
@@ -610,11 +616,12 @@ pub fn forget_master_pointer(cursor_id: &str) {
let Ok(display) = open_display() else {
return;
};
+ let _ = remove_master_pointer(display, ids.pointer_id);
+ unsafe { x11::xlib::XCloseDisplay(display) };
+}
- let Ok(devices) = xi2_query_devices(display) else {
- unsafe { x11::xlib::XCloseDisplay(display) };
- return;
- };
+fn remove_master_pointer(display: *mut x11::xlib::Display, pointer_id: i32) -> Result<()> {
+ let devices = xi2_query_devices(display)?;
let mut virtual_core_pointer = None;
let mut virtual_core_keyboard = None;
@@ -629,22 +636,67 @@ pub fn forget_master_pointer(cursor_id: &str) {
let (Some(return_pointer), Some(return_keyboard)) =
(virtual_core_pointer, virtual_core_keyboard)
else {
- unsafe { x11::xlib::XCloseDisplay(display) };
- return;
+ bail!("cannot remove MPX master without its virtual core return devices");
};
let mut change = x11::xinput2::XIAnyHierarchyChangeInfo::default();
unsafe {
let remove = change.remove();
(*remove)._type = x11::xinput2::XIRemoveMaster;
- (*remove).deviceid = ids.pointer_id;
+ (*remove).deviceid = pointer_id;
(*remove).return_mode = x11::xinput2::XIAttachToMaster;
(*remove).return_pointer = return_pointer;
(*remove).return_keyboard = return_keyboard;
- let _ = x11::xinput2::XIChangeHierarchy(display, &mut change, 1);
+ let rc = x11::xinput2::XIChangeHierarchy(display, &mut change, 1);
+ x11::xlib::XSync(display, 0);
+ if rc != 0 {
+ bail!("XIChangeHierarchy(XIRemoveMaster) failed with status {rc}");
+ }
+ }
+ Ok(())
+}
+
+/// Recover only versioned masters whose local owner is provably gone. A PID
+/// alone cannot identify an owner on a shared/remote X server or across restarts.
+pub(crate) fn reap_orphaned_master_pointers() {
+ if std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ return;
+ }
+ let Ok(owner) = mpx_owner::Owner::current() else {
+ return;
+ };
+ let Ok(display) = open_display() else {
+ return;
+ };
+ // Prevent an ID from being removed/reused by another X client between our
+ // enumeration and removal. No network or arbitrary filesystem reads occur
+ // under this grab: owner checks inspect local procfs and kill(pid, 0).
+ unsafe {
+ x11::xlib::XGrabServer(display);
+ }
+ let result = (|| -> Result<()> {
+ for (id, use_, name) in xi2_query_devices(display)? {
+ if use_ != x11::xinput2::XIMasterPointer {
+ continue;
+ }
+ let Some(candidate) = mpx_owner::Owner::from_pointer_name(&name) else {
+ continue;
+ };
+ if candidate.stale_in(&owner) {
+ remove_master_pointer(display, id)?;
+ tracing::info!(device_id = id, "removed orphaned Cua MPX master pair");
+ }
+ }
+ Ok(())
+ })();
+ unsafe {
+ x11::xlib::XUngrabServer(display);
x11::xlib::XSync(display, 0);
x11::xlib::XCloseDisplay(display);
}
+ if let Err(error) = result {
+ tracing::warn!("MPX orphan recovery incomplete: {error}");
+ }
}
fn create_uinput_pointer(name: &str) -> Result<VirtualDevice> {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_owner.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_owner.rs
new file mode 100644
index 0000000000..4c8672fa99
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mpx_owner.rs
@@ -0,0 +1,220 @@
+//! Incarnation-aware ownership encoded atomically in XIAddMaster's name.
+//! No separate property-write window can leave an unmarked new master after SIGKILL.
+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
+use sha2::{Digest, Sha256};
+use std::{fs, io};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(super) struct Owner {
+ domain: [u8; 16],
+ pid: u32,
+ start_ticks: u64,
+}
+
+fn start_ticks(stat: &str) -> io::Result<u64> {
+ // comm can contain spaces and closing parentheses. Fields following its
+ // final ')' begin with state (field 3); starttime is field 22.
+ stat.rsplit_once(')')
+ .and_then(|(_, tail)| tail.split_whitespace().nth(19))
+ .and_then(|value| value.parse().ok())
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "invalid proc stat"))
+}
+
+fn process_start(pid: u32) -> io::Result<u64> {
+ start_ticks(&fs::read_to_string(format!("/proc/{pid}/stat"))?)
+}
+
+impl Owner {
+ pub(super) fn current() -> io::Result<Self> {
+ let pid = std::process::id();
+ let own_stat = fs::read_to_string("/proc/self/stat")?;
+ if own_stat
+ .split_whitespace()
+ .next()
+ .and_then(|p| p.parse::<u32>().ok())
+ != Some(pid)
+ {
+ return Err(io::Error::other("procfs exposes another PID namespace"));
+ }
+ let start_ticks = start_ticks(&own_stat)?;
+ // A procfs mounted from another PID namespace cannot be used to
+ // identify peers through namespace-local PIDs.
+ if process_start(pid)? != start_ticks {
+ return Err(io::Error::other(
+ "procfs does not identify this PID namespace",
+ ));
+ }
+ let boot = fs::read_to_string("/proc/sys/kernel/random/boot_id")?;
+ let namespace = fs::read_link("/proc/self/ns/pid")?;
+ let mut hash = Sha256::new();
+ hash.update(boot.trim().as_bytes());
+ hash.update([0]);
+ hash.update(namespace.as_os_str().as_encoded_bytes());
+ hash.update([0]);
+ hash.update(unsafe { libc::geteuid() }.to_be_bytes());
+ let domain = hash.finalize()[..16].try_into().unwrap();
+ Ok(Self {
+ domain,
+ pid,
+ start_ticks,
+ })
+ }
+
+ pub(super) fn master_name(&self, nonce: u64) -> String {
+ let mut process = [0; 12];
+ process[..4].copy_from_slice(&self.pid.to_be_bytes());
+ process[4..].copy_from_slice(&self.start_ticks.to_be_bytes());
+ format!(
+ "CUA v1.{}.{}.{}",
+ URL_SAFE_NO_PAD.encode(self.domain),
+ URL_SAFE_NO_PAD.encode(process),
+ URL_SAFE_NO_PAD.encode(nonce.to_be_bytes())
+ )
+ }
+
+ pub(super) fn from_pointer_name(name: &str) -> Option<Self> {
+ let mut parts = name
+ .strip_prefix("CUA v1.")?
+ .strip_suffix(" pointer")?
+ .split('.');
+ let domain: [u8; 16] = URL_SAFE_NO_PAD
+ .decode(parts.next()?)
+ .ok()?
+ .try_into()
+ .ok()?;
+ let process: [u8; 12] = URL_SAFE_NO_PAD
+ .decode(parts.next()?)
+ .ok()?
+ .try_into()
+ .ok()?;
+ let _: [u8; 8] = URL_SAFE_NO_PAD
+ .decode(parts.next()?)
+ .ok()?
+ .try_into()
+ .ok()?;
+ if parts.next().is_some() {
+ return None;
+ }
+ let pid = u32::from_be_bytes(process[..4].try_into().ok()?);
+ if pid == 0 || pid > i32::MAX as u32 {
+ return None;
+ }
+ Some(Self {
+ domain,
+ pid,
+ start_ticks: u64::from_be_bytes(process[4..].try_into().ok()?),
+ })
+ }
+
+ pub(super) fn stale_in(&self, current: &Self) -> bool {
+ self.stale_with(current, process_start, |pid| {
+ // hidepid and permission failures can look like absent procfs
+ // entries. Require the kernel to independently report ESRCH.
+ (unsafe { libc::kill(pid as i32, 0) }) == -1
+ && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
+ })
+ }
+
+ fn stale_with(
+ &self,
+ current: &Self,
+ read: impl FnOnce(u32) -> io::Result<u64>,
+ absent: impl FnOnce(u32) -> bool,
+ ) -> bool {
+ if self.domain != current.domain {
+ return false;
+ }
+ match read(self.pid) {
+ Ok(start) => start != self.start_ticks,
+ Err(error) if error.kind() == io::ErrorKind::NotFound => absent(self.pid),
+ Err(_) => false,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn owner() -> Owner {
+ Owner {
+ domain: [7; 16],
+ pid: 123,
+ start_ticks: 456,
+ }
+ }
+
+ #[test]
+ fn ownership_roundtrip_is_bounded_even_at_integer_limits() {
+ let owner = Owner {
+ pid: i32::MAX as u32,
+ start_ticks: u64::MAX,
+ ..owner()
+ };
+ let name = owner.master_name(u64::MAX);
+ assert!(format!("{name} uinput pointer").len() <= 78);
+ assert_eq!(
+ Owner::from_pointer_name(&format!("{name} pointer")),
+ Some(owner.clone())
+ );
+ assert_ne!(owner.master_name(1), owner.master_name(2));
+ for suffix in [" keyboard", " XTEST pointer", " pointer extra"] {
+ assert!(Owner::from_pointer_name(&format!("{name}{suffix}")).is_none());
+ }
+ for name in [
+ "CUA legacy mp-123-1 pointer",
+ "CUA v1.bad.bad.bad pointer",
+ "ordinary pointer",
+ ] {
+ assert!(Owner::from_pointer_name(name).is_none());
+ }
+ }
+
+ #[test]
+ fn live_peer_and_unverifiable_metadata_are_preserved() {
+ let owner = owner();
+ assert!(!owner.stale_with(&owner, |_| Ok(456), |_| panic!("must not probe")));
+ for kind in [
+ io::ErrorKind::PermissionDenied,
+ io::ErrorKind::InvalidData,
+ io::ErrorKind::Interrupted,
+ ] {
+ assert!(!owner.stale_with(&owner, |_| Err(kind.into()), |_| panic!("must not probe")));
+ }
+ assert!(!owner.stale_with(&owner, |_| Err(io::ErrorKind::NotFound.into()), |_| false));
+ let foreign = Owner {
+ domain: [8; 16],
+ ..owner.clone()
+ };
+ assert!(!foreign.stale_with(
+ &owner,
+ |_| panic!("foreign domain"),
+ |_| panic!("foreign domain")
+ ));
+ }
+
+ #[test]
+ fn dead_owner_and_reused_pid_are_stale() {
+ let owner = owner();
+ assert!(owner.stale_with(&owner, |_| Err(io::ErrorKind::NotFound.into()), |_| true));
+ assert!(owner.stale_with(&owner, |_| Ok(999), |_| panic!("must not probe")));
+ }
+
+ #[test]
+ fn proc_stat_comm_delimiters_do_not_shift_starttime() {
+ let tail = (3..=21)
+ .map(|n| n.to_string())
+ .collect::<Vec<_>>()
+ .join(" ");
+ assert_eq!(
+ start_ticks(&format!("123 (name with ) parentheses) {tail} 98765 23")).unwrap(),
+ 98765
+ );
+ assert!(start_ticks("bad").is_err());
+ }
+
+ #[test]
+ fn actual_current_process_is_not_stale() {
+ let owner = Owner::current().unwrap();
+ assert!(!owner.stale_in(&owner));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index f7d13facb7..c13985260f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -157,6 +157,13 @@ pub fn register_tools_with_cursor_and_provider(
tools::build_registry_with_provider(compat, provider)
}
+/// Standalone daemon startup recovery. Keep this out of registry construction:
+/// read-only commands such as describe/list-tools must not mutate X11 devices.
+#[cfg(target_os = "linux")]
+pub fn recover_orphaned_mpx_devices() {
+ input::reap_orphaned_master_pointers();
+}
+
#[cfg(test)]
mod display_detection_tests {
use super::detect_wsl;
diff --git a/libs/cua-driver/tests/linux-mpx-recovery.py b/libs/cua-driver/tests/linux-mpx-recovery.py
new file mode 100644
index 0000000000..1fa45d7d85
--- /dev/null
+++ b/libs/cua-driver/tests/linux-mpx-recovery.py
@@ -0,0 +1,270 @@
+#!/usr/bin/env python3
+"""Focused MPX lifecycle regression for a disposable real-Xorg/uinput desktop.
+
+Complements scripts/ci/linux/run-rust-e2e.sh; Xvfb/TigerVNC cannot run this test.
+All window interactions use Cua Driver. Signals target only harness-owned daemons.
+Requires Python GTK3 bindings, xinput, and an already-built Linux Driver.
+"""
+import argparse
+import base64
+import json
+import os
+from pathlib import Path
+import re
+import signal
+import socket
+import subprocess
+import sys
+import time
+
+
+def fixture(oracle):
+ import gi
+ gi.require_version("Gtk", "3.0")
+ from gi.repository import Gtk, Gdk
+
+ def event(kind, **fields):
+ with open(oracle, "a") as stream:
+ stream.write(json.dumps(dict(time_ns=time.time_ns(), event=kind, **fields)) + "\n")
+
+ window = Gtk.Window(title="CUA MPX lifecycle fixture")
+ window.set_default_size(700, 500)
+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=16)
+ window.add(box)
+ entry = Gtk.Entry()
+ entry.get_accessible().set_name("Keyboard recovery oracle")
+ entry.connect("changed", lambda widget: event("text", value=widget.get_text()))
+ box.pack_start(entry, False, False, 0)
+ canvas = Gtk.DrawingArea()
+ canvas.get_accessible().set_name("MPX scroll canvas")
+ canvas.set_size_request(650, 400)
+ canvas.add_events(Gdk.EventMask.SCROLL_MASK | Gdk.EventMask.SMOOTH_SCROLL_MASK)
+ canvas.connect("scroll-event", lambda widget, ev: event("scroll") or True)
+ box.pack_start(canvas, True, True, 0)
+ window.connect("destroy", Gtk.main_quit)
+ window.show_all()
+ Gtk.main()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--driver", required=True)
+ parser.add_argument("--output", required=True)
+ parser.add_argument("--source-sha", required=True)
+ args = parser.parse_args()
+ repository = Path(__file__).resolve().parents[3]
+ head = subprocess.check_output(["git", "-C", str(repository), "rev-parse", "HEAD"], text=True).strip()
+ assert head == args.source_sha, "Harness source does not match the requested candidate"
+ assert sys.platform == "linux" and os.environ.get("DISPLAY")
+ assert not os.environ.get("WAYLAND_DISPLAY"), "Requires a dedicated X11 desktop"
+ assert os.access("/dev/uinput", os.R_OK | os.W_OK), "Requires guest-local uinput access"
+ driver = str(Path(args.driver).resolve(strict=True))
+ root = Path(args.output).resolve()
+ root.mkdir(parents=True, exist_ok=False)
+ oracle = root / "fixture.jsonl"
+ daemons, handles, actors = [], [], []
+ stopped = None
+ target = None
+ observer = None
+ serial = 0
+ proof = {"source_sha": args.source_sha, "cases": []}
+
+ def save(name, value):
+ (root / name).write_text(json.dumps(value, indent=2) + "\n")
+
+ def raw(endpoint, tool, params, image=None, text_result=False):
+ argv = [driver, "--socket", endpoint, "call", tool, json.dumps(params)]
+ if image:
+ argv += ["--screenshot-out-file", str(image)]
+ result = subprocess.run(argv, capture_output=True, text=True, timeout=25)
+ assert result.returncode == 0, (tool, result.stdout, result.stderr)
+ if text_result:
+ return result.stdout
+ return json.loads(result.stdout)
+
+ def snapshot(endpoint, label):
+ value = raw(endpoint, "get_window_state", target, root / (label + ".png"))
+ save(label + ".json", value)
+ assert value.get("window_id") == target["window_id"], value
+ assert value.get("screenshot_width", 0) >= 650 and value.get("screenshot_height", 0) >= 450
+
+ def start():
+ nonlocal serial
+ serial += 1
+ endpoint = str(root / ("daemon-" + str(serial) + ".sock"))
+ log = (root / ("daemon-" + str(serial) + ".log")).open("w")
+ handles.append(log)
+ process = subprocess.Popen([driver, "serve", "--socket", endpoint,
+ "--dangerously-bypass-approvals"],
+ stdin=subprocess.DEVNULL, stdout=log, stderr=log)
+ daemons.append((process, endpoint))
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ assert process.poll() is None, "daemon exited during startup"
+ try:
+ with socket.socket(socket.AF_UNIX) as connection:
+ connection.connect(endpoint)
+ return process, endpoint
+ except OSError:
+ time.sleep(.02)
+ raise AssertionError("daemon startup timed out")
+
+ def stop(process, endpoint):
+ result = subprocess.run([driver, "--socket", endpoint, "stop"],
+ capture_output=True, text=True, timeout=20)
+ assert result.returncode == 0, result.stderr
+ process.wait(timeout=20)
+
+ def devices(label):
+ value = subprocess.check_output(["xinput", "list", "--short"], text=True)
+ (root / (label + ".txt")).write_text(value)
+ return value
+
+ def masters(value):
+ return {line.split("id=")[0].strip() for line in value.splitlines()
+ if "CUA " in line and "[master pointer" in line}
+
+ def owned(value, pid):
+ found = set()
+ for name in masters(value):
+ match = re.search(r"CUA v1\.[A-Za-z0-9_-]+\.([A-Za-z0-9_-]+)\.[A-Za-z0-9_-]+ pointer", name)
+ if match and int.from_bytes(base64.urlsafe_b64decode(match[1] + "==")[:4], "big") == pid:
+ found.add(name)
+ return found
+
+ def events(kind):
+ if not oracle.exists():
+ return []
+ return [row for line in oracle.read_text().splitlines()
+ if (row := json.loads(line))["event"] == kind]
+
+ def key(endpoint, label, letter):
+ snapshot(endpoint, label + "-before")
+ result = raw(endpoint, "press_key", dict(target, key=letter, delivery_mode="foreground"))
+ save(label + "-action.json", result)
+ snapshot(endpoint, label + "-after")
+ assert events("text")[-1]["value"].endswith(letter), "keyboard oracle did not change"
+
+ def scroll(endpoint, label, amount=3):
+ snapshot(endpoint, label + "-before")
+ before = len(events("scroll"))
+ result = raw(endpoint, "scroll", dict(target, direction="down", amount=amount, x=350, y=250))
+ save(label + "-action.json", result)
+ snapshot(endpoint, label + "-after")
+ assert len(events("scroll")) > before, "native fixture received no scroll events"
+ return result
+
+ def long_scroll(process, endpoint, label):
+ snapshot(endpoint, label + "-before")
+ before = len(events("scroll"))
+ log = (root / (label + "-action.log")).open("w")
+ handles.append(log)
+ actor = subprocess.Popen([driver, "--socket", endpoint, "call", "scroll",
+ json.dumps(dict(target, direction="down", amount=50, x=350, y=250))],
+ stdout=log, stderr=log)
+ actors.append(actor)
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline and actor.poll() is None:
+ value = devices(label + "-during")
+ if owned(value, process.pid) and "uinput pointer" in value and len(events("scroll")) > before:
+ return actor, owned(value, process.pid)
+ time.sleep(.01)
+ raise AssertionError("No active owned MPX device with native scroll delivery")
+
+ try:
+ devices("initial")
+ primary, endpoint = start()
+ observer, observer_endpoint = start()
+ baseline = masters(devices("baseline-after-startup"))
+ launched = raw(endpoint, "launch_app", {"name": sys.executable,
+ "additional_arguments": [str(Path(__file__).resolve()), "--fixture", str(oracle)]})
+ window = next(w for w in launched["windows"] if w["title"] == "CUA MPX lifecycle fixture")
+ target = {"pid": window["pid"], "window_id": window["window_id"], "session": "mpx-lifecycle"}
+ snapshot(endpoint, "initial-window")
+ # Prove the refusal before using this disposable test's foreground route.
+ refusal = raw(endpoint, "press_key", dict(target, key="a"))
+ save("background-key.json", refusal)
+ snapshot(endpoint, "background-key-after")
+ if refusal.get("code") == "background_unavailable":
+ key(endpoint, "initial-key", "a")
+ else:
+ assert events("text")[-1]["value"].endswith("a")
+ scroll(endpoint, "normal-scroll")
+ assert not owned(devices("normal-cleanup"), primary.pid)
+ stop(primary, endpoint)
+ snapshot(observer_endpoint, "clean-exit")
+ assert not owned(devices("clean-exit-devices"), primary.pid)
+ proof["cases"].append({"case": "normal-input-and-clean-exit", "passed": True})
+
+ for sig, label in [(signal.SIGTERM, "term"), (signal.SIGKILL, "kill")]:
+ primary, endpoint = start()
+ actor, live = long_scroll(primary, endpoint, label)
+ primary.send_signal(sig)
+ primary.wait(timeout=10)
+ actor.wait(timeout=15)
+ orphan = owned(devices(label + "-after-exit"), primary.pid)
+ assert orphan == live, "interruption did not retain the observed orphan"
+ snapshot(observer_endpoint, label + "-window-survives")
+ # Read-only registry construction must not perform recovery.
+ subprocess.run([driver, "describe", "scroll"], stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, check=True, timeout=15)
+ assert owned(devices(label + "-after-describe"), primary.pid) == orphan
+ dead_pid = primary.pid
+ primary, endpoint = start()
+ after = devices(label + "-after-restart")
+ assert not owned(after, dead_pid), "restart did not recover the orphan"
+ assert baseline <= masters(after), "existing unowned master was removed"
+ key(endpoint, label + "-keyboard", "t" if label == "term" else "k")
+ proof["cases"].append({"case": label + "-restart-recovery", "passed": True,
+ "orphan_count": len(orphan), "legacy_preserved": True})
+ stop(primary, endpoint)
+
+ primary, endpoint = start()
+ actor, live = long_scroll(observer, observer_endpoint, "live-peer")
+ observer.send_signal(signal.SIGSTOP)
+ stopped = observer
+ stop(primary, endpoint)
+ primary, endpoint = start()
+ assert owned(devices("live-peer-after-restart"), observer.pid) == live
+ observer.send_signal(signal.SIGCONT)
+ stopped = None
+ assert actor.wait(timeout=15) == 0
+ snapshot(observer_endpoint, "live-peer-completed")
+ assert not owned(devices("live-peer-cleanup"), observer.pid)
+ key(observer_endpoint, "live-peer-keyboard", "p")
+ proof["cases"].append({"case": "paused-live-peer-preserved-and-resumed", "passed": True})
+ assert masters(devices("final")) == baseline
+ proof["passed"] = True
+ finally:
+ if stopped is not None and stopped.poll() is None:
+ stopped.send_signal(signal.SIGCONT)
+ if target is not None and observer is not None and observer.poll() is None:
+ try:
+ snapshot(observer_endpoint, "fixture-before-cleanup")
+ # kill_app emits human-readable text; verify the independent inventory.
+ cleanup = raw(observer_endpoint, "kill_app", {"pid": target["pid"]}, text_result=True)
+ save("fixture-cleanup.json", {"response": cleanup})
+ remaining = raw(observer_endpoint, "list_windows", {})
+ assert not any(w["pid"] == target["pid"] for w in remaining["windows"])
+ except Exception as error:
+ proof["cleanup_error"] = str(error)
+ proof["passed"] = False
+ for process, endpoint in reversed(daemons):
+ if process.poll() is None:
+ stop(process, endpoint)
+ for actor in actors:
+ if actor.poll() is None:
+ actor.terminate()
+ actor.wait(timeout=10)
+ for handle in handles:
+ handle.close()
+ save("proof.json", proof)
+ assert "cleanup_error" not in proof, proof
+ print(json.dumps(proof), flush=True)
+
+
+if __name__ == "__main__":
+ if len(sys.argv) == 3 and sys.argv[1] == "--fixture":
+ fixture(sys.argv[2])
+ else:
+ main()