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): harden cross-platform browser certification (#2367)

Francesco Bonacci2b06a782544e
diff --git a/.github/workflows/e2e-rust-standalone-browsers.yml b/.github/workflows/e2e-rust-standalone-browsers.yml
index aefd0ebe80..9eee5cc315 100644
--- a/.github/workflows/e2e-rust-standalone-browsers.yml
+++ b/.github/workflows/e2e-rust-standalone-browsers.yml
@@ -34,7 +34,7 @@ jobs:
echo "sha=${sha,,}" >> "$GITHUB_OUTPUT"
browser:
- name: "${{ matrix.label }} / Chrome and Edge"
+ name: "${{ matrix.label }} / ${{ matrix.products }}"
needs: source
strategy:
fail-fast: false
@@ -43,9 +43,11 @@ jobs:
- label: Windows
os: windows-latest
artifact: rust-browser-windows
+ products: chrome,edge
- label: Linux X11
os: ubuntu-latest
artifact: rust-browser-linux-x11
+ products: chrome
runs-on: ${{ matrix.os }}
timeout-minutes: 60
env:
@@ -54,6 +56,7 @@ jobs:
CUA_E2E_FORBID_SKIPS: "1"
CUA_TEST_DRIVER_STDERR: "1"
CUA_E2E_BROWSER_STDERR: "1"
+ CUA_E2E_BROWSER_PRODUCTS: ${{ matrix.products }}
RUST_BACKTRACE: "1"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
@@ -88,7 +91,7 @@ jobs:
- name: Build source driver on Linux
if: runner.os == 'Linux'
shell: bash
- run: cargo build --release -p cua-driver --manifest-path libs/cua-driver/rust/Cargo.toml
+ run: cargo build --release -p cua-driver --features portal-input --manifest-path libs/cua-driver/rust/Cargo.toml
- name: Run standalone browsers on Windows
if: runner.os == 'Windows'
shell: pwsh
diff --git a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
index da4eb05720..952e14b6ca 100644
--- a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
+++ b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
@@ -102,6 +102,8 @@ for why Cua Driver uses CDP and which risks remain outside the driver.
| `browser_binding_stale` | A connection generation changed; bind again. |
| `browser_reconnect_exhausted` | The bounded reconnect policy could not establish a proven socket. |
| `browser_input_incomplete` | Keystroke typing delivered only a reported prefix. |
+| `browser_route_unavailable` | The classified engine or platform has no accepted typed route. For Firefox and Safari, bounded detail identifies the required protocol and current lifecycle limitation. |
+| `browser_input_trust_unavailable` | Trusted input cannot preserve background posture. Bounded detail identifies the explicit `dom_event` alternative when a synthetic ref-targeted action is acceptable. |
## Recording and telemetry
@@ -115,21 +117,26 @@ The content-free browser operation and refusal fields are documented in
## Platform scope
The prompt-assisted route is available for Google Chrome and Microsoft Edge on
-macOS and Windows. Chrome has product-specific acceptance evidence on Linux
-X11 and on the validated native-Wayland Sway lane. Chromium and Edge use the
-same descriptor-backed Linux route, but still need product-specific acceptance
-evidence before they are listed as validated. Every route requires an
+macOS and Windows. Chrome and Edge have product-specific acceptance evidence
+on Linux X11. Chrome is also accepted on GNOME Wayland, and Chromium is
+accepted alongside Chrome and Edge on the validated native-Wayland Sway lane.
+The Chromium-family products use the same descriptor-backed Linux route, but
+still need product-specific acceptance evidence on each desktop before they
+are listed as validated. Every route
+requires an
exact approved PID and native window, one uniquely matched setup control, a
loopback endpoint owned by that process, one exact browser-owned consent
action, and a fresh native/CDP rebind.
Linux additionally requires the browser's complete AT-SPI renderer tree. Start
the Chromium-family process with `--force-renderer-accessibility`, or run a
-screen reader that enables full renderer accessibility. On Sway, Cua Driver
-briefly focuses the exact compositor-attested container for fixed internal-page
-navigation and restores the previous container before continuing. It refuses
-generic Wayland sessions that cannot prove exact process, window, and geometry
-identity.
+screen reader that enables full renderer accessibility. On Sway and validated
+GNOME Shell sessions, Cua Driver briefly focuses the exact
+compositor-attested window for fixed internal-page navigation and restores the
+previous window before continuing. GNOME requires the maintained WinRects
+helper API v4 and an immutable D-Bus owner that resolves to the current user's
+system-installed GNOME Shell process. Cua Driver refuses generic Wayland
+sessions that cannot prove exact process, window, and geometry identity.
The setup adapters currently recognize the products' English accessibility
labels. Other UI locales fail closed without toggling an unrecognized control.
diff --git a/libs/cua-driver/docs/browser-cross-platform-hardening-journal.md b/libs/cua-driver/docs/browser-cross-platform-hardening-journal.md
new file mode 100644
index 0000000000..76374fc5f2
--- /dev/null
+++ b/libs/cua-driver/docs/browser-cross-platform-hardening-journal.md
@@ -0,0 +1,131 @@
+# Browser Cross-Platform Hardening Journal
+
+This journal records implementation and validation evidence for the browser
+support hardening branch. It is not a public support contract.
+
+## 2026-07-19: Scope and baseline
+
+- Branch created from exact `origin/main` commit `6b6ad1e0`.
+- Fable and local source review agreed that Linux Chromium-family product
+ certification is achievable in this work window.
+- Safari existing-profile attachment needs a WebKit/WebDriver-specific engine.
+ Firefox existing-profile attachment cannot enable its Remote Agent on an
+ already-running ordinary process; Mozilla requires launch-time enablement.
+- Generic Wayland remains refused until a compositor can attest exact window
+ identity. Sway and the maintained GNOME helper are the accepted native
+ Wayland identity routes.
+- macOS and Linux trusted Chromium pointer delivery remains an exact refusal
+ when Chromium would activate the standalone browser. Synthetic ref-targeted
+ `dom_event` delivery is a distinct explicit route, not trusted input.
+
+## Implemented locally
+
+- Added exact `CUA_E2E_BROWSER_PRODUCTS` selection. Explicit certification
+ sets fail on unknown, duplicate, or missing products; the historical default
+ selection is unchanged.
+- Added a source-bound `browser-provenance.jsonl` artifact populated from each
+ launched browser's CDP version endpoint. Hosted lanes now declare their exact
+ mandatory product list instead of using a broader display label.
+- Added the stable Microsoft Edge Linux executable name.
+- Corrected the public evidence claim: Linux X11 accepted Chrome; native Sway
+ accepted Chromium.
+- Enriched unsupported Gecko/WebKit refusals with bounded engine, product,
+ protocol, and lifecycle detail before native-window probing.
+- Enriched pre-dispatch trusted-input refusals with the explicit synthetic
+ alternative and a proof that no trusted delivery was attempted.
+- Added a real-browser generic-Wayland refusal row. It withholds all
+ compositor-specific identity from the driver and proves the browser window
+ and fixture state are unchanged when exact identity is unavailable.
+- Made the shared loopback fixture complete a real HTTP readiness round trip
+ before it is returned to browser tests.
+- Corrected the existing-profile setup row to model the user workflow: launch
+ an ordinary browser page without CDP, prepare that exact native window, then
+ navigate to the oracle fixture through the newly attached browser route.
+- Made standalone Linux certification compile with `portal-input`, matching
+ the published artifact instead of misclassifying GNOME/KDE through a
+ default-feature binary that can only fall back to `wtype`.
+- Made `XDG_SESSION_TYPE=wayland` plus `WAYLAND_DISPLAY` authoritative for the
+ standalone runner and browser launch. GNOME/KDE retain `DISPLAY` for
+ XWayland, but that no longer sends a native Wayland lane through X11 window
+ enumeration or launches its browser on XWayland.
+- Added protocol and compositor identity design records.
+- Added a GNOME Wayland browser-identity route using WinRects helper API
+ v4. Browser-sensitive calls now prove the immutable D-Bus owner is the
+ current user's system-installed GNOME Shell process, use exact compositor
+ window identity, and restore the previously focused Shell window after each
+ bounded setup or consent operation.
+
+## Local evidence
+
+- `cargo test -p cua-driver-core browser::`: 132 passed, 0 failed.
+- `cargo test -p cua-driver-testkit`: 49 passed, 0 failed.
+- `cargo test -p cua-driver --test standalone_browser_behavior_test --no-run`:
+ compiled successfully at the current working tree.
+- `cargo test -p platform-linux --no-default-features`: platform code compiled
+ on macOS. The release-equivalent `portal-input` build compiled on GNOME and
+ completed the canonical browser matrix below.
+
+## Representative evidence
+
+- GNOME Wayland with Google Chrome at source `2ca38aea`: 13 delivered, 3
+ expected policy refusals, 0 failures, 0 skips, and 16 playable videos. This
+ accepts the GNOME helper route for Chrome without making a generic Wayland
+ claim.
+- Native Sway with Chromium at source `2ca38aea`: 13 delivered, 3 expected
+ policy refusals, 0 failures, 0 skips, and 16 playable videos.
+- Native Sway with Google Chrome and Microsoft Edge at source `2ca38aea`: 26
+ delivered, 6 expected policy refusals, 0 failures, 0 skips, and 32 playable
+ videos. Together these runs accept Chrome, Chromium, and Edge on Sway.
+- Linux X11 with Microsoft Edge at source `2ca38aea`: 13 delivered, 3 expected
+ policy refusals, 0 failures, 0 skips, and 16 playable videos. Snap Chromium
+ could not start its CDP endpoint in an SSH-created Xvfb session because the
+ snap required a real login-session cgroup; that preflight failure is not a
+ Cua Driver behavioral result.
+- macOS Tahoe canonical desktop matrix at source `f3413ac0`: 140 delivered, 8
+ expected refusals, 0 failures, 0 skips, and playable video for every declared
+ row. Later branch changes before `2ca38aea` affect only Linux test paths.
+- Generic native Wayland at source `2f48888d`: one real Chromium existing-profile
+ setup attempt refused with `browser_route_unavailable`, 0 failures, 0 skips,
+ and playable video. The harness retained Sway IPC only as an out-of-band
+ focus and z-order oracle; the Cua Driver child received an unusable socket
+ path and could not use compositor-specific identity.
+- macOS Tahoe existing-profile setup at source `75c40845`: the corrected Chrome
+ row completed setup, exact attachment, typed navigation, external fixture
+ mutation, and video/report validation with no failure or skip.
+- macOS Tahoe standalone Chrome and Edge matrix at source `86d799b8`: 26
+ delivered, 4 expected policy refusals, 0 failures, 0 skips, and 30 playable
+ videos. Both ordinary-profile setup and isolated-profile launch passed for
+ both products after the harness began from an ordinary `about:blank` window
+ and navigated through the prepared browser route.
+- macOS Tahoe exact-tip setup replay at source `a22840a4`: existing-profile
+ setup passed for Chrome and Edge, and isolated-profile launch passed for
+ Edge. Chrome isolated launch encountered one transient
+ `ERR_HTTP_RESPONSE_CODE_FAILURE`; an immediate clean retry and three further
+ consecutive runs all delivered with videos and complete fixture journals.
+ No assertion was relaxed and no retry was added to the harness.
+- Native Sway exact-tip setup replay at source `a22840a4`: existing-profile
+ setup and isolated-profile launch delivered for Chrome and Edge, with 4
+ playable videos and no failure or skip.
+- GNOME Wayland with Google Chrome at source `b1838255`: the canonical runner
+ completed 13 delivered rows, 3 expected policy refusals, 0 failures, 0
+ skips, and 16 playable videos. This run used the release-equivalent
+ `portal-input` feature and native Wayland even though GNOME also exported an
+ XWayland `DISPLAY`.
+- [Hosted Linux X11 with Google Chrome at source `b1838255`](https://github.com/trycua/cua/actions/runs/29722330860):
+ 13 delivered, 3 expected policy refusals, 0 failures, 0 skips, and 16
+ playable videos.
+- [Hosted Windows with Google Chrome and Microsoft Edge at source `b1838255`](https://github.com/trycua/cua/actions/runs/29722330860):
+ 28 delivered, 2 expected policy refusals, 0 failures, 0 skips, and 30
+ playable videos.
+
+## Deliberate boundaries
+
+- Already-running ordinary Safari and Firefox profiles remain structured,
+ protocol-specific refusals; neither product exposes the current Chromium
+ attachment lifecycle.
+- Generic Wayland remains fail-closed when no accepted compositor adapter can
+ attest the exact native window. Sway and the maintained GNOME helper are
+ accepted routes, not evidence of a generic protocol.
+- Trusted Chromium pointer input on macOS and Linux remains refused when it
+ would activate the browser. Explicit ref-targeted `dom_event` delivery is
+ available when a synthetic event satisfies the caller's contract.
diff --git a/libs/cua-driver/docs/browser-engine-support-plan.md b/libs/cua-driver/docs/browser-engine-support-plan.md
new file mode 100644
index 0000000000..2080672a5b
--- /dev/null
+++ b/libs/cua-driver/docs/browser-engine-support-plan.md
@@ -0,0 +1,91 @@
+# Browser Engine Support Plan
+
+This is an architecture explanation and implementation roadmap. It records why
+the typed browser surface supports an engine only after it can preserve exact
+targeting, approval, and background-delivery guarantees. It is not a support
+matrix; the public support contract remains the source of truth for accepted
+browser and platform combinations.
+
+## Current Boundary
+
+The current browser engine is CDP-native. Core owns a `CdpConnection`, binds a
+native window to an exact Chromium target, and re-proves process, window,
+endpoint, generation, and tab identity before mutation. `BrowserPlatform`
+abstracts operating-system identity and endpoint ownership, not the browser
+wire protocol.
+
+This boundary is appropriate for Chromium but cannot truthfully represent
+Firefox or Safari by renaming CDP concepts. Unsupported engines therefore
+return `browser_route_unavailable` with bounded `engine_family`, `product`,
+`required_protocol`, and `limitation` detail before native-window or endpoint
+probing.
+
+## Firefox
+
+Firefox's Remote Agent implements WebDriver BiDi. Mozilla documents that it is
+started with `--remote-debugging-port`, accepts loopback connections, and has no
+other enablement mechanism. An ordinary Firefox process that was not launched
+with the flag cannot become attachable without a restart. See Mozilla's
+[Remote Agent security model](https://firefox-source-docs.mozilla.org/remote/Security.html).
+
+Consequences:
+
+- Cua Driver must not edit the profile, restart Firefox, or claim that a
+ desktop-input fallback is typed browser attachment.
+- Existing-profile attachment to an already-running ordinary Firefox profile
+ remains a structured refusal.
+- A driver-owned isolated Firefox process is feasible later, but it needs a
+ WebDriver BiDi transport and capability store rather than a CDP adapter.
+- A Firefox capability must bind the BiDi session, browser process generation,
+ native window, browsing context, and Cua session, then re-prove all of them
+ after reconnect.
+
+## Safari
+
+Safari automation uses `safaridriver` and WebDriver. Apple requires the host to
+enable remote automation and describes additional isolation between automation
+sessions and normal browsing data. See [Enable WebDriver on macOS](https://developer.apple.com/documentation/safari-developer-tools/macos-enabling-webdriver)
+and [About WebDriver for Safari](https://developer.apple.com/documentation/webkit/about-webdriver-for-safari).
+
+Consequences:
+
+- Safari does not expose the loopback CDP endpoint used by the current binding
+ and grant model.
+- Cua Driver must not present a new WebDriver automation window as attachment
+ to the person's existing Safari profile.
+- A future Safari engine needs an explicit WebDriver session contract,
+ Safari-owned approval state, native window correlation, and session-specific
+ privacy rules.
+- Existing-profile attachment remains a structured refusal until a real Safari
+ route can prove those properties without copying or restarting the profile.
+
+## Protocol-Neutral Core
+
+A future multi-engine implementation should introduce a protocol boundary
+above CDP rather than expand `BrowserPlatform`:
+
+1. `BrowserTransport` owns connection, generation, and reconnect behavior.
+2. `BrowserContextId` replaces CDP target and session identifiers in the public
+ capability store.
+3. Engine adapters provide snapshot, navigation, typing, pointer, dialog,
+ upload, download, and lifecycle operations with explicit capability flags.
+4. Native binding remains a separate proof joined to the engine context before
+ every mutation.
+5. Approval artifacts name the engine, exact process/window generation, and
+ requested profile posture.
+
+No adapter may silently emulate a missing engine action with foreground desktop
+input. It either meets the typed action contract or returns a stable refusal.
+
+## Release Acceptance
+
+An engine becomes supported only when representative real-browser rows prove:
+
+- setup or launch follows the advertised profile contract;
+- exact window and browsing-context binding, including ambiguous-window cases;
+- reconnect generation invalidation and stale capability refusal;
+- external page-state mutation for every advertised action;
+- background focus, z-order or occlusion, cursor, and no-leaked-input guards;
+- non-mutating structured refusals for unavailable actions and environments;
+- redacted screenshots, trajectories, logs, and telemetry; and
+- playable video evidence at the exact source commit.
diff --git a/libs/cua-driver/docs/wayland-compositor-identity-plan.md b/libs/cua-driver/docs/wayland-compositor-identity-plan.md
new file mode 100644
index 0000000000..6bd666c08a
--- /dev/null
+++ b/libs/cua-driver/docs/wayland-compositor-identity-plan.md
@@ -0,0 +1,102 @@
+# Wayland Compositor Identity Plan
+
+This is an architecture explanation and evidence plan for expanding exact
+browser attachment beyond Sway. It does not claim generic Wayland support.
+
+## Why Compositor Identity Is Required
+
+Existing-profile setup can open an internal browser page and press one exact
+accessibility control. Before doing so, Cua Driver must prove that the native
+toplevel, browser PID, geometry, AT-SPI application/window, product descriptor,
+and loopback endpoint all describe the same browser generation.
+
+Title, application ID, or screen-coordinate similarity alone is insufficient.
+An attacker or unrelated window can reuse those values. When the compositor
+cannot attest exact identity, mutation must refuse before opening the setup
+page or sending input.
+
+## Accepted Sway Route
+
+The existing Sway adapter uses compositor IPC to correlate the exact container,
+PID, and rectangle with the AT-SPI tree. Setup may briefly focus that attested
+container for fixed browser-owned internal navigation, then restores the prior
+container. Canonical Sway evidence accepts Google Chrome, Chromium, and
+Microsoft Edge after each product completed the same full matrix with playable
+video and no unexpected results.
+
+## Accepted GNOME Route
+
+The maintained WinRects extension v4 exposes the narrow identity route Cua
+Driver needs on GNOME Shell and Mutter: a stable window identifier, PID,
+geometry, focus and stacking state, and exact activation.
+
+The Linux adapter resolves the extension's immutable unique D-Bus owner,
+verifies that the owner is the current user's system-installed `gnome-shell`
+process, requires helper API v4 for browser-sensitive calls, and addresses that
+unique owner directly. This prevents an unrelated same-session process from
+replacing the public bus name between verification and activation. Setup and
+consent briefly activate one exact window, then restore and verify the prior
+Shell focus.
+
+The route is accepted for Google Chrome after the full standalone-browser
+matrix recorded 13 delivered behaviors, 3 policy refusals, 0 failures, and 0
+skips with 16 playable videos at one source commit. Other Chromium-family
+products still require their own product-specific evidence on GNOME.
+
+The adapter refuses when the component is missing, incompatible, disabled, or
+unable to distinguish multiple windows for one browser process. Enabling a
+generic unsafe-mode switch is not an acceptable production dependency.
+
+## Candidate Compositors
+
+### KDE Plasma and KWin
+
+KWin 6 scripting exposes a per-window internal ID, PID, frame geometry,
+stacking order, active state, and workspace activation. See the official
+[KWin scripting API](https://develop.kde.org/docs/plasma/kwin/api/).
+
+A maintained Cua Driver KWin component could return a versioned, read-only
+identity record and perform one exact focus-and-restore transition. The adapter
+must bind its D-Bus peer, KWin generation, internal window ID, PID, geometry,
+and AT-SPI window. A generic user-provided script or title lookup is not enough.
+
+### Other Compositors
+
+The standard `ext-foreign-toplevel-list-v1` protocol exposes an opaque stable
+toplevel identifier, title, and application ID, but not PID or geometry. See
+the [foreign toplevel protocol](https://wayland.app/protocols/ext-foreign-toplevel-list-v1).
+It can contribute one part of a proof, but cannot independently authorize
+mutation.
+
+wlroots compositors may expose additional management or compositor IPC. Each
+route remains compositor-specific until it proves all required fields. No
+screen-coordinate fallback is allowed.
+
+## Threat Cases
+
+Each adapter and harness must cover:
+
+- two same-title browser windows with equal or near-equal geometry;
+- PID reuse or browser restart between approval and mutation;
+- a decoy application with the same application ID or title;
+- a window moving, changing workspace, minimizing, or closing during setup;
+- stale compositor object IDs after remap;
+- an incomplete or mismatched AT-SPI tree;
+- endpoint ownership or generation drift; and
+- focus restoration failure after a bounded setup action.
+
+Any ambiguity produces a stable, non-mutating structured refusal.
+
+## Release Acceptance Per Compositor
+
+A compositor is listed as supported only after the canonical matrix records:
+
+1. exact compositor, distribution, browser product, and version provenance;
+2. setup, attach, reconnect, multi-tab, stale-ref, background type, trusted
+ input policy, and ambiguous-window rows;
+3. external page-state oracles rather than driver success responses;
+4. continuous focus, z-order or occlusion, and no-leaked-input guards;
+5. cursor preservation where the compositor exposes a trustworthy readback;
+6. before and after evidence plus playable video at the exact source commit;
+7. explicit environment results for missing APIs or accessibility trees; and
+8. generic and unknown Wayland sessions refusing before mutation.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
index 4cb7ac2ce5..7d2e9bfe84 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs
@@ -51,7 +51,10 @@ use super::store::{
format_ref, BrowserStore, FrameIdentity, FrameKind, FrameRef, RefEntry, SemanticContinuation,
SnapshotRecord, TabRecord, TargetRecord,
};
-use super::types::{BindingQuality, NativeWindowInfo, OwnedEndpoint, Rect};
+use super::types::{
+ BindingQuality, BrowserClassification, BrowserEngineFamily, NativeWindowInfo, OwnedEndpoint,
+ Rect,
+};
/// Bounds tolerance (device pixels) for native ↔ CDP window correlation.
/// Absorbs window-shadow and DIP-rounding differences.
@@ -82,6 +85,41 @@ fn route_err(context: &str, err: impl std::fmt::Display) -> BrowserRefusal {
)
}
+pub(super) fn unsupported_engine_refusal(
+ classification: &BrowserClassification,
+ operation: &'static str,
+) -> BrowserRefusal {
+ let (message, protocol, limitation) = match classification.engine {
+ BrowserEngineFamily::Gecko => (
+ "Firefox browser tools require a WebDriver BiDi or Remote Agent route; attaching to an ordinary running profile is not supported",
+ "webdriver_bidi",
+ "remote_agent_requires_launch_time_enablement",
+ ),
+ BrowserEngineFamily::Webkit => (
+ "Safari browser tools require a WebKit-native automation route; Safari does not expose an attachable CDP endpoint for an ordinary running profile",
+ "webkit_automation",
+ "no_attachable_runtime_endpoint",
+ ),
+ BrowserEngineFamily::Chromium => (
+ "this Chromium-family browser does not expose a supported CDP route",
+ "cdp",
+ "cdp_unavailable",
+ ),
+ BrowserEngineFamily::Unknown => (
+ "this browser engine has no supported typed browser route",
+ "unknown",
+ "engine_route_unavailable",
+ ),
+ };
+ BrowserRefusal::new(BrowserRefusalCode::BrowserRouteUnavailable, message).with_detail(json!({
+ "operation": operation,
+ "engine_family": classification.engine,
+ "product": classification.product_kind,
+ "required_protocol": protocol,
+ "limitation": limitation,
+ }))
+}
+
/// Everything revalidation proves before a mutation proceeds. The
/// `record`/`tab` evidence rides along for future callers even though
/// the v1 tools only need the attached connection.
@@ -866,13 +904,7 @@ impl BrowserEngine {
));
}
if !class.supports_cdp {
- return Err(refuse(
- BrowserRefusalCode::BrowserRouteUnavailable,
- format!(
- "{} does not expose a CDP route in browser-tool v1",
- class.product.as_deref().unwrap_or("this browser")
- ),
- ));
+ return Err(unsupported_engine_refusal(&class, "bind_native_window"));
}
let native = self.native_window_checked(pid, window_id).await?;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
index 22c8a6c101..06b4feda72 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
@@ -365,6 +365,13 @@ impl BrowserPointerTool {
"{limitation}; use input_route=\"dom_event\" with refs to explicitly request synthetic full-background pointer delivery"
),
)
+ .with_detail(json!({
+ "requested_route": "trusted",
+ "limitation": limitation,
+ "alternative_route": "dom_event",
+ "alternative_requires_ref": true,
+ "trusted_delivery_attempted": false,
+ }))
.to_tool_result(),
);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
index ebfaa0862d..ed77e98be9 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs
@@ -15,6 +15,7 @@ use super::approval::{
consume_existing_profile_approval, consume_prepare_approval, validate_profile,
ExistingProfileApprovalScope,
};
+use super::engine::unsupported_engine_refusal;
use super::platform::{
BrowserConsentOutcome, BrowserConsentRequest, ExistingProfileSetupOutcome,
ExistingProfileSetupRequest, PrepareAction, PrepareAttachment, PrepareAttachmentKind,
@@ -601,9 +602,9 @@ impl BrowserEngine {
let classification = self.platform.classify_browser(request.pid).await?;
if !classification.supports_cdp || classification.engine != BrowserEngineFamily::Chromium {
- return Err(refusal(
- BrowserRefusalCode::BrowserRouteUnavailable,
- "isolated automatic setup is currently supported only for Chromium browsers",
+ return Err(unsupported_engine_refusal(
+ &classification,
+ "prepare_isolated_profile",
));
}
let fingerprint = self.platform.process_fingerprint(request.pid).await?;
@@ -712,9 +713,9 @@ impl BrowserEngine {
let classification = self.platform.classify_browser(request.pid).await?;
if !classification.supports_cdp || classification.engine != BrowserEngineFamily::Chromium {
- return Err(refusal(
- BrowserRefusalCode::BrowserRouteUnavailable,
- "existing-profile attachment is currently limited to Chromium browsers",
+ return Err(unsupported_engine_refusal(
+ &classification,
+ "attach_existing_profile",
));
}
self.native_window_checked(request.pid, window_id).await?;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
index bdc9cf3b29..0677b3fec7 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
@@ -762,6 +762,13 @@ impl Tool for BrowserClickTool {
"{limitation}; use input_route=\"dom_event\" with a ref for a synthetic full-background click"
),
)
+ .with_detail(json!({
+ "requested_route": "trusted",
+ "limitation": limitation,
+ "alternative_route": "dom_event",
+ "alternative_requires_ref": true,
+ "trusted_delivery_attempted": false,
+ }))
.to_tool_result();
}
}
@@ -1827,6 +1834,14 @@ mod tests {
channel: None,
supports_cdp: false,
},
+ 4 => BrowserClassification {
+ is_browser: true,
+ engine: BrowserEngineFamily::Gecko,
+ product_kind: BrowserProduct::Firefox,
+ product: Some("MockFirefox".into()),
+ channel: None,
+ supports_cdp: false,
+ },
_ => BrowserClassification {
is_browser: false,
engine: BrowserEngineFamily::Unknown,
@@ -1843,6 +1858,10 @@ mod tests {
pid: i64,
window_id: u64,
) -> Result<NativeWindowInfo, BrowserRefusal> {
+ assert!(
+ !matches!(pid, 3 | 4),
+ "unsupported browser engines must refuse before native-window probing"
+ );
use crate::browser::types::{NativeOwnershipMethod, NativeOwnershipProof, Rect};
Ok(NativeWindowInfo {
pid,
@@ -2073,6 +2092,35 @@ mod tests {
structured(&result)["refusal"]["code"],
"browser_route_unavailable"
);
+ assert_eq!(
+ structured(&result)["refusal"]["detail"]["engine_family"],
+ "webkit"
+ );
+ assert_eq!(
+ structured(&result)["refusal"]["detail"]["product"],
+ "safari"
+ );
+ assert_eq!(
+ structured(&result)["refusal"]["detail"]["limitation"],
+ "no_attachable_runtime_endpoint"
+ );
+ }
+
+ #[tokio::test]
+ async fn firefox_refusal_names_the_required_protocol_without_probing_the_window() {
+ let tool = GetBrowserStateTool::new(engine());
+ let result = tool
+ .invoke(json!({ "pid": 4, "window_id": 7, "_session_id": "run-1" }))
+ .await;
+ let refusal = &structured(&result)["refusal"];
+ assert_eq!(refusal["code"], "browser_route_unavailable");
+ assert_eq!(refusal["detail"]["engine_family"], "gecko");
+ assert_eq!(refusal["detail"]["product"], "firefox");
+ assert_eq!(refusal["detail"]["required_protocol"], "webdriver_bidi");
+ assert_eq!(
+ refusal["detail"]["limitation"],
+ "remote_agent_requires_launch_time_enablement"
+ );
}
#[tokio::test]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
index 74311929ae..e4443e4226 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs
@@ -1647,6 +1647,14 @@ async fn trusted_click_refuses_when_standalone_background_posture_is_unavailable
structured(&trusted)["refusal"]["code"],
"browser_input_trust_unavailable"
);
+ assert_eq!(
+ structured(&trusted)["refusal"]["detail"]["alternative_route"],
+ "dom_event"
+ );
+ assert_eq!(
+ structured(&trusted)["refusal"]["detail"]["trusted_delivery_attempted"],
+ false
+ );
assert!(recorded_calls(&f, "Input.dispatchMouseEvent").is_empty());
let synthetic = BrowserClickTool::new(f.engine.clone())
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/browser_fixture.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/browser_fixture.rs
index eb9532d3c2..72e791a436 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/browser_fixture.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/browser_fixture.rs
@@ -1,9 +1,9 @@
use std::io::{Read, Write};
-use std::net::{TcpListener, TcpStream};
+use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
-use std::time::Duration;
+use std::time::{Duration, Instant};
/// Loopback HTTP host for the repo-owned browser fixture and its state oracle.
///
@@ -72,6 +72,8 @@ impl BrowserFixtureServer {
}
});
+ wait_until_ready(address);
+
Self {
page_url,
journal_url,
@@ -149,6 +151,34 @@ impl BrowserFixtureServer {
}
}
+fn wait_until_ready(address: SocketAddr) {
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ let ready = TcpStream::connect_timeout(&address, Duration::from_millis(200))
+ .and_then(|mut stream| {
+ stream.set_read_timeout(Some(Duration::from_millis(500)))?;
+ stream.write_all(
+ format!(
+ "GET /fixture HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n"
+ )
+ .as_bytes(),
+ )?;
+ let mut response = String::new();
+ stream.read_to_string(&mut response)?;
+ Ok(response.starts_with("HTTP/1.1 200 OK"))
+ })
+ .unwrap_or(false);
+ if ready {
+ return;
+ }
+ assert!(
+ Instant::now() < deadline,
+ "browser fixture server did not complete its startup probe"
+ );
+ thread::sleep(Duration::from_millis(10));
+ }
+}
+
fn handle_connection(
mut stream: TcpStream,
page: &[u8],
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index f0dbd19369..4dc69d7fa0 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -15,8 +15,9 @@ use std::thread;
use std::time::{Duration, Instant};
use cua_driver_testkit::e2e::{
- execute_case, recording_evidence, write_environment_from_env, CaseSpec, Delivery, DriverRoute,
- EnvironmentRecord, Evidence, Observation, OracleKind, RefusalCode, Scope, Targeting,
+ append_json_line, execute_case, recording_evidence, write_environment_from_env, CaseSpec,
+ Delivery, DriverRoute, EnvironmentRecord, Evidence, Observation, OracleKind, RefusalCode,
+ Scope, Targeting,
};
use cua_driver_testkit::observer::TargetWindow;
use cua_driver_testkit::sentinel::ForegroundSentinel;
@@ -166,6 +167,115 @@ struct BrowserSpec {
executable: PathBuf,
}
+const SUPPORTED_BROWSER_PRODUCTS: &[&str] = &["chrome", "chromium", "edge"];
+
+fn parse_browser_products(raw: &str) -> Result<Vec<String>, String> {
+ let mut products = Vec::new();
+ for product in raw
+ .split(',')
+ .map(str::trim)
+ .filter(|product| !product.is_empty())
+ {
+ let product = product.to_ascii_lowercase();
+ if !SUPPORTED_BROWSER_PRODUCTS.contains(&product.as_str()) {
+ return Err(format!(
+ "unsupported browser product {product:?}; expected one of {}",
+ SUPPORTED_BROWSER_PRODUCTS.join(", ")
+ ));
+ }
+ if products.contains(&product) {
+ return Err(format!("duplicate browser product {product:?}"));
+ }
+ products.push(product);
+ }
+ if products.is_empty() {
+ return Err("at least one browser product is required".to_owned());
+ }
+ Ok(products)
+}
+
+fn requested_browser_products() -> Option<Vec<String>> {
+ let raw = std::env::var("CUA_E2E_BROWSER_PRODUCTS").ok()?;
+ Some(
+ parse_browser_products(&raw)
+ .unwrap_or_else(|error| panic!("invalid CUA_E2E_BROWSER_PRODUCTS={raw:?}: {error}")),
+ )
+}
+
+fn dedupe_browser_products(browsers: Vec<BrowserSpec>) -> Vec<BrowserSpec> {
+ browsers.into_iter().fold(Vec::new(), |mut unique, spec| {
+ if !unique
+ .iter()
+ .any(|existing: &BrowserSpec| existing.name == spec.name)
+ {
+ unique.push(spec);
+ }
+ unique
+ })
+}
+
+#[test]
+fn browser_product_selection_is_ordered_and_strict() {
+ assert_eq!(
+ parse_browser_products("Edge, chrome,chromium").unwrap(),
+ ["edge", "chrome", "chromium"]
+ );
+ assert!(parse_browser_products("").is_err());
+ assert!(parse_browser_products("chrome,chrome").is_err());
+ assert!(parse_browser_products("firefox").is_err());
+
+ let deduped = dedupe_browser_products(vec![
+ BrowserSpec {
+ name: "chromium".to_owned(),
+ executable: PathBuf::from("/first/chromium"),
+ },
+ BrowserSpec {
+ name: "edge".to_owned(),
+ executable: PathBuf::from("/edge"),
+ },
+ BrowserSpec {
+ name: "chromium".to_owned(),
+ executable: PathBuf::from("/second/chromium"),
+ },
+ ]);
+ assert_eq!(deduped.len(), 2);
+ assert_eq!(deduped[0].executable, PathBuf::from("/first/chromium"));
+}
+
+fn select_browser_products(
+ mut browsers: Vec<BrowserSpec>,
+ prefer_chrome_over_chromium: bool,
+) -> Vec<BrowserSpec> {
+ if let Some(requested) = requested_browser_products() {
+ let missing = requested
+ .iter()
+ .filter(|product| !browsers.iter().any(|spec| &spec.name == *product))
+ .cloned()
+ .collect::<Vec<_>>();
+ assert!(
+ missing.is_empty(),
+ "requested standalone browser products were not found: {}",
+ missing.join(", ")
+ );
+ browsers.retain(|spec| requested.contains(&spec.name));
+ browsers.sort_by_key(|spec| {
+ requested
+ .iter()
+ .position(|product| product == &spec.name)
+ .unwrap_or(usize::MAX)
+ });
+ } else if prefer_chrome_over_chromium && browsers.iter().any(|spec| spec.name == "chrome") {
+ // Preserve the historical default lane: Chromium is the fallback when
+ // Chrome is absent. Certification runs opt into each product.
+ browsers.retain(|spec| spec.name != "chromium");
+ }
+ // A distro may expose one browser installation through several wrappers
+ // (for example /usr/bin/chromium-browser and /snap/bin/chromium). The
+ // certification matrix is product-scoped, so keep the first viable
+ // executable for each requested product instead of reporting duplicates.
+ dedupe_browser_products(browsers)
+}
+
struct BrowserFixture {
driver: McpDriver,
server: BrowserFixtureServer,
@@ -183,38 +293,43 @@ fn browser_specs() -> Vec<BrowserSpec> {
"CUA_E2E_BROWSER_BIN is not a file: {}",
executable.display()
);
- let name = std::env::var("CUA_E2E_BROWSER_NAME").unwrap_or_else(|_| "chromium".to_owned());
- return vec![BrowserSpec { name, executable }];
+ let name = std::env::var("CUA_E2E_BROWSER_NAME")
+ .unwrap_or_else(|_| "chromium".to_owned())
+ .to_ascii_lowercase();
+ return select_browser_products(vec![BrowserSpec { name, executable }], false);
}
#[cfg(target_os = "macos")]
{
let home = PathBuf::from(std::env::var_os("HOME").expect("HOME"));
- return [
- (
- "chrome",
- PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
- ),
- (
- "chrome",
- home.join("Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
- ),
- (
- "edge",
- PathBuf::from("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
- ),
- (
- "edge",
- home.join("Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
- ),
- ]
- .into_iter()
- .filter(|(_, executable)| executable.is_file())
- .map(|(name, executable)| BrowserSpec {
- name: name.to_owned(),
- executable,
- })
- .collect();
+ return select_browser_products(
+ [
+ (
+ "chrome",
+ PathBuf::from("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
+ ),
+ (
+ "chrome",
+ home.join("Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
+ ),
+ (
+ "edge",
+ PathBuf::from("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
+ ),
+ (
+ "edge",
+ home.join("Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
+ ),
+ ]
+ .into_iter()
+ .filter(|(_, executable)| executable.is_file())
+ .map(|(name, executable)| BrowserSpec {
+ name: name.to_owned(),
+ executable,
+ })
+ .collect(),
+ false,
+ );
}
#[cfg(target_os = "linux")]
{
@@ -223,6 +338,7 @@ fn browser_specs() -> Vec<BrowserSpec> {
("chromium", PathBuf::from("/usr/bin/chromium")),
("chromium", PathBuf::from("/usr/bin/chromium-browser")),
("edge", PathBuf::from("/usr/bin/microsoft-edge")),
+ ("edge", PathBuf::from("/usr/bin/microsoft-edge-stable")),
];
if let Some(path) = std::env::var_os("PATH") {
for (name, executable_name) in [
@@ -230,6 +346,7 @@ fn browser_specs() -> Vec<BrowserSpec> {
("chromium", "chromium"),
("chromium", "chromium-browser"),
("edge", "microsoft-edge"),
+ ("edge", "microsoft-edge-stable"),
] {
if let Some(executable) = std::env::split_paths(&path)
.map(|directory| directory.join(executable_name))
@@ -239,7 +356,7 @@ fn browser_specs() -> Vec<BrowserSpec> {
}
}
}
- let mut browsers = candidates
+ let browsers = candidates
.into_iter()
.filter(|(_, executable)| executable.is_file())
.map(|(name, executable)| {
@@ -267,13 +384,7 @@ fn browser_specs() -> Vec<BrowserSpec> {
.into_iter()
.map(|(spec, _)| spec)
.collect::<Vec<_>>();
- // Chromium is the open-source fallback for environments without the
- // Chrome stable channel. Do not expand a Chrome/Edge acceptance lane
- // merely because the host image also exposes a Chromium package shim.
- if browsers.iter().any(|spec| spec.name == "chrome") {
- browsers.retain(|spec| spec.name != "chromium");
- }
- return browsers;
+ return select_browser_products(browsers, true);
}
#[cfg(target_os = "windows")]
let candidates = {
@@ -286,35 +397,38 @@ fn browser_specs() -> Vec<BrowserSpec> {
let local_app_data = std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
.unwrap_or_default();
- return [
- (
- "chrome",
- program_files.join(r"Google\Chrome\Application\chrome.exe"),
- ),
- (
- "chrome",
- program_files_x86.join(r"Google\Chrome\Application\chrome.exe"),
- ),
- (
- "chrome",
- local_app_data.join(r"Google\Chrome\Application\chrome.exe"),
- ),
- (
- "edge",
- program_files_x86.join(r"Microsoft\Edge\Application\msedge.exe"),
- ),
- (
- "edge",
- program_files.join(r"Microsoft\Edge\Application\msedge.exe"),
- ),
- ]
- .into_iter()
- .filter(|(_, executable)| executable.is_file())
- .map(|(name, executable)| BrowserSpec {
- name: name.to_owned(),
- executable,
- })
- .collect();
+ return select_browser_products(
+ [
+ (
+ "chrome",
+ program_files.join(r"Google\Chrome\Application\chrome.exe"),
+ ),
+ (
+ "chrome",
+ program_files_x86.join(r"Google\Chrome\Application\chrome.exe"),
+ ),
+ (
+ "chrome",
+ local_app_data.join(r"Google\Chrome\Application\chrome.exe"),
+ ),
+ (
+ "edge",
+ program_files_x86.join(r"Microsoft\Edge\Application\msedge.exe"),
+ ),
+ (
+ "edge",
+ program_files.join(r"Microsoft\Edge\Application\msedge.exe"),
+ ),
+ ]
+ .into_iter()
+ .filter(|(_, executable)| executable.is_file())
+ .map(|(name, executable)| BrowserSpec {
+ name: name.to_owned(),
+ executable,
+ })
+ .collect(),
+ false,
+ );
};
}
@@ -379,6 +493,24 @@ fn wait_for_browser_endpoint(port: u16) {
}
}
+fn record_browser_provenance(spec: &BrowserSpec, port: u16) {
+ let Some(path) = std::env::var_os("CUA_E2E_BROWSER_PROVENANCE_FILE") else {
+ return;
+ };
+ let version = browser_http_json(port, "/json/version")
+ .unwrap_or_else(|error| panic!("read browser provenance: {error}"));
+ let record = serde_json::json!({
+ "schema": "cua-driver-browser-provenance-v1",
+ "source_sha": std::env::var("CUA_E2E_SOURCE_SHA").ok(),
+ "product": spec.name,
+ "browser": version.get("Browser"),
+ "protocol_version": version.get("Protocol-Version"),
+ "user_agent": version.get("User-Agent"),
+ });
+ append_json_line(Path::new(&path), &record)
+ .unwrap_or_else(|error| panic!("write browser provenance: {error}"));
+}
+
fn harness_cdp_call_at_url(
ws_url: &str,
method: &str,
@@ -560,7 +692,15 @@ fn profile_entries(root: &Path) -> HashSet<std::ffi::OsString> {
fn spawn_driver(label: &str) -> McpDriver {
#[cfg(target_os = "macos")]
let driver = McpDriver::spawn_macos_daemon_proxy_named(label);
- #[cfg(not(target_os = "macos"))]
+ #[cfg(target_os = "linux")]
+ let driver = if std::env::var("CUA_E2E_WAYLAND_SESSION").as_deref() == Ok("generic") {
+ // Keep Sway IPC available to the out-of-band test oracle while the
+ // product under test sees only standard/generic Wayland capabilities.
+ McpDriver::spawn_named_with_env(label, &[("SWAYSOCK", "/dev/null/cua-e2e-withheld")])
+ } else {
+ McpDriver::spawn_named(label)
+ };
+ #[cfg(all(not(target_os = "macos"), not(target_os = "linux")))]
let driver = McpDriver::spawn_named(label);
driver.expect("cua-driver binary/daemon is required for standalone browser E2E")
}
@@ -570,8 +710,7 @@ fn configure_linux_browser_command(command: &mut Command) {
command.arg("--password-store=basic");
let native_wayland = std::env::var("XDG_SESSION_TYPE")
.is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
- && std::env::var_os("WAYLAND_DISPLAY").is_some()
- && std::env::var_os("DISPLAY").is_none();
+ && std::env::var_os("WAYLAND_DISPLAY").is_some();
if native_wayland {
command.arg("--ozone-platform=wayland");
}
@@ -601,11 +740,7 @@ fn command_for_browser(
position: (i32, i32),
) -> Command {
let mut command = Command::new(&spec.executable);
- let output = if std::env::var_os("CUA_E2E_BROWSER_STDERR").is_some() {
- Stdio::inherit()
- } else {
- Stdio::null()
- };
+ let output = browser_stderr();
command
.arg(format!("--remote-debugging-port={cdp_port}"))
.arg(format!("--user-data-dir={}", profile.display()))
@@ -657,10 +792,18 @@ fn command_for_unprepared_browser(
.arg(url)
.stdin(Stdio::null())
.stdout(Stdio::null())
- .stderr(Stdio::null());
+ .stderr(browser_stderr());
command
}
+fn browser_stderr() -> Stdio {
+ if std::env::var_os("CUA_E2E_BROWSER_STDERR").is_some() {
+ Stdio::inherit()
+ } else {
+ Stdio::null()
+ }
+}
+
fn window_ids(driver: &mut McpDriver) -> HashSet<u64> {
driver
.call("list_windows", serde_json::json!({}))
@@ -704,6 +847,64 @@ fn wait_for_fixture_window(
}
}
if Instant::now() >= deadline {
+ eprintln!(
+ "standalone browser fixture window timed out; before={before:?}; windows={}; journal={}",
+ windows.raw,
+ server.snapshot()
+ );
+ return None;
+ }
+ thread::sleep(Duration::from_millis(100));
+ }
+}
+
+fn browser_app_name_matches(spec: &BrowserSpec, app_name: &str) -> bool {
+ let app_name = app_name.to_ascii_lowercase();
+ match spec.name.as_str() {
+ "chrome" => app_name.contains("chrome"),
+ "chromium" => app_name.contains("chromium"),
+ "edge" => app_name.contains("edge"),
+ _ => false,
+ }
+}
+
+fn wait_for_new_browser_window(
+ driver: &mut McpDriver,
+ before: &HashSet<u64>,
+ spec: &BrowserSpec,
+ launched_pid: u32,
+) -> Option<(u32, u64)> {
+ let deadline = Instant::now() + Duration::from_secs(40);
+ loop {
+ let windows = driver.call("list_windows", serde_json::json!({}));
+ if let Some(window) = windows.structured()["windows"]
+ .as_array()
+ .and_then(|windows| {
+ windows.iter().find(|window| {
+ window["window_id"]
+ .as_u64()
+ .is_some_and(|id| !before.contains(&id))
+ && window["is_on_screen"] == true
+ && window["bounds"]["width"].as_f64().unwrap_or_default() > 0.0
+ && window["bounds"]["height"].as_f64().unwrap_or_default() > 0.0
+ && (window["pid"].as_u64() == Some(u64::from(launched_pid))
+ || window["app_name"]
+ .as_str()
+ .is_some_and(|app_name| browser_app_name_matches(spec, app_name)))
+ })
+ })
+ {
+ return Some((
+ window["pid"].as_u64().expect("browser window pid") as u32,
+ window["window_id"].as_u64().expect("browser window id"),
+ ));
+ }
+ if Instant::now() >= deadline {
+ eprintln!(
+ "unprepared browser window timed out; product={}; launched_pid={launched_pid}; before={before:?}; windows={}",
+ spec.name,
+ windows.raw
+ );
return None;
}
thread::sleep(Duration::from_millis(100));
@@ -810,6 +1011,7 @@ fn launch_browser_with_html(spec: &BrowserSpec, label: &str, html: String) -> Br
TEST_BROWSER_INITIAL_POSITION,
);
navigate_initial_page(cdp_port, &server);
+ record_browser_provenance(spec, cdp_port);
let window = wait_for_fixture_window(&mut driver, &before, &server);
let (pid, window_id) = window.unwrap_or_else(|| {
panic!(
@@ -839,13 +1041,20 @@ fn launch_unprepared_browser(spec: &BrowserSpec, label: &str) -> BrowserFixture
let mut command = command_for_unprepared_browser(
spec,
profile.path(),
- server.page_url(),
+ "about:blank",
TEST_BROWSER_INITIAL_POSITION,
);
let child = spawn_in_job(&mut command).expect("launch unprepared standalone browser");
+ let launched_pid = child.id();
+ eprintln!(
+ "[standalone-browser] spawned unprepared {} pid={} profile={}",
+ spec.name,
+ child.id(),
+ profile.path().display()
+ );
driver.reaper().push(child);
- let (pid, window_id) = wait_for_fixture_window(&mut driver, &before, &server)
- .expect("unprepared browser fixture window");
+ let (pid, window_id) = wait_for_new_browser_window(&mut driver, &before, spec, launched_pid)
+ .expect("unprepared browser native window");
driver.reaper().track_pid(pid);
BrowserFixture {
driver,
@@ -1313,6 +1522,18 @@ fn run_trusted_click(spec: &BrowserSpec) {
"{}",
click.raw
);
+ assert_eq!(
+ click.structured()["refusal"]["detail"]["alternative_route"],
+ "dom_event",
+ "{}",
+ click.raw
+ );
+ assert_eq!(
+ click.structured()["refusal"]["detail"]["trusted_delivery_attempted"],
+ false,
+ "{}",
+ click.raw
+ );
wait_for_text(&fixture.server, "lbl-counter", "counter=0");
Observation::refused(
RefusalCode::BrowserInputTrustUnavailable,
@@ -1338,7 +1559,6 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {
execute_case(
case(&spec.name, "browser_prepare_isolated_launch"),
|evidence| {
- let source_server = BrowserFixtureServer::start(&standalone_fixture_html());
let target_server = BrowserFixtureServer::start(&standalone_fixture_html());
let source_profile = tempfile::Builder::new()
.prefix("cua-e2e-user-browser-")
@@ -1353,14 +1573,21 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {
let mut source_command = command_for_unprepared_browser(
spec,
source_profile.path(),
- source_server.page_url(),
+ "about:blank",
TEST_BROWSER_INITIAL_POSITION,
);
let source_child = spawn_in_job(&mut source_command).expect("launch ordinary browser");
+ let launched_pid = source_child.id();
+ eprintln!(
+ "[standalone-browser] spawned ordinary {} pid={} profile={}",
+ spec.name,
+ source_child.id(),
+ source_profile.path().display()
+ );
driver.reaper().push(source_child);
let (source_pid, source_window_id) =
- wait_for_fixture_window(&mut driver, &before, &source_server)
- .expect("ordinary browser fixture window");
+ wait_for_new_browser_window(&mut driver, &before, spec, launched_pid)
+ .expect("ordinary browser native window");
driver.reaper().track_pid(source_pid);
let session = format!("standalone-prepare-{source_pid}");
@@ -1466,7 +1693,6 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {
);
assert_eq!(clicked.structured()["status"], "ok", "{}", clicked.raw);
wait_for_text(&target_server, "lbl-counter", "counter=1");
- wait_for_text(&source_server, "lbl-counter", "counter=0");
let source_windows =
driver.call("list_windows", serde_json::json!({"pid": source_pid}));
assert!(
@@ -1772,6 +1998,17 @@ fn run_existing_profile_setup(spec: &BrowserSpec) {
.and_then(|tab| tab["tab_id"].as_str())
.expect("existing-profile setup active tab")
.to_owned();
+ let navigated = fixture.driver.call(
+ "browser_navigate",
+ serde_json::json!({
+ "target_id": target,
+ "tab_id": tab,
+ "url": fixture.server.page_url(),
+ "session": session,
+ }),
+ );
+ assert_eq!(navigated.structured()["status"], "ok", "{}", navigated.raw);
+ wait_for_observed(&fixture.server, "WEB_HARNESS_MARKER_v1");
let snapshot = fixture.driver.call(
"get_browser_state",
serde_json::json!({
@@ -1816,6 +2053,119 @@ fn run_existing_profile_setup(spec: &BrowserSpec) {
);
}
+#[cfg(target_os = "linux")]
+fn run_generic_wayland_existing_profile_refusal(spec: &BrowserSpec) {
+ assert!(
+ std::env::var_os("WAYLAND_DISPLAY").is_some()
+ && std::env::var("CUA_E2E_WAYLAND_SESSION").as_deref() == Ok("generic"),
+ "the generic-Wayland refusal row requires its explicit native-Wayland lane"
+ );
+ assert!(
+ platform_linux::wayland::shell_helper::trusted_window_ids_for_pid(std::process::id())
+ .is_none(),
+ "the generic-Wayland refusal row requires the attested GNOME helper to be unavailable"
+ );
+ let scenario = format!(
+ "{}-{}-standalone-generic-wayland-existing-profile-refusal",
+ std::env::consts::OS,
+ spec.name
+ );
+ execute_case(
+ refusal_case(
+ &spec.name,
+ "browser_prepare_existing_profile_generic_wayland",
+ RefusalCode::BrowserRouteUnavailable,
+ ),
+ |evidence| {
+ let mut driver = spawn_driver(&scenario);
+ let server = BrowserFixtureServer::start(&standalone_fixture_html());
+ let profile = tempfile::Builder::new()
+ .prefix("cua-e2e-generic-wayland-browser-")
+ .tempdir()
+ .expect("create generic Wayland browser profile");
+ let mut command = command_for_unprepared_browser(
+ spec,
+ profile.path(),
+ server.page_url(),
+ TEST_BROWSER_INITIAL_POSITION,
+ );
+ let child = spawn_in_job(&mut command).expect("launch generic Wayland browser");
+ let pid = child.id();
+ driver.reaper().push(child);
+ driver.reaper().track_pid(pid);
+ wait_for_observed(&server, "WEB_HARNESS_MARKER_v1");
+
+ let windows = driver.call("list_windows", serde_json::json!({"pid": pid}));
+ let opaque_window = windows.structured()["windows"]
+ .as_array()
+ .and_then(|windows| windows.iter().find(|window| window["pid"] == pid))
+ .unwrap_or_else(|| {
+ panic!(
+ "generic Wayland did not expose the browser's opaque native window: {}",
+ windows.raw
+ )
+ });
+ let opaque_unattested_window_id = opaque_window["window_id"]
+ .as_u64()
+ .expect("opaque generic Wayland window id");
+ assert!(
+ opaque_window["z_index"].is_null(),
+ "generic Wayland must not treat an AT-SPI window as compositor-attested: {}",
+ windows.raw
+ );
+
+ let sentinel = ForegroundSentinel::launch(&mut driver);
+ *evidence = recording_evidence(driver.recording_dir());
+ driver.start_behavior_recording();
+ let (mut observation, passed) = sentinel
+ .observe_desktop(|| {
+ let session = format!("generic-wayland-refusal-{pid}");
+ let started =
+ driver.call("start_session", serde_json::json!({ "session": session }));
+ assert!(!started.is_error(), "start_session failed: {}", started.raw);
+ let approval_token =
+ mint_existing_profile_approval(ExistingProfileApprovalScope {
+ pid: pid as i64,
+ window_id: opaque_unattested_window_id,
+ session: session.clone(),
+ })
+ .expect("mint generic-Wayland adversarial approval");
+ let refused = driver.call(
+ "browser_prepare",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": opaque_unattested_window_id,
+ "session": session,
+ "strategy": {"kind": "existing_profile"},
+ "approval_token": approval_token,
+ }),
+ );
+ assert_eq!(
+ refused.structured()["refusal"]["code"],
+ "browser_route_unavailable",
+ "{}",
+ refused.raw
+ );
+ assert!(
+ refused.structured()["refusal"]["detail"]["setup_side_effects"].is_null(),
+ "generic Wayland must refuse before setup mutation: {}",
+ refused.raw
+ );
+ wait_for_text(&server, "lbl-counter", "counter=0");
+ Observation::refused(
+ RefusalCode::BrowserRouteUnavailable,
+ vec![OracleKind::FixtureState],
+ refused.text(),
+ Evidence::default(),
+ )
+ })
+ .expect("observe generic Wayland refusal desktop effects");
+ observation.passed_oracles.extend(passed);
+ observation
+ },
+ );
+}
+
fn run_stale_ref(spec: &BrowserSpec) {
let scenario = format!(
"{}-{}-standalone-stale-ref",
@@ -2670,7 +3020,20 @@ fn run_download(spec: &BrowserSpec) {
run_with_background_oracles(&mut fixture, |fixture| {
let session = format!("standalone-download-{}", fixture.pid);
let (target, tab, snapshot) = bind(fixture, &session);
- let destination = tempfile::tempdir().expect("create approved download directory");
+ // Sandboxed browser packages such as Ubuntu's Chromium snap use a
+ // private /tmp namespace. A temporary directory under HOME remains
+ // visible to both the browser and the driver while still being
+ // removed automatically when the fixture exits.
+ let home = std::env::var_os("HOME")
+ .or_else(|| std::env::var_os("USERPROFILE"))
+ .map(PathBuf::from)
+ .expect("browser E2E home directory");
+ let destination = tempfile::Builder::new()
+ // Snap grants ordinary home-directory access but intentionally
+ // excludes arbitrary dotfiles and hidden directories.
+ .prefix("cua-e2e-download-")
+ .tempdir_in(home)
+ .expect("create approved download directory");
let canonical =
std::fs::canonicalize(destination.path()).expect("canonical download directory");
let downloaded = fixture.driver.call(
@@ -2835,6 +3198,11 @@ standalone_browser_test!(
standalone_browser_existing_profile_setup,
run_existing_profile_setup
);
+#[cfg(target_os = "linux")]
+standalone_browser_test!(
+ standalone_browser_generic_wayland_existing_profile_refusal,
+ run_generic_wayland_existing_profile_refusal
+);
standalone_browser_test!(standalone_browser_stale_ref, run_stale_ref);
standalone_browser_test!(standalone_browser_frames, run_frame_roundtrip);
standalone_browser_test!(standalone_browser_multi_tab, run_multi_tab);
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
index 22cdbe2eda..c0b76d2327 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
@@ -165,10 +165,13 @@ fn with_target_foreground<T>(
body: impl FnOnce() -> anyhow::Result<T>,
) -> anyhow::Result<T> {
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
- let window = crate::wayland::sway_ipc::window_for_id(window_id)
- .filter(|window| window.pid == pid)
- .ok_or_else(|| anyhow::anyhow!("no exact Sway container owns the approved window"))?;
- crate::wayland::sway_ipc::with_focused_container(window.id, body)
+ if let Some(window) =
+ crate::wayland::sway_ipc::window_for_id(window_id).filter(|window| window.pid == pid)
+ {
+ crate::wayland::sway_ipc::with_focused_container(window.id, body)
+ } else {
+ crate::wayland::shell_helper::with_focused_window(pid, window_id, body)
+ }
} else {
crate::input::with_x11_foreground(window_id, 80, body)
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
index 24dd9d09b9..ddfb17f355 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs
@@ -475,6 +475,30 @@ impl BrowserPlatform for LinuxBrowserPlatform {
},
});
}
+ if let Some(window) =
+ crate::wayland::shell_helper::trusted_window_for_id(pid_u32, window_id)
+ {
+ return Ok(NativeWindowInfo {
+ pid,
+ window_id,
+ title: window.title,
+ bounds: Rect::new(
+ f64::from(window.x),
+ f64::from(window.y),
+ f64::from(window.width),
+ f64::from(window.height),
+ ),
+ geometry_exact: true,
+ ownership: NativeOwnershipProof {
+ method: NativeOwnershipMethod::PlatformAttested,
+ owner_pid: pid,
+ detail: Some(
+ "verified GNOME Shell helper owner, stable window id, pid, and frame rect"
+ .to_owned(),
+ ),
+ },
+ });
+ }
let window = tokio::task::spawn_blocking(move || {
crate::wayland::list_windows_dispatch(Some(pid_u32))
.into_iter()
@@ -560,6 +584,11 @@ impl BrowserPlatform for LinuxBrowserPlatform {
})?;
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
let Some(windows) = crate::wayland::sway_ipc::list_windows() else {
+ if let Some(owned) =
+ crate::wayland::shell_helper::trusted_window_ids_for_pid(pid_u32)
+ {
+ return Ok(Some(owned.len() == 1 && owned[0] == window_id));
+ }
if crate::wayland::is_inject_mode() {
// The private cua-compositor route owns both the native
// toplevel enumeration and its PID correlation. Unlike a
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
index c50ad37e33..77f7d81e14 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
@@ -143,10 +143,13 @@ fn with_target_foreground<T>(
body: impl FnOnce() -> anyhow::Result<T>,
) -> anyhow::Result<T> {
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
- let window = crate::wayland::sway_ipc::window_for_id(window_id)
- .filter(|window| window.pid == pid)
- .ok_or_else(|| anyhow::anyhow!("no exact Sway container owns the approved window"))?;
- crate::wayland::sway_ipc::with_focused_container(window.id, body)
+ if let Some(window) =
+ crate::wayland::sway_ipc::window_for_id(window_id).filter(|window| window.pid == pid)
+ {
+ crate::wayland::sway_ipc::with_focused_container(window.id, body)
+ } else {
+ crate::wayland::shell_helper::with_focused_window(pid, window_id, body)
+ }
} else {
crate::input::with_x11_foreground(window_id, 80, body)
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs b/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs
index 291e7cb7fb..0a525d8865 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs
@@ -1,12 +1,14 @@
-//! Native Wayland full-desktop video capture through `wf-recorder`.
+//! Native Wayland full-desktop video capture.
//!
-//! FFmpeg's Linux input backend is X11-only. On a native Wayland session,
-//! `wf-recorder` consumes the compositor's screencopy protocol and writes the
-//! same MP4 artifact shape expected by the shared recording session.
+//! wlroots compositors use `wf-recorder`. GNOME does not expose the wlroots
+//! screencopy protocol, so its attested Shell helper supplies compositor-owned
+//! PNG frames which are encoded into the same MP4 artifact through FFmpeg.
use std::io::Read;
+use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
+use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::{Duration, Instant};
use cua_driver_core::video::{VideoBackend, VideoBackendFactory, VideoMetadata};
@@ -15,11 +17,155 @@ pub struct WfRecorderVideoBackendFactory;
impl VideoBackendFactory for WfRecorderVideoBackendFactory {
fn start(&self, output_path: &Path) -> anyhow::Result<Box<dyn VideoBackend>> {
+ if let Some(first_frame) = crate::wayland::shell_helper::trusted_screenshot_display() {
+ return GnomeShellVideoBackend::start(output_path, first_frame)
+ .map(|backend| Box::new(backend) as Box<dyn VideoBackend>);
+ }
WfRecorderVideoBackend::start(output_path)
.map(|backend| Box::new(backend) as Box<dyn VideoBackend>)
}
}
+struct GnomeShellVideoBackend {
+ stop_tx: mpsc::Sender<()>,
+ worker: std::thread::JoinHandle<anyhow::Result<()>>,
+ output_path: PathBuf,
+ started_at: Instant,
+}
+
+impl GnomeShellVideoBackend {
+ fn start(output_path: &Path, first_frame: Vec<u8>) -> anyhow::Result<Self> {
+ let available = Command::new("ffmpeg")
+ .arg("-version")
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .map(|status| status.success())
+ .unwrap_or(false);
+ if !available {
+ anyhow::bail!("ffmpeg is required for GNOME Wayland video capture");
+ }
+ if let Some(parent) = output_path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+
+ let output_path = output_path.to_path_buf();
+ let worker_output = output_path.clone();
+ let (stop_tx, stop_rx) = mpsc::channel();
+ let (ready_tx, ready_rx) = mpsc::sync_channel(1);
+ let worker = std::thread::spawn(move || {
+ let result = run_gnome_shell_encoder(&worker_output, first_frame, stop_rx, &ready_tx);
+ if result.is_err() {
+ let _ = ready_tx.send(result.as_ref().map(|_| ()).map_err(ToString::to_string));
+ }
+ result
+ });
+ match ready_rx.recv_timeout(Duration::from_secs(8)) {
+ Ok(Ok(())) => Ok(Self {
+ stop_tx,
+ worker,
+ output_path,
+ started_at: Instant::now(),
+ }),
+ Ok(Err(error)) => {
+ let _ = worker.join();
+ anyhow::bail!("GNOME Wayland video failed to start: {error}")
+ }
+ Err(error) => {
+ let _ = stop_tx.send(());
+ let _ = worker.join();
+ anyhow::bail!("GNOME Wayland video startup timed out: {error}")
+ }
+ }
+ }
+}
+
+fn run_gnome_shell_encoder(
+ output_path: &Path,
+ first_frame: Vec<u8>,
+ stop_rx: mpsc::Receiver<()>,
+ ready_tx: &mpsc::SyncSender<Result<(), String>>,
+) -> anyhow::Result<()> {
+ let mut child = Command::new("ffmpeg")
+ .args([
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "image2pipe",
+ "-framerate",
+ "5",
+ "-vcodec",
+ "png",
+ "-i",
+ "-",
+ "-an",
+ "-vf",
+ "pad=ceil(iw/2)*2:ceil(ih/2)*2",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-movflags",
+ "+faststart",
+ "-y",
+ ])
+ .arg(output_path)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::null())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| anyhow::anyhow!("failed to start GNOME FFmpeg encoder: {error}"))?;
+ let mut stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| anyhow::anyhow!("GNOME FFmpeg encoder exposed no stdin"))?;
+ stdin.write_all(&first_frame)?;
+ stdin.flush()?;
+ let _ = ready_tx.send(Ok(()));
+
+ loop {
+ match stop_rx.recv_timeout(Duration::from_millis(200)) {
+ Ok(()) | Err(RecvTimeoutError::Disconnected) => break,
+ Err(RecvTimeoutError::Timeout) => {
+ let frame = crate::wayland::shell_helper::trusted_screenshot_display()
+ .ok_or_else(|| anyhow::anyhow!("trusted GNOME compositor capture stopped"))?;
+ stdin.write_all(&frame)?;
+ stdin.flush()?;
+ }
+ }
+ }
+ drop(stdin);
+ let output = child.wait_with_output()?;
+ if !output.status.success() {
+ anyhow::bail!(
+ "GNOME FFmpeg encoder exited with {}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+ if output_path.metadata().map(|meta| meta.len()).unwrap_or(0) == 0 {
+ anyhow::bail!("GNOME FFmpeg encoder produced an empty artifact");
+ }
+ Ok(())
+}
+
+impl VideoBackend for GnomeShellVideoBackend {
+ fn stop(self: Box<Self>) -> anyhow::Result<VideoMetadata> {
+ let elapsed = self.started_at.elapsed();
+ let _ = self.stop_tx.send(());
+ match self.worker.join() {
+ Ok(result) => result?,
+ Err(_) => anyhow::bail!("GNOME Wayland video worker panicked"),
+ }
+ Ok(VideoMetadata {
+ path: self.output_path,
+ duration_ms: elapsed.as_millis() as u64,
+ finalized: true,
+ })
+ }
+}
+
struct WfRecorderVideoBackend {
child: Child,
output_path: PathBuf,
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
index 4ec0524135..0185d390d6 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/shell_helper.rs
@@ -20,6 +20,7 @@
//! there's no zbus blocking-feature or async-context coupling — the calls are
//! infrequent (once per `get_window_state`, a few per click).
+use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::process::Command;
use std::time::Duration;
@@ -28,26 +29,64 @@ use crate::x11::WindowInfo;
const DEST: &str = "org.cua.WinRects";
const PATH: &str = "/org/cua/WinRects";
const IFACE: &str = "org.cua.WinRects";
+const DBUS_DEST: &str = "org.freedesktop.DBus";
+const DBUS_PATH: &str = "/org/freedesktop/DBus";
+const DBUS_IFACE: &str = "org.freedesktop.DBus";
+const BROWSER_HELPER_API_VERSION: u32 = 4;
+
+#[derive(Debug, Clone)]
+struct ShellWindow {
+ info: WindowInfo,
+ focused: bool,
+}
pub fn available() -> bool {
- static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *AVAILABLE.get_or_init(|| gdbus_call("GetRects", &[]).is_some())
+ shell_owner(false).is_some()
}
fn gdbus_call(method: &str, args: &[String]) -> Option<String> {
- gdbus_call_with_timeout(method, args, Duration::from_millis(800))
+ let owner = shell_owner(false)?;
+ gdbus_call_to(
+ &owner,
+ PATH,
+ &format!("{IFACE}.{method}"),
+ args,
+ Duration::from_millis(800),
+ )
}
fn gdbus_call_with_timeout(method: &str, args: &[String], timeout: Duration) -> Option<String> {
+ let owner = shell_owner(false)?;
+ gdbus_call_to(&owner, PATH, &format!("{IFACE}.{method}"), args, timeout)
+}
+
+fn trusted_gdbus_call(method: &str, args: &[String]) -> Option<String> {
+ let owner = shell_owner(true)?;
+ gdbus_call_to(
+ &owner,
+ PATH,
+ &format!("{IFACE}.{method}"),
+ args,
+ Duration::from_millis(800),
+ )
+}
+
+fn gdbus_call_to(
+ destination: &str,
+ object_path: &str,
+ method: &str,
+ args: &[String],
+ timeout: Duration,
+) -> Option<String> {
let mut cmd = Command::new("gdbus");
cmd.arg("call")
.arg("--session")
.arg("--dest")
- .arg(DEST)
+ .arg(destination)
.arg("--object-path")
- .arg(PATH)
+ .arg(object_path)
.arg("--method")
- .arg(format!("{IFACE}.{method}"));
+ .arg(method);
for a in args {
cmd.arg(a);
}
@@ -65,6 +104,101 @@ fn gdbus_call_with_timeout(method: &str, args: &[String], timeout: Duration) ->
Some(String::from_utf8_lossy(&out.stdout).into_owned())
}
+/// Resolve the helper's immutable unique bus name and prove that it is hosted
+/// by this user's system-installed GNOME Shell process. Browser-sensitive
+/// callers additionally require the current helper API. Calling the unique
+/// name closes the race where another process replaces the well-known name
+/// after ownership is checked.
+fn shell_owner(require_browser_api: bool) -> Option<String> {
+ let owner_raw = gdbus_call_to(
+ DBUS_DEST,
+ DBUS_PATH,
+ &format!("{DBUS_IFACE}.GetNameOwner"),
+ &[DEST.to_owned()],
+ Duration::from_millis(800),
+ )?;
+ let owner = parse_quoted_string(&owner_raw)?;
+ if !owner.starts_with(':') {
+ return None;
+ }
+
+ let pid_raw = gdbus_call_to(
+ DBUS_DEST,
+ DBUS_PATH,
+ &format!("{DBUS_IFACE}.GetConnectionUnixProcessID"),
+ &[owner.clone()],
+ Duration::from_millis(800),
+ )?;
+ let uid_raw = gdbus_call_to(
+ DBUS_DEST,
+ DBUS_PATH,
+ &format!("{DBUS_IFACE}.GetConnectionUnixUser"),
+ &[owner.clone()],
+ Duration::from_millis(800),
+ )?;
+ let pid = parse_first_u32(&pid_raw)?;
+ let uid = parse_first_u32(&uid_raw)?;
+ if uid != current_uid() || !is_trusted_gnome_shell(pid) {
+ return None;
+ }
+
+ if require_browser_api {
+ let version_raw = gdbus_call_to(
+ &owner,
+ PATH,
+ &format!("{IFACE}.GetVersion"),
+ &[],
+ Duration::from_millis(800),
+ )?;
+ if parse_first_u32(&version_raw)? < BROWSER_HELPER_API_VERSION {
+ return None;
+ }
+ }
+ Some(owner)
+}
+
+fn parse_quoted_string(raw: &str) -> Option<String> {
+ let start = raw.find('\'')? + 1;
+ let end = raw[start..].find('\'')? + start;
+ (end > start).then(|| raw[start..end].to_owned())
+}
+
+fn parse_first_u32(raw: &str) -> Option<u32> {
+ // `gdbus call` renders typed scalars as `(uint32 6079,)`. Searching the
+ // whole string would incorrectly return the `32` in the type annotation.
+ let payload = raw.split_once("uint32").map_or(raw, |(_, payload)| payload);
+ payload
+ .split(|character: char| !character.is_ascii_digit())
+ .find(|part| !part.is_empty())?
+ .parse()
+ .ok()
+}
+
+fn current_uid() -> u32 {
+ std::fs::metadata("/proc/self")
+ .map(|meta| meta.uid())
+ .unwrap_or(u32::MAX)
+}
+
+fn is_trusted_gnome_shell(pid: u32) -> bool {
+ let comm = std::fs::read_to_string(format!("/proc/{pid}/comm")).ok();
+ if comm.as_deref().map(str::trim) != Some("gnome-shell") {
+ return false;
+ }
+ let executable = std::fs::read_link(format!("/proc/{pid}/exe")).ok();
+ let metadata = executable
+ .as_ref()
+ .and_then(|path| std::fs::metadata(path).ok());
+ executable
+ .as_ref()
+ .and_then(|path| path.file_name())
+ .and_then(|name| name.to_str())
+ == Some("gnome-shell")
+ && metadata
+ .as_ref()
+ .is_some_and(|meta| meta.uid() == 0 && meta.permissions().mode() & 0o022 == 0)
+}
+
/// Capture the GNOME stage through the compositor helper.
///
/// Mutter does not expose wlroots screencopy protocols, and its one-shot
@@ -73,9 +207,27 @@ fn gdbus_call_with_timeout(method: &str, args: &[String], timeout: Duration) ->
/// can use Shell's screenshot API without confusing a stable Wayland window id
/// for an X11 drawable.
pub fn screenshot_display() -> Option<Vec<u8>> {
+ let raw = gdbus_call_with_timeout("Capture", &[], Duration::from_secs(5))?;
+ decode_capture(&raw)
+}
+
+/// Capture the GNOME stage only when the helper owner and current browser API
+/// have passed the same compositor-attestation checks used for mutation.
+pub fn trusted_screenshot_display() -> Option<Vec<u8>> {
+ let owner = shell_owner(true)?;
+ let raw = gdbus_call_to(
+ &owner,
+ PATH,
+ &format!("{IFACE}.Capture"),
+ &[],
+ Duration::from_secs(5),
+ )?;
+ decode_capture(&raw)
+}
+
+fn decode_capture(raw: &str) -> Option<Vec<u8>> {
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
- let raw = gdbus_call_with_timeout("Capture", &[], Duration::from_secs(5))?;
let start = raw.find('\'')? + 1;
let end = raw.rfind('\'')?;
if end <= start {
@@ -176,6 +328,71 @@ pub fn list_windows(filter_pid: Option<u32>) -> Option<Vec<WindowInfo>> {
parse_windows(&raw, filter_pid)
}
+/// Return one compositor-attested GNOME window only when the current helper
+/// API is hosted by the verified Shell owner.
+pub fn trusted_window_for_id(pid: u32, window_id: u64) -> Option<WindowInfo> {
+ trusted_shell_windows(Some(pid))?
+ .into_iter()
+ .find(|window| window.info.xid == window_id)
+ .map(|window| window.info)
+}
+
+/// Enumerate exact browser-window ids for one process through the verified
+/// GNOME Shell helper. `None` means no trusted helper is available; an empty
+/// vector means the trusted helper found no owned windows.
+pub fn trusted_window_ids_for_pid(pid: u32) -> Option<Vec<u64>> {
+ Some(
+ trusted_shell_windows(Some(pid))?
+ .into_iter()
+ .map(|window| window.info.xid)
+ .collect(),
+ )
+}
+
+/// Briefly activate an exact compositor-owned window, execute one bounded
+/// focus-sensitive operation, and restore the prior exact Shell focus.
+pub fn with_focused_window<T>(
+ pid: u32,
+ window_id: u64,
+ body: impl FnOnce() -> anyhow::Result<T>,
+) -> anyhow::Result<T> {
+ let before = trusted_shell_windows(None)
+ .ok_or_else(|| anyhow::anyhow!("the verified GNOME Shell helper API is unavailable"))?;
+ let target = before
+ .iter()
+ .find(|window| window.info.pid == Some(pid) && window.info.xid == window_id)
+ .ok_or_else(|| anyhow::anyhow!("no exact GNOME Shell window owns the approved target"))?;
+ let previous = before
+ .iter()
+ .find(|window| window.focused)
+ .map(|window| window.info.xid)
+ .ok_or_else(|| anyhow::anyhow!("GNOME Shell did not expose a restorable focused window"))?;
+
+ if target.focused {
+ return body();
+ }
+ trusted_activate_window(window_id)
+ .then_some(())
+ .ok_or_else(|| anyhow::anyhow!("GNOME Shell did not confirm exact target activation"))?;
+ let body_result = body();
+ let restored = trusted_activate_window(previous);
+ match (body_result, restored) {
+ (Ok(value), true) => Ok(value),
+ (Err(error), true) => Err(error),
+ (Ok(_), false) => {
+ anyhow::bail!("GNOME Shell did not restore the previously focused window")
+ }
+ (Err(error), false) => Err(anyhow::anyhow!(
+ "{error}; GNOME Shell also failed to restore the previously focused window"
+ )),
+ }
+}
+
+fn trusted_shell_windows(filter_pid: Option<u32>) -> Option<Vec<ShellWindow>> {
+ let raw = trusted_gdbus_call("GetRects", &[])?;
+ parse_shell_windows(&raw, filter_pid)
+}
+
/// Ask GNOME Shell to focus and raise one stable-sequence window.
///
/// Returns `false` when the helper is absent, the id is unknown, or Shell did
@@ -195,6 +412,23 @@ pub fn activate_window(window_id: u64) -> bool {
window_is_focused(window_id)
}
+fn trusted_activate_window(window_id: u64) -> bool {
+ let Ok(window_id) = u32::try_from(window_id) else {
+ return false;
+ };
+ let accepted = trusted_gdbus_call("Activate", &[window_id.to_string()])
+ .is_some_and(|output| output.trim_start().starts_with("(true,"));
+ if !accepted {
+ return false;
+ }
+ std::thread::sleep(Duration::from_millis(60));
+ trusted_shell_windows(None).is_some_and(|windows| {
+ windows
+ .into_iter()
+ .any(|window| window.info.xid == u64::from(window_id) && window.focused)
+ })
+}
+
fn window_is_focused(window_id: u32) -> bool {
let Some(raw) = gdbus_call("GetRects", &[]) else {
return false;
@@ -214,6 +448,15 @@ fn window_is_focused(window_id: u32) -> bool {
}
fn parse_windows(raw: &str, filter_pid: Option<u32>) -> Option<Vec<WindowInfo>> {
+ Some(
+ parse_shell_windows(raw, filter_pid)?
+ .into_iter()
+ .map(|window| window.info)
+ .collect(),
+ )
+}
+
+fn parse_shell_windows(raw: &str, filter_pid: Option<u32>) -> Option<Vec<ShellWindow>> {
let start = raw.find('[')?;
let end = raw.rfind(']')?;
let windows: Vec<serde_json::Value> = serde_json::from_str(&raw[start..=end]).ok()?;
@@ -249,17 +492,23 @@ fn parse_windows(raw: &str, filter_pid: Option<u32>) -> Option<Vec<WindowInfo>>
.and_then(serde_json::Value::as_u64)
.and_then(|value| usize::try_from(value).ok());
- Some(WindowInfo {
- xid: id,
- pid: Some(pid),
- app_name: title.clone(),
- title,
- is_on_screen: visible && !minimized && width > 0 && height > 0,
- z_index,
- x,
- y,
- width,
- height,
+ Some(ShellWindow {
+ info: WindowInfo {
+ xid: id,
+ pid: Some(pid),
+ app_name: title.clone(),
+ title,
+ is_on_screen: visible && !minimized && width > 0 && height > 0,
+ z_index,
+ x,
+ y,
+ width,
+ height,
+ },
+ focused: window
+ .get("focused")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(false),
})
})
.collect(),
@@ -306,4 +555,27 @@ mod tests {
assert_eq!(windows.len(), 1);
assert!(!windows[0].is_on_screen);
}
+
+ #[test]
+ fn parses_dbus_owner_and_numeric_identity() {
+ assert_eq!(
+ parse_quoted_string("(':1.204',)"),
+ Some(":1.204".to_owned())
+ );
+ assert_eq!(parse_first_u32("(uint32 6079,)"), Some(6079));
+ assert_eq!(parse_first_u32("(uint32 4,)"), Some(4));
+ assert_eq!(parse_first_u32("(6079,)"), Some(6079));
+ assert_eq!(parse_quoted_string("(nothing,)"), None);
+ assert_eq!(parse_first_u32("(nothing,)"), None);
+ }
+
+ #[test]
+ fn preserves_exact_focus_from_shell_snapshot() {
+ let raw = r#"('[{"id":46,"pid":6079,"title":"Target","x":66,"y":32,"w":958,"h":736,"focused":false,"minimized":false,"visible":true,"stacking":2},{"id":47,"pid":6080,"title":"Sentinel","x":0,"y":0,"w":100,"h":100,"focused":true,"minimized":false,"visible":true,"stacking":3}]',)"#;
+ let windows = parse_shell_windows(raw, None).expect("valid helper response");
+ assert_eq!(windows.len(), 2);
+ assert!(!windows[0].focused);
+ assert!(windows[1].focused);
+ assert_eq!(windows[1].info.xid, 47);
+ }
}
diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
index edeb4c4e49..ba7c75efda 100644
--- a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/main.js
@@ -58,6 +58,7 @@ ipcMain.on('cua-e2e-sentinel-event', (_event, entry) => {
});
let mainWindow;
+let sentinelHeartbeatTimer;
function createWindow() {
const fixedTitle = sentinelMode
@@ -129,6 +130,18 @@ function createWindow() {
if (mainWindow && !mainWindow.isDestroyed()) {
mainWindow.setTitle(fixedTitle);
if (sentinelMode) {
+ // Drive the clock from the main process but require the renderer to
+ // handle each probe before it can journal a heartbeat. Native
+ // Wayland fullscreen surfaces can suspend renderer-owned interval
+ // timers even while renderer IPC remains healthy.
+ if (!sentinelHeartbeatTimer) {
+ sentinelHeartbeatTimer = setInterval(() => {
+ if (mainWindow && !mainWindow.isDestroyed()) {
+ mainWindow.webContents.send('cua-e2e-sentinel-heartbeat-probe');
+ }
+ }, 100);
+ sentinelHeartbeatTimer.unref();
+ }
if (process.platform !== 'darwin' && !nativeWayland) {
mainWindow.setAlwaysOnTop(true);
}
@@ -175,5 +188,9 @@ app.whenReady().then(() => {
});
app.on('window-all-closed', () => {
+ if (sentinelHeartbeatTimer) {
+ clearInterval(sentinelHeartbeatTimer);
+ sentinelHeartbeatTimer = undefined;
+ }
if (process.platform !== 'darwin') app.quit();
});
diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
index 32a3a5f534..526bef5297 100644
--- a/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/electron/preload.js
@@ -57,5 +57,5 @@ if (sentinelMode) {
window.addEventListener('contextmenu', event =>
record('contextmenu', { x: event.clientX, y: event.clientY })
);
- setInterval(() => record('heartbeat'), 100);
+ ipcRenderer.on('cua-e2e-sentinel-heartbeat-probe', () => record('heartbeat'));
}
diff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.md
index 97acb1999e..ca7122a83a 100644
--- a/libs/cua-driver/tests/runners/macos-lume/README.md
+++ b/libs/cua-driver/tests/runners/macos-lume/README.md
@@ -273,8 +273,8 @@ cd ~/cua
libs/cua-driver/tests/runners/macos-lume/run-all.sh --standalone-browser
```
-This adds eight adversarial installed-browser rows and writes their separate
-typed results and MP4 evidence under
+This adds the declared adversarial installed-browser rows and writes their
+separate typed results and MP4 evidence under
`artifacts/cua-driver/macos-standalone-browser/`. Missing external browsers are
a hard failure for this option; they never shrink the reported matrix. On a
repeat run, the entrypoint preserves the previous standalone-browser evidence
diff --git a/libs/cua-driver/wayland-helper/README.md b/libs/cua-driver/wayland-helper/README.md
index 6bbb679cb2..f6437f2056 100644
--- a/libs/cua-driver/wayland-helper/README.md
+++ b/libs/cua-driver/wayland-helper/README.md
@@ -7,6 +7,9 @@ these things globally.
It exposes `org.cua.WinRects` on the session bus:
+- `GetVersion() -> uint` — a browser-sensitive API version. cua-driver only
+ accepts it after resolving the immutable D-Bus owner and proving the owner is
+ the current user's system-installed `gnome-shell` process.
- `GetRects() -> json` — every window's frame geometry and surface-buffer
origin. cua-driver combines the buffer origin with AT-SPI
`CoordType::Window` per-widget coords: `screen = origin + window_xy`. This is
@@ -38,6 +41,13 @@ still work when it is absent, but pixel geometry, the Shell cursor, and safe
foreground portal input are unavailable. cua-driver refuses focus-bound input
instead of injecting into an unverified target.
+Browser setup and consent are held to a stricter boundary: helper API v4 or
+newer must be served by the verified GNOME Shell owner. The driver addresses
+that owner's unique D-Bus name, so another same-session process cannot replace
+the public name between verification and an activation request. One exact
+target is activated only for the bounded operation, then the previously
+focused Shell window is restored and verified.
+
wlroots compositors such as Sway and labwc do not need it: cua-driver uses
foreign-toplevel activation, virtual-pointer input, and layer-shell there.
diff --git a/libs/cua-driver/wayland-helper/winrects@cua/extension.js b/libs/cua-driver/wayland-helper/winrects@cua/extension.js
index 817a44a9ab..87ee3f7066 100644
--- a/libs/cua-driver/wayland-helper/winrects@cua/extension.js
+++ b/libs/cua-driver/wayland-helper/winrects@cua/extension.js
@@ -11,6 +11,7 @@ Gio._promisify(Shell.Screenshot.prototype, 'screenshot_stage_to_content');
Gio._promisify(Shell.Screenshot, 'composite_to_stream');
const IFACE = `<node><interface name="org.cua.WinRects">
+<method name="GetVersion"><arg type="u" direction="out" name="version"/></method>
<method name="GetRects"><arg type="s" direction="out" name="json"/></method>
<method name="Capture"><arg type="s" direction="out" name="png_base64"/></method>
<method name="Activate"><arg type="u" direction="in" name="id"/><arg type="b" direction="out" name="activated"/></method>
@@ -68,6 +69,7 @@ export default class WinRectsExtension extends Extension {
if (this._impl) { this._impl.unexport(); this._impl = null; }
if (this._nameId) { Gio.bus_unown_name(this._nameId); this._nameId = 0; }
}
+ GetVersion() { return 4; }
GetRects() {
const actors = global.get_window_actors();
const actorByWindow = new Map();
diff --git a/libs/cua-driver/wayland-helper/winrects@cua/metadata.json b/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
index 89f708d423..1eb4884ef8 100644
--- a/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
+++ b/libs/cua-driver/wayland-helper/winrects@cua/metadata.json
@@ -1 +1 @@
-{"uuid":"winrects@cua","name":"WinRects","description":"Expose window geometry, capture, cursor, and verified activation for cua-driver on Wayland.","shell-version":["45","46","47","48"],"version":3}
+{"uuid":"winrects@cua","name":"WinRects","description":"Expose window geometry, capture, cursor, and verified activation for cua-driver on Wayland.","shell-version":["45","46","47","48"],"version":4}
diff --git a/scripts/ci/README.md b/scripts/ci/README.md
index 8233c19544..1974f30842 100644
--- a/scripts/ci/README.md
+++ b/scripts/ci/README.md
@@ -21,36 +21,73 @@ scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
The runners require an existing desktop user session and a fresh artifact
directory. They stage the repo-owned Electron foreground sentinel when the
fixture is absent and execute each scenario in an independent Cargo process.
-In a pure native Wayland session, the Unix runner also enables the driver's
-native Wayland backend and launches the sentinel through Wayland, so the result
-cannot silently fall back to X11. To exercise the same matrix in the repo-owned
-native Sway session, run:
+In a Wayland session, the Unix runner also enables the driver's native Wayland
+backend and launches the sentinel and test browsers through Wayland, so GNOME
+and KDE cannot silently fall back to X11 merely because they retain `DISPLAY`
+for XWayland. To exercise the same matrix in the repo-owned native Sway session,
+run:
```bash
CUA_E2E_WAYLAND_RUNNER="$PWD/scripts/ci/run-rust-standalone-browser-e2e.sh" \
scripts/ci/linux/run-rust-e2e-wayland.sh
```
+To prove the fail-closed boundary without a compositor-specific identity
+adapter, run the same browser runner in a native Wayland session with
+`CUA_E2E_WAYLAND_SESSION=generic` on the Sway worker. That environment selects
+only the real-browser generic-Wayland refusal row. The harness retains
+`SWAYSOCK` as an out-of-band focus and z-order oracle, while the spawned Cua
+Driver daemon receives an intentionally unusable socket path and cannot use
+Sway identity.
+Ordinary attachment rows are not applicable because the lane deliberately
+withholds exact compositor identity from the product under test.
+
When a Nix-store Chromium is used on a non-NixOS VM, its SUID sandbox helper
cannot carry the required root ownership. Set `CUA_E2E_BROWSER_NO_SANDBOX=1`
only for that isolated test VM; ordinary installed-browser runs keep Chromium's
sandbox enabled.
+Snap-confined Chromium is not a portable Xvfb certification target. Its launch
+can depend on a real login-session cgroup in addition to X11 authentication,
+so an SSH-created Xvfb session may reject the browser before its CDP endpoint
+starts. Use a distribution-native browser package for X11 certification, or
+run the snap in its real logged-in desktop session. Treat this as a runner
+preflight failure, not a Cua Driver behavioral result.
+
Release validation sets `CUA_TEST_REQUIRE_EXTERNAL_BROWSERS=1` so a missing
browser fails instead of silently omitting the suite.
+By default, Linux preserves the compatibility lane's historical product
+selection: Chrome when installed, otherwise Chromium, plus Edge when present.
+Maintainer certification runs can request an exact product set:
+
+```bash
+CUA_E2E_BROWSER_PRODUCTS=chrome,chromium,edge \
+ scripts/ci/run-rust-standalone-browser-e2e.sh
+```
+
+Every named product is mandatory. An unknown name, duplicate name, or missing
+executable fails before a behavioral row runs, so the matrix cannot silently
+shrink. Use `CUA_E2E_BROWSER_BIN` with `CUA_E2E_BROWSER_NAME` only for a
+single-product diagnostic run. Every launched product also appends its
+CDP-reported product, version, protocol version, user agent, and exact source
+SHA to `browser-provenance.jsonl` beside the matrix report.
+On Linux the runner compiles `cua-driver` with `portal-input`, matching the
+published artifact so representative GNOME/KDE runs exercise the libei
+fallback instead of a default-feature `wtype` refusal.
+
For the test layout and the distinction between unit tests, shared harnesses,
and native harnesses, see
`libs/cua-driver/docs/test-harnesses-guide.md`.
-| Runner | Session | Canonical command |
-| --- | --- | --- |
-| `linux/run-rust-e2e.sh` | Existing Linux X11 or Wayland desktop | no selector |
-| `linux/run-rust-e2e-wayland.sh` | Headless native Sway session | no selector |
-| `linux/run-rust-e2e-inject.sh` | Nested `cua-compositor` session | no selector |
-| `linux/run-rust-e2e-desktop.sh` | Existing representative Linux desktop | no selector |
-| `windows/run-rust-e2e.ps1` | Windows console/RDP user session | `-RequireGui` |
-| `macos/run-rust-e2e.sh` | Logged-in macOS session already prepared by the maintainer wrapper | no selector |
+| Runner | Session | Canonical command |
+| ------------------------------- | ------------------------------------------------------------------ | ----------------- |
+| `linux/run-rust-e2e.sh` | Existing Linux X11 or Wayland desktop | no selector |
+| `linux/run-rust-e2e-wayland.sh` | Headless native Sway session | no selector |
+| `linux/run-rust-e2e-inject.sh` | Nested `cua-compositor` session | no selector |
+| `linux/run-rust-e2e-desktop.sh` | Existing representative Linux desktop | no selector |
+| `windows/run-rust-e2e.ps1` | Windows console/RDP user session | `-RequireGui` |
+| `macos/run-rust-e2e.sh` | Logged-in macOS session already prepared by the maintainer wrapper | no selector |
Use the command without a selector for the canonical complete run. CI sets the
private `CUA_E2E_INTERNAL_LANE` partition to `shared`, `native`, or `capture`
diff --git a/scripts/ci/run-rust-standalone-browser-e2e.sh b/scripts/ci/run-rust-standalone-browser-e2e.sh
index 3289edcd6e..be1cd1914e 100755
--- a/scripts/ci/run-rust-standalone-browser-e2e.sh
+++ b/scripts/ci/run-rust-standalone-browser-e2e.sh
@@ -17,6 +17,7 @@ fi
mkdir -p "${ARTIFACT_DIR}/recordings"
export CUA_E2E_DECLARATIONS_FILE="${ARTIFACT_DIR}/cases.jsonl"
export CUA_E2E_ENVIRONMENT_FILE="${ARTIFACT_DIR}/environment.jsonl"
+export CUA_E2E_BROWSER_PROVENANCE_FILE="${ARTIFACT_DIR}/browser-provenance.jsonl"
export CUA_E2E_RESULTS_FILE="${ARTIFACT_DIR}/results.jsonl"
export CUA_E2E_RECORDINGS_ROOT="${ARTIFACT_DIR}/recordings"
export CUA_TEST_WORKSPACE_ROOT="${RUST_ROOT}"
@@ -27,13 +28,19 @@ export CUA_TEST_DRIVER_STDERR=1
export RUST_BACKTRACE="${RUST_BACKTRACE:-1}"
HOST_OS="$(uname -s)"
+CARGO_DRIVER_FEATURE_ARGS=()
+if [[ "${HOST_OS}" == Linux ]]; then
+ # Published Linux artifacts include the portal/libei route. Compile the
+ # browser matrix with the same feature set so GNOME/KDE setup cannot be
+ # misclassified from a default-feature test binary that falls back to wtype.
+ CARGO_DRIVER_FEATURE_ARGS=(--features portal-input)
+fi
if [[ "${HOST_OS}" == Linux ]] \
&& [[ "${XDG_SESSION_TYPE:-}" == wayland ]] \
- && [[ -n "${WAYLAND_DISPLAY:-}" ]] \
- && [[ -z "${DISPLAY:-}" ]]; then
- # This lane promises native Wayland behavior. Opt into the driver's native
- # backend explicitly so a missing caller variable cannot silently exercise
- # the X11 fallback and time out during native-window correlation.
+ && [[ -n "${WAYLAND_DISPLAY:-}" ]]; then
+ # GNOME/KDE retain DISPLAY for XWayland even in native Wayland sessions.
+ # Session type and the Wayland socket are the authority; opt into the native
+ # backend so those desktops cannot silently exercise X11 enumeration.
export CUA_DRIVER_RS_ENABLE_WAYLAND=1
export ELECTRON_OZONE_PLATFORM_HINT=wayland
fi
@@ -70,6 +77,7 @@ fi
: > "${CUA_E2E_DECLARATIONS_FILE}"
: > "${CUA_E2E_ENVIRONMENT_FILE}"
+: > "${CUA_E2E_BROWSER_PROVENANCE_FILE}"
: > "${CUA_E2E_RESULTS_FILE}"
SOURCE_MARKER="${REPO_ROOT}/.cua-e2e-source-sha"
@@ -81,40 +89,51 @@ if [[ -f "${SOURCE_MARKER}" ]]; then
fi
if [[ "${CUA_E2E_SKIP_BUILD:-0}" != 1 ]]; then
- cargo build --release -p cua-driver --manifest-path "${RUST_ROOT}/Cargo.toml"
+ cargo build --release -p cua-driver \
+ ${CARGO_DRIVER_FEATURE_ARGS[@]+"${CARGO_DRIVER_FEATURE_ARGS[@]}"} \
+ --manifest-path "${RUST_ROOT}/Cargo.toml"
fi
if [[ ! -x "${CUA_TEST_DRIVER_BIN}" ]]; then
echo "Driver binary not found: ${CUA_TEST_DRIVER_BIN}" >&2
exit 1
fi
-tests=(
- standalone_browser_background_type
- standalone_browser_dialogs
-)
-if [[ "${HOST_OS}" == Linux ]]; then
- tests+=(standalone_browser_dialog_background_refusal)
+if [[ "${HOST_OS}" == Linux && "${CUA_E2E_WAYLAND_SESSION:-}" == generic ]]; then
+ if [[ "${XDG_SESSION_TYPE:-}" != wayland || -z "${WAYLAND_DISPLAY:-}" || -z "${SWAYSOCK:-}" ]]; then
+ echo "The generic Wayland lane requires native Wayland and an out-of-band Sway oracle" >&2
+ exit 2
+ fi
+ tests=(standalone_browser_generic_wayland_existing_profile_refusal)
+else
+ tests=(
+ standalone_browser_background_type
+ standalone_browser_dialogs
+ )
+ if [[ "${HOST_OS}" == Linux ]]; then
+ tests+=(standalone_browser_dialog_background_refusal)
+ fi
+ tests+=(
+ standalone_browser_download
+ standalone_browser_existing_profile
+ standalone_browser_existing_profile_setup
+ standalone_browser_frames
+ standalone_browser_multi_tab
+ standalone_browser_pointer_actions
+ standalone_browser_prepare_isolated
+ standalone_browser_roundtrip
+ standalone_browser_semantic_state
+ standalone_browser_stale_ref
+ standalone_browser_trusted_click
+ standalone_browser_upload
+ standalone_browser_window_collision
+ )
fi
-tests+=(
- standalone_browser_download
- standalone_browser_existing_profile
- standalone_browser_existing_profile_setup
- standalone_browser_frames
- standalone_browser_multi_tab
- standalone_browser_pointer_actions
- standalone_browser_prepare_isolated
- standalone_browser_roundtrip
- standalone_browser_semantic_state
- standalone_browser_stale_ref
- standalone_browser_trusted_click
- standalone_browser_upload
- standalone_browser_window_collision
-)
failure_count=0
for test_name in "${tests[@]}"; do
echo "[RUN] ${test_name}"
set +e
(cd "${RUST_ROOT}" && cargo test --release -p cua-driver \
+ ${CARGO_DRIVER_FEATURE_ARGS[@]+"${CARGO_DRIVER_FEATURE_ARGS[@]}"} \
--test standalone_browser_behavior_test "${test_name}" -- \
--ignored --exact --nocapture --test-threads=1) \
2>&1 | tee "${ARTIFACT_DIR}/${test_name}.log"
diff --git a/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1 b/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
index cc3417b43e..e3570488f1 100644
--- a/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
+++ b/scripts/ci/windows/run-rust-standalone-browser-e2e.ps1
@@ -24,6 +24,7 @@ $recordings = Join-Path $artifactDir "recordings"
New-Item -ItemType Directory -Force $recordings | Out-Null
$env:CUA_E2E_DECLARATIONS_FILE = Join-Path $artifactDir "cases.jsonl"
$env:CUA_E2E_ENVIRONMENT_FILE = Join-Path $artifactDir "environment.jsonl"
+$env:CUA_E2E_BROWSER_PROVENANCE_FILE = Join-Path $artifactDir "browser-provenance.jsonl"
$env:CUA_E2E_RESULTS_FILE = Join-Path $artifactDir "results.jsonl"
$env:CUA_E2E_RECORDINGS_ROOT = $recordings
$env:CUA_TEST_WORKSPACE_ROOT = $rustRoot
@@ -36,6 +37,7 @@ $env:CUA_TEST_DRIVER_STDERR = "1"
foreach ($path in @(
$env:CUA_E2E_DECLARATIONS_FILE,
$env:CUA_E2E_ENVIRONMENT_FILE,
+ $env:CUA_E2E_BROWSER_PROVENANCE_FILE,
$env:CUA_E2E_RESULTS_FILE
)) {
New-Item -ItemType File -Path $path | Out-Null