Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): add local consent UI and complete Wayland certification (#2597)

Francesco Bonaccie9852cb68494
diff --git a/docs/content/docs/concepts/how-permission-policies-work.mdx b/docs/content/docs/concepts/how-permission-policies-work.mdx
index ab8d915d29..427bea508a 100644
--- a/docs/content/docs/concepts/how-permission-policies-work.mdx
+++ b/docs/content/docs/concepts/how-permission-policies-work.mdx
@@ -108,9 +108,10 @@ A policy that allows `screenshot` permits an agent to take an unlimited number o
The policy is evaluated in the same process as the tool implementation. An
agent that can replace or inject code into the runtime-owning process can
bypass it. Local shell access alone does not turn ordinary MCP arguments,
-files, TTY input, or environment values into protected consent. Use a trusted
-host to construct direct runtimes, or a trusted launcher and OS isolation for
-workers and services.
+files, TTY input, or environment values into a trusted confirmation channel.
+The built-in native card is only best-effort same-desktop confirmation. Use a
+trusted host to construct direct runtimes, or a trusted launcher and OS
+isolation for workers and services.
For remote agents connecting through an authenticated service, the policy
provides a meaningful boundary: the service runtime will not execute a tool
diff --git a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
index 816b4275df..79cbb83574 100644
--- a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
+++ b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
@@ -155,7 +155,7 @@ runtime. Use separate private workers or services for crash isolation,
different trust domains, different OS identities, or independent desktops.
On macOS, the cursor overlay additionally requires an AppKit main-thread UI
-owner. A direct runtime without a certified host adapter returns structured
+owner. A direct runtime without a suitable host adapter returns structured
`facility_unavailable` results for cursor-overlay operations; it does not
report success or start hidden AppKit work on an unsafe thread. A private
worker or service owns the required event loop. A headless service or worker
diff --git a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
index 93222ae8fa..93a0d76994 100644
--- a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
+++ b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx
@@ -79,10 +79,54 @@ browser, copy the profile, or modify profile files. The route supports Chrome
and Edge on macOS and Windows, plus Chrome in the validated Linux X11 and Sway
configurations. Chromium and Edge have descriptor-backed Linux routes but are
not yet product-validated there. Start a named driver session and choose the
-permission mode before launching the daemon. The standalone daemon has no
-certified protected host provider, so `standard` and `autonomous` refuse
-logged-in profile attachment. For a disposable VM where you accept the risk,
-launch unrestricted mode explicitly:
+permission mode before launching the daemon.
+
+Prefer `bounded` for repeatable browser automation: approve one short-lived
+manifest that names the exact browser window, allowed origins, and typed
+browser tools. This avoids per-action prompts without granting every Cua
+capability. For example:
+
+```yaml
+version: 1
+mode: bounded
+expires_after: 2h
+idle_timeout: 20m
+resources:
+ browser:
+ existing_profiles:
+ - pid: 844
+ window_id: 10725
+ origins:
+ - https://app.example.com
+allow:
+ tools:
+ - start_session
+ - end_session
+ - get_browser_state
+ - browser_prepare
+ - browser_navigate
+ - browser_click
+ - browser_type
+```
+
+Launch Cua Driver with that reviewed scope:
+
+```bash
+cua-driver serve \
+ --permission-mode bounded \
+ --session-policy ./browser-session.yaml \
+ --approve-session-policy
+```
+
+Interactive standalone runtimes show a persistent Stop indicator for the
+bounded attachment, but do not prompt again for actions already admitted by
+the manifest. The built-in indicator is ordinary same-desktop UI: another
+automation runtime or remote-desktop controller with access to that desktop
+can operate it. Use a stronger host-provided collector when hostile local
+automation is in scope.
+
+For a disposable VM where you intentionally accept all Cua actions, launch
+unrestricted mode explicitly instead:
```bash
cua-driver serve \
@@ -102,14 +146,15 @@ browser_prepare({
```
> **Warning:** Unrestricted mode has no runtime Cua approval prompts and makes
-> no prompt-injection safety claim. Prefer `isolated_new`. Use unrestricted
+> no prompt-injection safety claim. Prefer `isolated_new`, or a bounded
+> existing-profile manifest when authentication is required. Use unrestricted
> existing-profile attachment only in an environment whose account and data
> exposure you accept.
-A trusted embedding host can install the protected-consent provider described
+A trusted embedding host can install the confirmation provider described
in [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes).
-In that configuration, `standard` prompts once for the bound browser resource,
-and `autonomous` uses the launch-approved session manifest.
+In `standard`, the provider prompts once for the bound browser resource.
+`bounded` uses the launch-approved session manifest.
The browser may display its own remote-debugging consent prompt. Cua Driver will
press only the exact browser-owned semantic allow action for this approved
diff --git a/docs/content/docs/how-to-guides/driver/update.mdx b/docs/content/docs/how-to-guides/driver/update.mdx
index 9b7c8fe497..1ba097708c 100644
--- a/docs/content/docs/how-to-guides/driver/update.mdx
+++ b/docs/content/docs/how-to-guides/driver/update.mdx
@@ -7,6 +7,31 @@ import { Callout } from 'fumadocs-ui/components/callout';
Cua Driver gives you three update paths: a passive banner at launch time, a CLI command that only checks, and a separate command that installs the update. Keep the **check and apply steps separate** so you can decide when to change the installed binary.
+## Before updating from 0.12.x to 0.13.0
+
+The installer command, CLI/MCP connection flow, tool names, and Python and
+TypeScript SDK constructors remain the same. Two behavior changes require
+attention:
+
+1. `standard` permission mode is actively enforced. Interactive CLI and MCP
+ runtimes show a native confirmation card for exact sensitive actions and a
+ persistent Stop indicator while a grant is live. Headless runtimes fail
+ closed when confirmation is required. The built-in card is best-effort
+ same-desktop UI, not a secure-desktop or biometric boundary.
+2. The old cursor-style fields and `set_agent_cursor_style` operation are
+ removed. Sessions use the built-in animated `cua.default` theme unless an
+ installed theme ID is selected.
+
+For unattended authenticated-browser work, create a short-lived `bounded`
+manifest instead of disabling every approval. Use `unrestricted` only when a
+trusted launcher explicitly supplies `--dangerously-bypass-approvals` and the
+environment can tolerate full Cua autonomy.
+
+See [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes),
+[Drive a web page](/how-to-guides/driver/drive-a-web-page), and
+[Personalize the agent cursor](/how-to-guides/driver/personalize-cursor) before
+restarting a long-running daemon or worker.
+
## Check for updates
```bash
diff --git a/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx b/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
index 7d4b20a264..f4d95fae63 100644
--- a/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
+++ b/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
@@ -13,7 +13,7 @@ The importing application owns OS permissions and permission UX. On macOS,
direct `check_permissions` calls are read-only even when `prompt` is requested;
relaunch the responsible host after changing TCC grants. Direct macOS runtimes
also return `facility_unavailable` for agent-cursor overlay operations unless
-the host installs a certified AppKit main-thread adapter. Use a private worker
+the host installs a suitable AppKit main-thread adapter. Use a private worker
or explicit service when the overlay is required.
## Install the SDK
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 59843958dc..8135269a74 100644
--- a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
+++ b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx
@@ -14,7 +14,7 @@ profiles.
"pid": 844,
"window_id": 10725,
"session": "research-1",
- "strategy": {"kind": "existing_profile"}
+ "strategy": { "kind": "existing_profile" },
}
```
@@ -22,16 +22,25 @@ profiles.
with legacy `allow_launch` or `profile` fields. Authorization depends on the
daemon's immutable [permission mode](/reference/cua-driver/permission-modes):
-- `standard` requests exact protected consent from a certified host provider.
+- `standard` requests exact confirmation from the runtime's provider.
- `bounded` requires the launch-approved manifest to list this PID/window;
the provider activates its persistent Stop indicator without a second prompt.
- `unrestricted` attaches without a runtime approval after the trusted launcher
supplied `--dangerously-bypass-approvals`.
The internal approval marker supplied by an MCP transport does not authorize
-this strategy. The standalone daemon currently has no certified Codex or Claude
-host provider, so `standard` and `bounded` fail closed there. Use an isolated
-profile or an explicitly launched unrestricted daemon.
+this strategy. Interactive standalone daemons use Cua's native confirmation
+card. Headless daemons without a confirmation surface fail closed in
+`standard`, and bounded attachment fails when its required persistent
+indicator cannot be shown.
+
+![Cua Driver confirmation card beside its persistent session indicator](/img/cua-driver-consent-ui.jpg)
+
+The native card is same-desktop, best-effort confirmation. It prevents
+tool-argument forgery and clearly presents the exact operation, but another
+process or remote-desktop controller that can automate the same desktop can
+activate it. It is not a secure-desktop or biometric boundary. Use a stronger
+host-provided collector when local hostile automation is in scope.
The old `browser-approve` file artifact is disabled by default. A trusted
launcher can temporarily enable it with
@@ -43,26 +52,26 @@ and is not protected human consent.
A successful call returns `action: "attached_existing_profile"` and an
`attachment` object with:
-| Field | Value |
-| --- | --- |
-| `kind` | `existing_profile` |
-| `browser` | `chromium` |
-| `capabilities_invalidated` | `true` |
-| `next_action` | `get_browser_state` |
+| Field | Value |
+| -------------------------- | ------------------- |
+| `kind` | `existing_profile` |
+| `browser` | `chromium` |
+| `capabilities_invalidated` | `true` |
+| `next_action` | `get_browser_state` |
`side_effects` reports the bounded setup and consent effects:
-| Field | Meaning |
-| --- | --- |
-| `opened_setup_page` | A temporary tab was opened in the approved native window. |
-| `closed_setup_page` | That temporary setup tab was closed successfully. |
-| `focused_setup_address_field` | The temporary tab's address field received in-app focus for exact navigation. |
-| `enabled_remote_debugging` | The exact per-instance Chrome checkbox was toggled from off to on and the same control's resulting state was verified. |
-| `used_bounded_pixel_fallback` | macOS used its setup-page-only pixel route to read or change the checkbox after the web AX subtree was unavailable. |
-| `foregrounded_window` | Setup temporarily foregrounded the exact approved browser window for a bounded local action. |
-| `injected_global_input` | Setup delivered global mouse or keyboard input only after revalidating the approved browser process and window. |
-| `changed_preferences` | Mirrors `enabled_remote_debugging` for the generic prepare contract. |
-| `displayed_consent_prompt` | Chrome displayed its browser-owned connection-consent prompt. |
+| Field | Meaning |
+| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
+| `opened_setup_page` | A temporary tab was opened in the approved native window. |
+| `closed_setup_page` | That temporary setup tab was closed successfully. |
+| `focused_setup_address_field` | The temporary tab's address field received in-app focus for exact navigation. |
+| `enabled_remote_debugging` | The exact per-instance Chrome checkbox was toggled from off to on and the same control's resulting state was verified. |
+| `used_bounded_pixel_fallback` | macOS used its setup-page-only pixel route to read or change the checkbox after the web AX subtree was unavailable. |
+| `foregrounded_window` | Setup temporarily foregrounded the exact approved browser window for a bounded local action. |
+| `injected_global_input` | Setup delivered global mouse or keyboard input only after revalidating the approved browser process and window. |
+| `changed_preferences` | Mirrors `enabled_remote_debugging` for the generic prepare contract. |
+| `displayed_consent_prompt` | Chrome displayed its browser-owned connection-consent prompt. |
All fields are `false` when the endpoint was already available. The driver does
not return the profile identity, endpoint address, port, connection generation,
@@ -107,15 +116,15 @@ by the previous generation.
## Security properties
-| Property | Guarantee |
-| --- | --- |
-| Network exposure | The accepted DevTools endpoint must be loopback-only. |
-| Process binding | The endpoint, native window, and live process fingerprint must agree before every mutation. |
-| Driver authorization | Standard and bounded setup need a request-bound protected provider; a model-supplied Boolean, ordinary MCP approval, TTY input, and files are insufficient. |
-| Revocation | A protected grant cannot become live until its provider activates persistent Stop UI. `cua-driver revoke` and session end provide additional deny-only paths. |
-| Capability scope | Targets, tabs, dialogs, frames, and refs are opaque, session-scoped, and invalidated after navigation or connection-generation changes. |
-| Profile handling | Cua Driver does not copy, edit, restart, or terminate the selected existing profile. |
-| Residual local risk | CDP itself is not authenticated. Another process running as the same OS user may connect to an exposed endpoint outside Cua Driver. |
+| Property | Guarantee |
+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Network exposure | The accepted DevTools endpoint must be loopback-only. |
+| Process binding | The endpoint, native window, and live process fingerprint must agree before every mutation. |
+| Driver authorization | Standard and bounded setup need a request-bound confirmation provider; a model-supplied Boolean, ordinary MCP approval, TTY input, and files are insufficient. The built-in native card has `same_desktop_best_effort` assurance. |
+| Revocation | A grant cannot become live until its provider activates persistent Stop UI. `cua-driver revoke` and session end provide additional deny-only paths. |
+| Capability scope | Targets, tabs, dialogs, frames, and refs are opaque, session-scoped, and invalidated after navigation or connection-generation changes. |
+| Profile handling | Cua Driver does not copy, edit, restart, or terminate the selected existing profile. |
+| Residual local risk | CDP itself is not authenticated. Another process running as the same OS user may connect to an exposed endpoint outside Cua Driver. Another automation runtime with control of the same desktop may also activate the built-in confirmation card. |
An isolated profile is the recommended default. Existing-profile attachment is
appropriate only when the task requires its authenticated state and the host is
@@ -124,19 +133,19 @@ for why Cua Driver uses CDP and which risks remain outside the driver.
## Refusals
-| Code | Meaning |
-| --- | --- |
-| `browser_consent_required` | No live exact approval exists, or it expired. |
-| `browser_consent_revoked` | The person dismissed or denied the browser prompt. |
-| `browser_requires_setup` | No unique approved browser endpoint is available. |
-| `browser_endpoint_owner_mismatch` | Endpoint ownership or identity changed. |
-| `browser_wrong_target_refused` | The native window, prompt, or browser target is not exact. |
-| `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. |
-| `browser_origin_outside_scope` | A bounded-mode tab left the manifest's allowed origin set; further mutation pauses. |
+| Code | Meaning |
+| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `browser_consent_required` | No live exact approval exists, or it expired. |
+| `browser_consent_revoked` | The person dismissed or denied the browser prompt. |
+| `browser_requires_setup` | No unique approved browser endpoint is available. |
+| `browser_endpoint_owner_mismatch` | Endpoint ownership or identity changed. |
+| `browser_wrong_target_refused` | The native window, prompt, or browser target is not exact. |
+| `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. |
+| `browser_origin_outside_scope` | A bounded-mode tab left the manifest's allowed origin set; further mutation pauses. |
## Recording and telemetry
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 1c49d447e8..2a7a3c32cc 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -759,7 +759,7 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br
### `browser_prepare`
-Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile requires host approval or a short-lived setup token plus allow_launch=true. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the daemon's immutable permission mode: standard requires a certified protected-consent provider, bounded requires a launch-approved exact resource manifest plus protected indicator, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile consent. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
+Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoints are detected without side effects. Acting setup for an isolated profile requires host approval or a short-lived setup token plus allow_launch=true. It launches a separate browser and never copies, modifies, or terminates the requested user profile. Existing-profile attachment is explicit and follows the daemon's immutable permission mode: standard requires a request-bound confirmation provider, bounded requires a launch-approved exact resource manifest plus persistent indicator, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile consent. Interactive standalone daemons use Cua's best-effort same-desktop confirmation card; it is not a secure-desktop or biometric boundary. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused.
**Arguments:**
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
index c1ea6b6f1d..53bf0c760a 100644
--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -1,6 +1,6 @@
---
title: Permission modes and bounded autonomy
-description: Standard, bounded, and unrestricted startup modes, protected consent, session manifests, and revocation in Cua Driver.
+description: Standard, bounded, and unrestricted startup modes, confirmation providers, session manifests, and revocation in Cua Driver.
---
import { Callout } from 'fumadocs-ui/components/callout';
@@ -18,9 +18,9 @@ allowed.
| Mode | Startup | Human intervention | Existing logged-in profile |
| --- | --- | --- | --- |
-| `standard` | Default | Once per exact protected resource or typed action, including user-owned observation/input, file transfer, process termination, persistent configuration, and existing-profile attachment; grants are reused only within their exact scope | Requires a certified protected-consent provider and its persistent Stop indicator |
-| `bounded` | `--permission-mode bounded --session-policy <path> --approve-session-policy` | Once when a trusted launcher reviews and approves the bounded manifest | Allowed only when the manifest names the exact PID/window and a certified indicator provider is available |
-| `unrestricted` | `--dangerously-bypass-approvals` | Once at trusted launch; no runtime Cua approval prompts | May attach without a protected provider after the explicit launch warning |
+| `standard` | Default | Once per exact protected resource or typed action, including user-owned observation/input, file transfer, process termination, persistent configuration, and existing-profile attachment; grants are reused only within their exact scope | Requires an available confirmation provider and its persistent Stop indicator |
+| `bounded` | `--permission-mode bounded --session-policy <path> --approve-session-policy` | Once when a trusted launcher reviews and approves the bounded manifest | Allowed only when the manifest names the exact PID/window and an indicator provider is available |
+| `unrestricted` | `--dangerously-bypass-approvals` | Once at trusted launch; no runtime Cua approval prompts | May attach without a confirmation provider after the explicit launch warning |
`autonomous` remains a compatibility alias for `bounded`; new launchers and
manifests should use `bounded`. `yolo` remains a configuration alias for
@@ -68,7 +68,7 @@ The current inventory is fail-closed:
| `browser_unbounded_script` | `active` | Legacy `page` mutations have no exact browser binding and are denied in `standard` and `bounded`; only trusted launch-time acceptance of `unrestricted` can admit them. |
| `process_control` | `active` | `kill_app` approval binds an OS process fingerprint, which is re-proved immediately before termination to reject PID reuse. |
| `os_permission_prompt` | `active` | Agent tool calls cannot raise protected OS permission UI in any mode. `check_permissions` is read-only by default and explicit `prompt:true` is refused before platform dispatch. On macOS, the human-run `cua-driver permissions grant` setup command launches the installed app through LaunchServices; macOS owns the actual approval UI. |
-| `driver_configuration` | `active` | Persistent `set_config` changes require an exact protected grant in `standard` and an approved bounded scope in `bounded`. |
+| `driver_configuration` | `active` | Persistent `set_config` changes require an exact confirmed grant in `standard` and an approved bounded scope in `bounded`. |
| `clipboard`, `devices`, `shell_and_network` | `not_exposed` | Cua Driver does not expose these open-ended capabilities. |
No exposed sensitive route remains `metadata_only`. Compound calls must satisfy
@@ -76,30 +76,44 @@ every adapter they cross: screenshot-to-file needs both observation and exact
file-output grants, while trajectory replay needs exact file input and desktop
input grants.
-## Protected consent
+## Confirmation providers
-A protected provider must return a decision directly to the daemon over an
-authenticated host or OS channel. The request binds the decision to the daemon
-instance, request nonce, generation, mode, policy hashes, sessions, operation,
-expiry, and exact resource. An accepted request becomes live only after the
-provider activates a persistent indicator with a Stop control.
+A confirmation provider returns a decision directly to the runtime instead of
+accepting a Boolean tool argument. The request binds the decision to the
+runtime instance, request nonce, generation, mode, policy hashes, sessions,
+operation, expiry, and exact resource. An accepted request becomes live only
+after the provider activates a persistent indicator with a Stop control.
Ordinary MCP elicitation, MCP tool arguments, inherited standard input, a TTY,
environment variables, and files do not satisfy this contract. They are
-writable by the calling process. If the runtime has no certified provider,
+writable by the calling process. If the runtime has no provider,
`standard` and `bounded` refuse protected user-owned resources and typed
actions—including observation, input, file transfer/output, process control,
persistent configuration, and existing-profile attachment—before platform
dispatch when the required host is unavailable.
-<Callout type="info">
- The current standalone CLI/MCP daemon has no certified Codex or Claude host
- provider. Its protected-consent status therefore reports `unavailable`.
- Proven driver-owned isolated browser profiles remain prompt-light. A trusted
- embedding host can install the provider interface in process for user-owned
- resources.
+<Callout type="warn" title="Same-desktop confirmation is best effort">
+ Interactive standalone CLI and MCP runtimes use Cua's built-in native
+ confirmation card and persistent Stop indicator. This UI is visible,
+ request-bound, and cannot be forged with a Cua tool argument, but it is an
+ ordinary window on the same desktop. Another local automation runtime,
+ malware process, or remote-desktop controller that can operate that desktop
+ can activate it. It is not a secure-desktop, biometric, or forge-resistant
+ human-consent boundary.
</Callout>
+`get_config.authorization.protected_consent_assurance` reports
+`same_desktop_best_effort` for the built-in native provider, `host_provided`
+for an embedding-host provider, or `unavailable`. Headless runtimes without an
+interactive surface report `unavailable` and fail closed where confirmation or
+an indicator is required. Proven driver-owned isolated browser profiles remain
+prompt-light.
+
+An embedding host can install its own provider. The host determines its actual
+assurance—for example, whether the decision originates in a UI, policy engine,
+second device, or stronger OS-controlled surface. Cua reports such a provider
+as `host_provided`; that label is not a certification.
+
The old file-backed `browser-approve` artifact is disabled by default for
existing profiles. A trusted launcher can temporarily enable it with
`--allow-legacy-existing-profile-approval`, but the artifact is a compatibility
@@ -173,8 +187,8 @@ ask:
```
Tools omitted from all three sets are denied. `ask` also denies unattended
-dispatch because an agent cannot accept its own prompt. A future protected
-host adapter may resume such a call after protected approval.
+dispatch because an agent cannot accept its own prompt. A future trusted-host
+adapter may resume such a call after host approval.
For existing-profile preparation, the requested PID and native window must
match an `existing_profiles` entry. That exact entry also covers observation
diff --git a/docs/content/docs/reference/cua-driver/permission-policies.mdx b/docs/content/docs/reference/cua-driver/permission-policies.mdx
index 6e2c29a407..8dd4392e7a 100644
--- a/docs/content/docs/reference/cua-driver/permission-policies.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-policies.mdx
@@ -279,5 +279,5 @@ Permission denied: tool 'launch_app' is not allowed by the Rego policy
- [Restrict tool access with permission policies](/how-to-guides/driver/restrict-tool-access): step-by-step setup guide
- [How permission policies work](/concepts/how-permission-policies-work): evaluation engine internals and trust model
-- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): startup modes, session manifests, protected consent, and revocation
+- [Permission modes and bounded autonomy](/reference/cua-driver/permission-modes): startup modes, session manifests, confirmation providers, and revocation
- [MCP tools](/reference/cua-driver/mcp-tools): tool names and argument schemas
diff --git a/docs/public/img/cua-driver-consent-ui.jpg b/docs/public/img/cua-driver-consent-ui.jpg
new file mode 100644
index 0000000000..1e9a2d9dde
Binary files /dev/null and b/docs/public/img/cua-driver-consent-ui.jpg differ
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 07119eadeb..3d6d3715a2 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -870,6 +870,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "core_maths"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
+dependencies = [
+ "libm",
+]
+
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -954,6 +963,7 @@ dependencies = [
"futures-util",
"image",
"libc",
+ "overlay-ui",
"pip-preview",
"platform-linux",
"platform-macos",
@@ -1105,6 +1115,12 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
+[[package]]
+name = "data-url"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
+
[[package]]
name = "deranged"
version = "0.5.8"
@@ -1277,6 +1293,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "euclid"
+version = "0.22.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "evdev"
version = "0.12.2"
@@ -1364,6 +1389,12 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "float-cmp"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
+
[[package]]
name = "fluent-uri"
version = "0.4.1"
@@ -1393,6 +1424,28 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "fontconfig-parser"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+dependencies = [
+ "roxmltree",
+]
+
+[[package]]
+name = "fontdb"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3a6f9af55fb97ad673fb7a69533eb2f967648a06fa21f8c9bb2cd6d33975716"
+dependencies = [
+ "fontconfig-parser",
+ "log",
+ "slotmap",
+ "tinyvec",
+ "ttf-parser",
+]
+
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -1884,11 +1937,17 @@ dependencies = [
"byteorder-lite",
"moxcms",
"num-traits",
- "png",
+ "png 0.18.1",
"zune-core",
"zune-jpeg",
]
+[[package]]
+name = "imagesize"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285"
+
[[package]]
name = "indexmap"
version = "2.14.0"
@@ -1986,6 +2045,17 @@ dependencies = [
"regex-syntax",
]
+[[package]]
+name = "kurbo"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "smallvec",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -2020,6 +2090,12 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
[[package]]
name = "libredox"
version = "0.1.17"
@@ -2526,6 +2602,21 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"
+[[package]]
+name = "overlay-ui"
+version = "0.12.6"
+dependencies = [
+ "base64",
+ "cursor-overlay",
+ "image",
+ "resvg",
+ "serde",
+ "serde_json",
+ "thiserror 1.0.69",
+ "tiny-skia 0.11.4",
+ "usvg",
+]
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -2579,6 +2670,12 @@ dependencies = [
"siphasher",
]
+[[package]]
+name = "pico-args"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
+
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -2666,6 +2763,7 @@ dependencies = [
"libc",
"libspa",
"meval",
+ "overlay-ui",
"pip-preview",
"pipewire",
"reis",
@@ -2710,6 +2808,7 @@ dependencies = [
"objc2-app-kit",
"objc2-foundation",
"objc2-quartz-core",
+ "overlay-ui",
"pip-preview",
"screencapturekit",
"serde",
@@ -2734,6 +2833,7 @@ dependencies = [
"cursor-overlay",
"image",
"indexmap",
+ "overlay-ui",
"pip-preview",
"serde",
"serde_json",
@@ -2744,6 +2844,19 @@ dependencies = [
"windows 0.58.0",
]
+[[package]]
+name = "png"
+version = "0.17.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+dependencies = [
+ "bitflags 1.3.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
[[package]]
name = "png"
version = "0.18.1"
@@ -3072,6 +3185,29 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "resvg"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a325d5e8d1cebddd070b13f44cec8071594ab67d1012797c121f27a669b7958"
+dependencies = [
+ "log",
+ "pico-args",
+ "rgb",
+ "svgtypes",
+ "tiny-skia 0.11.4",
+ "usvg",
+]
+
+[[package]]
+name = "rgb"
+version = "0.8.53"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "ring"
version = "0.17.14"
@@ -3086,6 +3222,12 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "roxmltree"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -3161,6 +3303,24 @@ version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+[[package]]
+name = "rustybuzz"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c85d1ccd519e61834798eb52c4e886e8c2d7d698dd3d6ce0b1b47eb8557f1181"
+dependencies = [
+ "bitflags 2.11.1",
+ "bytemuck",
+ "core_maths",
+ "log",
+ "smallvec",
+ "ttf-parser",
+ "unicode-bidi-mirroring",
+ "unicode-ccc",
+ "unicode-properties",
+ "unicode-script",
+]
+
[[package]]
name = "ryu"
version = "1.0.23"
@@ -3432,6 +3592,15 @@ version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
+[[package]]
+name = "simplecss"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"
+dependencies = [
+ "log",
+]
+
[[package]]
name = "siphasher"
version = "1.0.2"
@@ -3444,6 +3613,15 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+[[package]]
+name = "slotmap"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
+dependencies = [
+ "version_check",
+]
+
[[package]]
name = "smallvec"
version = "1.15.1"
@@ -3498,6 +3676,9 @@ name = "strict-num"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
+dependencies = [
+ "float-cmp",
+]
[[package]]
name = "strsim"
@@ -3511,6 +3692,16 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+[[package]]
+name = "svgtypes"
+version = "0.15.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"
+dependencies = [
+ "kurbo",
+ "siphasher",
+]
+
[[package]]
name = "syn"
version = "2.0.117"
@@ -3681,6 +3872,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
+ "png 0.17.16",
"tiny-skia-path 0.11.4",
]
@@ -3695,7 +3887,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
- "png",
+ "png 0.18.1",
"tiny-skia-path 0.12.0",
]
@@ -3731,6 +3923,21 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "tinyvec"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
[[package]]
name = "tokio"
version = "1.52.1"
@@ -3947,6 +4154,15 @@ dependencies = [
"tracing-log",
]
+[[package]]
+name = "ttf-parser"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5be21190ff5d38e8b4a2d3b6a3ae57f612cc39c96e83cedeaf7abc338a8bac4a"
+dependencies = [
+ "core_maths",
+]
+
[[package]]
name = "tungstenite"
version = "0.24.0"
@@ -3989,6 +4205,24 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+
+[[package]]
+name = "unicode-bidi-mirroring"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64af057ad7466495ca113126be61838d8af947f41d93a949980b2389a118082f"
+
+[[package]]
+name = "unicode-ccc"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42"
+
[[package]]
name = "unicode-general-category"
version = "1.1.0"
@@ -4001,12 +4235,30 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+[[package]]
+name = "unicode-properties"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
+
+[[package]]
+name = "unicode-script"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee"
+
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+[[package]]
+name = "unicode-vo"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
+
[[package]]
name = "unicode-width"
version = "0.1.14"
@@ -4197,6 +4449,33 @@ dependencies = [
"serde",
]
+[[package]]
+name = "usvg"
+version = "0.44.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7447e703d7223b067607655e625e0dbca80822880248937da65966194c4864e6"
+dependencies = [
+ "base64",
+ "data-url",
+ "flate2",
+ "fontdb",
+ "imagesize",
+ "kurbo",
+ "log",
+ "pico-args",
+ "roxmltree",
+ "rustybuzz",
+ "simplecss",
+ "siphasher",
+ "strict-num",
+ "svgtypes",
+ "tiny-skia-path 0.11.4",
+ "unicode-bidi",
+ "unicode-script",
+ "unicode-vo",
+ "xmlwriter",
+]
+
[[package]]
name = "utf-8"
version = "0.7.6"
@@ -5017,6 +5296,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
+[[package]]
+name = "xmlwriter"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
+
[[package]]
name = "yansi-term"
version = "0.1.2"
diff --git a/libs/cua-driver/rust/Cargo.toml b/libs/cua-driver/rust/Cargo.toml
index 6cdd7deb9c..44e21cdab4 100644
--- a/libs/cua-driver/rust/Cargo.toml
+++ b/libs/cua-driver/rust/Cargo.toml
@@ -13,6 +13,7 @@ members = [
"crates/platform-linux",
"crates/cursor-overlay",
"crates/cursor-theme-cli",
+ "crates/overlay-ui",
"crates/pip-preview",
]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
index d78fb3d31b..3728f9c2e4 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
@@ -654,6 +654,22 @@ pub struct RiskAssessment {
pub operation_sensitive: bool,
}
+fn advertised_enforcement_for(tool: &str) -> RiskEnforcement {
+ let selector_matches = |selector: &&str| {
+ *selector == tool
+ || selector
+ .strip_prefix(tool)
+ .is_some_and(|suffix| suffix.starts_with('['))
+ };
+ if ENFORCEMENT_ADAPTERS.iter().any(|adapter| {
+ adapter.state == RiskEnforcement::Active && adapter.operations.iter().any(selector_matches)
+ }) {
+ RiskEnforcement::Active
+ } else {
+ RiskEnforcement::MetadataOnly
+ }
+}
+
/// Highest reviewed risk advertised for a tool. Runtime authorization uses
/// [`classify_tool_call`] so compound tools can narrow to a typed operation.
pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
@@ -728,7 +744,10 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
};
RiskAssessment {
class,
- enforcement: RiskEnforcement::MetadataOnly,
+ // Tool discovery cannot see the future arguments of a compound tool.
+ // Advertise the strongest shipped enforcement for any of its typed
+ // operations, then let classify_tool_call narrow the exact request.
+ enforcement: advertised_enforcement_for(tool),
operation_sensitive: matches!(class, RiskClass::R2 | RiskClass::R3 | RiskClass::R4),
}
}
@@ -947,10 +966,11 @@ fn enforce_hard_invariants(
tool: &str,
args: &Value,
) -> Result<(), crate::policy::AuthorizationError> {
- // Provider and indicator adapters hosted by the daemon must never become
- // an ordinary target. Coordinate-only desktop input cannot prove a target
- // PID and therefore is not a protected-UI route; certified providers must
- // render outside that surface and independently reject synthetic input.
+ // Provider and indicator adapters hosted by the runtime must never become
+ // an ordinary process-targeted Cua action. This protects the runtime's own
+ // controls from its PID-bound tools. It does not turn an ordinary
+ // same-desktop window into a secure-desktop boundary: coordinate-only
+ // input from Cua or another automation runtime remains a separate threat.
let process_targeting_tool = matches!(
tool,
"click"
@@ -1134,6 +1154,11 @@ pub fn status_json() -> serde_json::Value {
pub fn status_json_with_provider(
protected_consent_collector: Option<&'static str>,
) -> serde_json::Value {
+ let protected_consent_assurance = match protected_consent_collector {
+ Some("cua_local_desktop_confirmation_v1") => "same_desktop_best_effort",
+ Some(_) => "host_provided",
+ None => "unavailable",
+ };
let mode = configured_permission_mode();
let policy = crate::policy::configured_policy();
let managed_policy = crate::policy::configured_managed_policy();
@@ -1195,6 +1220,7 @@ pub fn status_json_with_provider(
"effective_not_exposed_risk_enforcement": effective_not_exposed_risk_enforcement,
"enforcement_adapters": enforcement_adapter_inventory_json(),
"protected_consent_collector": protected_consent_collector,
+ "protected_consent_assurance": protected_consent_assurance,
"session_policy_configured": std::env::var_os(crate::session_manifest::SESSION_POLICY_FILE_ENV).is_some(),
"session_policy_approved_at_startup": env_flag(crate::session_manifest::SESSION_POLICY_APPROVED_ENV),
"session_policy_valid": session_policy.is_ok(),
@@ -1275,6 +1301,11 @@ mod tests {
#[test]
fn existing_profile_is_the_first_actively_enforced_risk_operation() {
+ assert_eq!(
+ advertised_risk_for("browser_prepare").enforcement,
+ RiskEnforcement::Active,
+ "tools/list must advertise that at least one browser_prepare operation is actively enforced"
+ );
let existing = classify_tool_call(
"browser_prepare",
&serde_json::json!({"strategy": {"kind": "existing_profile"}}),
@@ -1550,6 +1581,17 @@ mod tests {
status["enforcement_adapters"],
enforcement_adapter_inventory_json()
);
+ assert_eq!(status["protected_consent_assurance"], "unavailable");
+ assert_eq!(
+ status_json_with_provider(Some("cua_local_desktop_confirmation_v1"))
+ ["protected_consent_assurance"],
+ "same_desktop_best_effort"
+ );
+ assert_eq!(
+ status_json_with_provider(Some("external_host_consent_v1"))
+ ["protected_consent_assurance"],
+ "host_provided"
+ );
assert_eq!(status["effective_session_mode_source"], "process");
assert_eq!(status["session_mode_delegation_enabled"], false);
assert_eq!(status["session_mode_delegation_ready"], false);
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 00b825c0a8..29e8c7a71a 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
@@ -1432,17 +1432,19 @@ impl BrowserEngine {
.unwrap_or_else(crate::authorization::configured_permission_mode);
if dispatch_mode.is_ok_and(|mode| mode == crate::authorization::PermissionMode::Bounded) {
let live_url = self.live_top_level_url(&conn, &cdp_session).await?;
- let manifest = match dispatch_context.as_deref() {
- Some(context) => context.bounded_manifest(),
- None => {
- crate::session_manifest::configured_session_manifest().map_err(|error| {
- refuse(
- BrowserRefusalCode::BrowserOriginOutsideScope,
- format!("the bounded session policy is unavailable: {error}"),
- )
- })?
- }
- };
+ // A browser mutation admitted for a delegated bounded session
+ // must use that exact session's manifest. Falling back to the
+ // process compatibility manifest would let a missing task-local
+ // context borrow unrelated authority.
+ let manifest = dispatch_context
+ .as_deref()
+ .ok_or_else(|| {
+ refuse(
+ BrowserRefusalCode::BrowserOriginOutsideScope,
+ "the bounded browser authorization context is unavailable",
+ )
+ })?
+ .bounded_manifest();
authorize_live_browser_origin(manifest, &live_url)?;
}
Ok(ValidatedTab {
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 9dd836d0c3..c584bb8668 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
@@ -803,7 +803,7 @@ impl BrowserEngine {
} else {
return Err(refusal(
BrowserRefusalCode::BrowserConsentRequired,
- "existing-profile attachment requires a certified trusted-consent provider in standard/bounded mode; the legacy file-backed artifact is disabled",
+ "existing-profile attachment requires an available request-bound confirmation provider in standard/bounded mode; the legacy file-backed artifact is disabled",
)
.with_detail(serde_json::json!({
"permission_mode": mode.as_str(),
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 5ee552a1fc..935dfc2020 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
@@ -595,10 +595,12 @@ impl BrowserPrepareTool {
token plus allow_launch=true. It launches a separate browser and never \
copies, modifies, or terminates the requested user profile. Existing-profile \
attachment is explicit and follows the daemon's immutable permission mode: \
- standard requires a certified protected-consent provider, bounded requires \
- a launch-approved exact resource manifest plus protected indicator, and \
+ standard requires a request-bound confirmation provider, bounded requires \
+ a launch-approved exact resource manifest plus persistent indicator, and \
unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP \
- transport approval never proves profile consent. On proven platforms, an \
+ transport approval never proves profile consent. Interactive standalone \
+ daemons use Cua's best-effort same-desktop confirmation card; it is not a \
+ secure-desktop or biometric boundary. On proven platforms, an \
authorized request also permits one bounded exact-window setup: \
open the recognized browser product's fixed remote-debugging page, toggle \
its uniquely matched per-instance checkbox, prove the PID-owned loopback \
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
index 1cb96220ac..de797c277f 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/consent.rs
@@ -8,7 +8,7 @@
//! to this interface.
use std::collections::{HashMap, HashSet};
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -22,6 +22,27 @@ use crate::authorization::{PermissionMode, RiskClass};
const DEFAULT_REQUEST_TTL: Duration = Duration::from_secs(2 * 60);
+/// Runtime-wide admission guard held only while protected human input is
+/// being collected. The action that requested consent is already suspended
+/// inside its provider; concurrent tool calls fail closed before they can
+/// inspect the prompt or inject input into it.
+struct ProtectedInteractionGuard {
+ depth: Arc<AtomicUsize>,
+}
+
+impl ProtectedInteractionGuard {
+ fn enter(depth: Arc<AtomicUsize>) -> Self {
+ depth.fetch_add(1, Ordering::AcqRel);
+ Self { depth }
+ }
+}
+
+impl Drop for ProtectedInteractionGuard {
+ fn drop(&mut self) {
+ self.depth.fetch_sub(1, Ordering::AcqRel);
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentAction {
@@ -114,17 +135,17 @@ impl ProtectedGrant {
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ConsentError {
- #[error("no certified protected-consent provider is available")]
+ #[error("no request-bound confirmation provider is available")]
Unavailable,
- #[error("protected consent was declined")]
+ #[error("confirmation was declined")]
Declined,
- #[error("protected consent was canceled")]
+ #[error("confirmation was canceled")]
Canceled,
- #[error("protected consent provider failed: {0}")]
+ #[error("confirmation provider failed: {0}")]
Provider(String),
- #[error("protected consent response did not match the exact request digest")]
+ #[error("confirmation response did not match the exact request digest")]
DigestMismatch,
- #[error("protected consent expired before activation")]
+ #[error("confirmation expired before activation")]
Expired,
#[error("persistent consent indicator could not be activated: {0}")]
Indicator(String),
@@ -137,6 +158,7 @@ pub struct ApprovalBroker {
daemon_instance: Arc<str>,
next_generation: Arc<AtomicU64>,
provider: Option<Arc<dyn ProtectedConsentProvider>>,
+ protected_interaction_depth: Arc<AtomicUsize>,
}
impl ApprovalBroker {
@@ -149,6 +171,7 @@ impl ApprovalBroker {
daemon_instance: Arc::from(Uuid::new_v4().to_string()),
next_generation: Arc::new(AtomicU64::new(1)),
provider,
+ protected_interaction_depth: Arc::new(AtomicUsize::new(0)),
}
}
@@ -158,6 +181,10 @@ impl ApprovalBroker {
.map(|provider| provider.provider_id())
}
+ pub fn protected_interaction_active(&self) -> bool {
+ self.protected_interaction_depth.load(Ordering::Acquire) != 0
+ }
+
#[allow(clippy::too_many_arguments)]
pub fn request(
&self,
@@ -225,10 +252,14 @@ impl ApprovalBroker {
if request.request_digest != digest_request(request) {
return Err(ConsentError::DigestMismatch);
}
- let decision = tokio::time::timeout(remaining(request)?, provider.request_consent(request))
- .await
- .map_err(|_| ConsentError::Provider("request timed out".to_owned()))?
- .map_err(ConsentError::Provider)?;
+ let decision = {
+ let _interaction_guard =
+ ProtectedInteractionGuard::enter(self.protected_interaction_depth.clone());
+ tokio::time::timeout(remaining(request)?, provider.request_consent(request))
+ .await
+ .map_err(|_| ConsentError::Provider("request timed out".to_owned()))?
+ .map_err(ConsentError::Provider)?
+ };
if decision.request_digest != request.request_digest {
return Err(ConsentError::DigestMismatch);
}
@@ -832,6 +863,17 @@ mod tests {
);
}
+ #[test]
+ fn protected_interaction_guard_is_scoped_to_one_broker() {
+ let first = ApprovalBroker::unavailable();
+ let second = ApprovalBroker::unavailable();
+ let guard = ProtectedInteractionGuard::enter(first.protected_interaction_depth.clone());
+ assert!(first.protected_interaction_active());
+ assert!(!second.protected_interaction_active());
+ drop(guard);
+ assert!(!first.protected_interaction_active());
+ }
+
#[tokio::test]
async fn missing_provider_fails_closed() {
let broker = ApprovalBroker::unavailable();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index d397282368..cc276326ba 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -807,6 +807,13 @@ impl ToolRegistry {
// caller-forgeable here.
crate::tool_args::sanitize_reserved_args(&mut args);
+ if self.approval_broker.protected_interaction_active() {
+ return permission_denied_result(
+ "a protected human-consent surface is active; Cua observation and input are temporarily suspended"
+ .to_owned(),
+ );
+ }
+
// Deprecated alias: `type_text_chars` → `type_text`. Swift's
// ToolRegistry.swift keeps the same alias (with stderr warning) for
// backwards compatibility with hermes-agent builds that still emit
@@ -3702,7 +3709,7 @@ mod capability_tests {
fn to_list_entry_includes_versioned_risk_metadata() {
let entry = dummy_def("browser_prepare").to_list_entry();
assert_eq!(entry["risk"]["class"], "r2");
- assert_eq!(entry["risk"]["enforcement"], "metadata_only");
+ assert_eq!(entry["risk"]["enforcement"], "active");
assert_eq!(entry["risk"]["operation_sensitive"], true);
assert_eq!(entry["risk"]["version"], "1");
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
index f80f77df52..a392d066ed 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/abi.rs
@@ -1194,6 +1194,9 @@ impl NativeAbiDriver {
host_bundle_id: Option<String>,
prepare_desktop_environment: bool,
register_host_tools: Option<fn(&mut cua_driver_core::tool::ToolRegistry)>,
+ protected_consent_provider: Option<
+ Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>,
+ >,
) -> Result<Self, DriverError> {
let options: AbiDriverOptions =
serde_json::from_value(options).map_err(|error| DriverError::Configuration {
@@ -1208,6 +1211,7 @@ impl NativeAbiDriver {
runtime_options.host_bundle_id = host_bundle_id;
runtime_options.prepare_desktop_environment = prepare_desktop_environment;
runtime_options.register_host_tools = register_host_tools;
+ runtime_options.protected_consent_provider = protected_consent_provider;
Self::create_for_host(runtime_options)
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
index e3607f8a72..4b2ed3ca84 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
@@ -518,6 +518,11 @@ pub struct DriverHostOptions {
/// Temporary compatibility hook for daemon-only administrative tools.
/// Desktop operations must live behind the typed SDK contract instead.
pub register_host_tools: Option<fn(&mut cua_driver_core::tool::ToolRegistry)>,
+ /// Constructor-only protected consent surface supplied by a trusted Rust
+ /// host. It is never exposed through UniFFI, MCP, CLI arguments, or
+ /// transport metadata.
+ pub protected_consent_provider:
+ Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
}
/// Runtime that imported the shared UniFFI SDK library. The language package
@@ -839,7 +844,7 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: None,
compatibility_authorization: None,
- protected_consent_provider: None,
+ protected_consent_provider: options.protected_consent_provider,
})
}
@@ -946,7 +951,7 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: None,
compatibility_authorization: None,
- protected_consent_provider: None,
+ protected_consent_provider: options.protected_consent_provider,
},
)?)),
client_kind: DaemonClientKind::Unknown,
@@ -995,7 +1000,7 @@ impl CuaDriver {
register_host_tools: options.register_host_tools,
authorization_ceiling: Some(ceiling),
compatibility_authorization: Some((mode, manifest)),
- protected_consent_provider: None,
+ protected_consent_provider: options.protected_consent_provider,
},
)?)),
client_kind: DaemonClientKind::Unknown,
@@ -1036,6 +1041,7 @@ impl CuaDriver {
host.host_bundle_id,
host.prepare_desktop_environment,
host.register_host_tools,
+ host.protected_consent_provider,
)?,
)),
client_kind: DaemonClientKind::Unknown,
@@ -1633,6 +1639,7 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: None,
+ protected_consent_provider: None,
});
assert!(inventory["tools"]
.as_array()
@@ -1686,6 +1693,7 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(register_slow_host_tool),
+ protected_consent_provider: None,
})
.unwrap();
let action_driver = driver.clone();
diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
index dd920f6d54..5960943065 100644
--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/observer.rs
@@ -1209,8 +1209,7 @@ pub mod linux {
struct GnomeWindow {
id: u64,
pid: u32,
- #[serde(rename = "title")]
- _title: String,
+ title: String,
x: i64,
y: i64,
w: i64,
@@ -1297,14 +1296,19 @@ pub mod linux {
}
fn fully_covers(cover: &GnomeWindow, target: &GnomeWindow) -> bool {
- target.w > 0
- && target.h > 0
- && cover.w > 0
- && cover.h > 0
- && cover.x <= target.x
+ let valid_rects = target.w > 0 && target.h > 0 && cover.w > 0 && cover.h > 0;
+ let covers_declared_frame = cover.x <= target.x
&& cover.y <= target.y
&& cover.x.saturating_add(cover.w) >= target.x.saturating_add(target.w)
- && cover.y.saturating_add(cover.h) >= target.y.saturating_add(target.h)
+ && cover.y.saturating_add(cover.h) >= target.y.saturating_add(target.h);
+ let test_sentinel_covers_visible_frame = cover.title.starts_with("CuaTestHarness Sentinel")
+ && cover.x == 0
+ && cover.y == 0
+ && target.x < cover.w
+ && target.y < cover.h
+ && target.x.saturating_add(target.w) > 0
+ && target.y.saturating_add(target.h) > 0;
+ valid_rects && (covers_declared_frame || test_sentinel_covers_visible_frame)
}
fn classify_gnome_target(windows: &[GnomeWindow], target: TargetWindow) -> TargetZ {
@@ -1840,6 +1844,28 @@ pub mod linux {
);
}
+ #[test]
+ fn gnome_fullscreen_test_sentinel_covers_the_visible_part_of_an_oversized_target() {
+ let mut windows = parse_gnome_windows(gnome_payload()).expect("GNOME JSON");
+ let target = TargetWindow {
+ pid: 100,
+ native_id: 10,
+ };
+ windows[0].x = 66;
+ windows[0].w = 1020;
+ windows[1].title = "CuaTestHarness Sentinel [cdp=12345]".to_owned();
+ assert_eq!(
+ classify_gnome_target(&windows, target),
+ TargetZ::BackgroundOccluded
+ );
+
+ windows[1].title = "ordinary window".to_owned();
+ assert_eq!(
+ classify_gnome_target(&windows, target),
+ TargetZ::BackgroundVisible
+ );
+ }
+
#[test]
fn gnome_focused_and_minimized_are_direct() {
let mut windows = parse_gnome_windows(gnome_payload()).expect("GNOME JSON");
diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
index 3fa4c61fe6..17411d3d25 100644
--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml
@@ -19,6 +19,7 @@ tracing-subscriber = { workspace = true }
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-sdk = { path = "../cua-driver-sdk" }
cursor-overlay = { path = "../cursor-overlay" }
+overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
async-trait = "0.1"
base64 = { workspace = true }
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index bcc2045dd8..2221a1b120 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -24,6 +24,7 @@ mod cli;
mod doctor;
mod mcp_http;
mod private_worker;
+mod protected_consent;
mod proxy;
mod responsibility;
mod sdk_adapter;
@@ -291,6 +292,7 @@ fn build_driver(
claude_code_compatibility: compatibility_mode,
prepare_desktop_environment: true,
register_host_tools: Some(check_update_tool::register_into),
+ protected_consent_provider: protected_consent::native_provider(),
})
}
@@ -323,6 +325,7 @@ fn inspect_tools_without_runtime() -> serde_json::Value {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(check_update_tool::register_into),
+ protected_consent_provider: None,
})
}
@@ -338,7 +341,7 @@ fn run_mcp_direct(compatibility_mode: bool) -> anyhow::Result<()> {
cua_driver_core::authorization::validate_startup_authorization()?;
cua_driver_core::policy::validate_configured_policy()?;
let cursor = cursor_overlay::CursorConfig::from_args();
- // A plain stdio MCP process does not provide the certified AppKit
+ // A plain stdio MCP process does not provide the required AppKit
// main-thread host adapter. Explicit direct mode on macOS must therefore
// expose facility_unavailable instead of initializing an overlay that can
// report success without a usable UI owner. Private-worker and app-service
@@ -426,6 +429,9 @@ mod mcp_runtime_selection_tests {
#[cfg(target_os = "macos")]
fn main() {
+ if let Some(code) = protected_consent::run_helper_if_requested() {
+ std::process::exit(code);
+ }
init_logging();
if let Some(code) = cli::run_permissions_host_request_if_requested() {
std::process::exit(code);
@@ -808,6 +814,9 @@ fn main() {
#[cfg(not(target_os = "macos"))]
fn main() -> anyhow::Result<()> {
+ if let Some(code) = protected_consent::run_helper_if_requested() {
+ std::process::exit(code);
+ }
init_logging();
if let Some(generation) = private_worker::requested_generation() {
return private_worker::run(generation, None);
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
index d26c746f82..79a6b194bc 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/private_worker.rs
@@ -124,6 +124,7 @@ async fn run_async(
claude_code_compatibility: false,
prepare_desktop_environment: true,
register_host_tools: Some(crate::check_update_tool::register_into),
+ protected_consent_provider: crate::protected_consent::native_provider(),
},
) {
Ok(driver) => driver,
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs b/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs
new file mode 100644
index 0000000000..88750653ab
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver/src/protected_consent.rs
@@ -0,0 +1,271 @@
+//! Built-in local-desktop confirmation host for standalone Cua Driver runtimes.
+//!
+//! The surface runs in a separate instance of the signed driver executable.
+//! Its request and result travel only through inherited anonymous pipes.
+//! This improves visibility and prevents tool-argument forgery, but it is not a
+//! secure-desktop boundary: another process that can automate the same desktop
+//! can still activate the prompt.
+
+use std::collections::HashMap;
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Child, Command, Stdio};
+use std::sync::{atomic::AtomicBool, Arc, Mutex};
+
+use async_trait::async_trait;
+use cua_driver_core::consent::{
+ ConsentAction, ConsentRequest, IndicatorLease, ProtectedConsentProvider, ProviderDecision,
+};
+use overlay_ui::{ConsentCard, HelperDecision, HelperEvent, HelperRequest, IndicatorCard};
+
+const HELPER_ENV: &str = "CUA_INTERNAL_PROTECTED_CONSENT_HELPER";
+
+pub(crate) fn native_provider() -> Option<Arc<dyn ProtectedConsentProvider>> {
+ if !interactive_surface_available() {
+ return None;
+ }
+ Some(Arc::new(NativeProtectedConsentProvider::default()))
+}
+
+fn interactive_surface_available() -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ platform_macos::session::has_graphic_access()
+ }
+ #[cfg(target_os = "windows")]
+ {
+ platform_windows::protected_consent::interactive_surface_available()
+ }
+ #[cfg(target_os = "linux")]
+ {
+ platform_linux::protected_consent::interactive_surface_available()
+ }
+}
+
+/// Run before telemetry, CLI parsing, or platform runtime initialization.
+pub(crate) fn run_helper_if_requested() -> Option<i32> {
+ if std::env::var_os(HELPER_ENV).is_none() {
+ return None;
+ }
+ Some(match run_helper() {
+ Ok(()) => 0,
+ Err(error) => {
+ let _ = write_event(&HelperEvent::Failed {
+ reason: error.to_string(),
+ });
+ 1
+ }
+ })
+}
+
+fn run_helper() -> anyhow::Result<()> {
+ let request: HelperRequest = serde_json::from_reader(std::io::stdin().lock())?;
+ #[cfg(target_os = "macos")]
+ {
+ platform_macos::protected_consent::run(request)
+ }
+ #[cfg(target_os = "windows")]
+ {
+ platform_windows::protected_consent::run(request)
+ }
+ #[cfg(target_os = "linux")]
+ {
+ platform_linux::protected_consent::run(request)
+ }
+}
+
+pub(crate) fn write_event(event: &HelperEvent) -> anyhow::Result<()> {
+ let mut stdout = std::io::stdout().lock();
+ serde_json::to_writer(&mut stdout, event)?;
+ stdout.write_all(b"\n")?;
+ stdout.flush()?;
+ Ok(())
+}
+
+#[derive(Default)]
+struct NativeProtectedConsentProvider {
+ indicators: Mutex<HashMap<String, IndicatorProcess>>,
+}
+
+struct IndicatorProcess {
+ child: Arc<Mutex<Child>>,
+ revoked: Arc<AtomicBool>,
+}
+
+#[async_trait]
+impl ProtectedConsentProvider for NativeProtectedConsentProvider {
+ fn provider_id(&self) -> &'static str {
+ "cua_local_desktop_confirmation_v1"
+ }
+
+ async fn request_consent(&self, request: &ConsentRequest) -> Result<ProviderDecision, String> {
+ let expires_unix_ms = u64::try_from(request.expires_unix_ms)
+ .map_err(|_| "protected consent expiry exceeds the helper wire range".to_owned())?;
+ let card = ConsentCard {
+ operation: request.operation.clone(),
+ risk_label: format!("{:?}", request.risk_class),
+ summary: request.human_summary.clone(),
+ request_digest: request.request_digest.clone(),
+ expires_unix_ms,
+ };
+ let expected_digest = request.request_digest.clone();
+ tokio::task::spawn_blocking(move || {
+ let event = run_one_shot(HelperRequest::Consent(card))?;
+ let HelperEvent::Decision {
+ action,
+ request_digest,
+ } = event
+ else {
+ return Err("protected helper did not return a decision".to_owned());
+ };
+ if request_digest != expected_digest {
+ return Err("protected helper returned a mismatched request digest".to_owned());
+ }
+ Ok(ProviderDecision {
+ action: match action {
+ HelperDecision::Accept => ConsentAction::Accept,
+ HelperDecision::Decline => ConsentAction::Decline,
+ HelperDecision::Cancel => ConsentAction::Cancel,
+ },
+ request_digest,
+ })
+ })
+ .await
+ .map_err(|error| format!("protected helper task failed: {error}"))?
+ }
+
+ async fn activate_indicator(&self, request: &ConsentRequest) -> Result<IndicatorLease, String> {
+ let id = format!("indicator-{}", request.nonce);
+ let summary = request.human_summary.clone();
+ let indicator_id = id.clone();
+ let (process, reader) = tokio::task::spawn_blocking(move || {
+ spawn_indicator(HelperRequest::Indicator(IndicatorCard {
+ indicator_id,
+ summary,
+ }))
+ })
+ .await
+ .map_err(|error| format!("indicator helper task failed: {error}"))??;
+
+ let revoked = process.revoked.clone();
+ let child = process.child.clone();
+ let watch_id = id.clone();
+ std::thread::Builder::new()
+ .name("cua-protected-indicator".to_owned())
+ .spawn(move || watch_indicator(reader, child, revoked, &watch_id))
+ .map_err(|error| format!("could not monitor protected indicator: {error}"))?;
+ let lease = IndicatorLease::new(id.clone(), process.revoked.clone());
+ self.indicators.lock().unwrap().insert(id, process);
+ Ok(lease)
+ }
+
+ async fn deactivate_indicator(&self, indicator_id: &str) {
+ let process = self.indicators.lock().unwrap().remove(indicator_id);
+ if let Some(process) = process {
+ process
+ .revoked
+ .store(true, std::sync::atomic::Ordering::Release);
+ if let Ok(mut child) = process.child.lock() {
+ let _ = child.kill();
+ let _ = child.wait();
+ }
+ }
+ }
+}
+
+fn spawn_child(request: &HelperRequest) -> Result<Child, String> {
+ let executable =
+ std::env::current_exe().map_err(|error| format!("resolve helper executable: {error}"))?;
+ let mut child = Command::new(executable)
+ .env(HELPER_ENV, "1")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::inherit())
+ .spawn()
+ .map_err(|error| format!("spawn protected helper: {error}"))?;
+ let mut stdin = child
+ .stdin
+ .take()
+ .ok_or_else(|| "protected helper stdin was unavailable".to_owned())?;
+ serde_json::to_writer(&mut stdin, request)
+ .map_err(|error| format!("serialize protected helper request: {error}"))?;
+ stdin
+ .flush()
+ .map_err(|error| format!("flush protected helper request: {error}"))?;
+ drop(stdin);
+ Ok(child)
+}
+
+fn run_one_shot(request: HelperRequest) -> Result<HelperEvent, String> {
+ let mut child = spawn_child(&request)?;
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| "protected helper stdout was unavailable".to_owned())?;
+ let mut reader = BufReader::new(stdout);
+ expect_ready(&mut reader)?;
+ let event = read_event(&mut reader)?;
+ let status = child
+ .wait()
+ .map_err(|error| format!("wait for protected helper: {error}"))?;
+ if !status.success() {
+ return Err(format!("protected helper exited with {status}"));
+ }
+ Ok(event)
+}
+
+fn spawn_indicator(
+ request: HelperRequest,
+) -> Result<(IndicatorProcess, BufReader<std::process::ChildStdout>), String> {
+ let mut child = spawn_child(&request)?;
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| "indicator helper stdout was unavailable".to_owned())?;
+ let mut reader = BufReader::new(stdout);
+ expect_ready(&mut reader)?;
+ Ok((
+ IndicatorProcess {
+ child: Arc::new(Mutex::new(child)),
+ revoked: Arc::new(AtomicBool::new(false)),
+ },
+ reader,
+ ))
+}
+
+fn watch_indicator(
+ mut reader: BufReader<std::process::ChildStdout>,
+ child: Arc<Mutex<Child>>,
+ revoked: Arc<AtomicBool>,
+ expected_id: &str,
+) {
+ let stopped = matches!(
+ read_event(&mut reader),
+ Ok(HelperEvent::Stop { indicator_id }) if indicator_id == expected_id
+ );
+ revoked.store(true, std::sync::atomic::Ordering::Release);
+ if !stopped {
+ tracing::warn!("protected indicator helper exited without an authenticated Stop event");
+ }
+ if let Ok(mut child) = child.lock() {
+ let _ = child.wait();
+ }
+}
+
+fn expect_ready(reader: &mut impl BufRead) -> Result<(), String> {
+ match read_event(reader)? {
+ HelperEvent::Ready => Ok(()),
+ HelperEvent::Failed { reason } => Err(reason),
+ _ => Err("protected helper did not become ready".to_owned()),
+ }
+}
+
+fn read_event(reader: &mut impl BufRead) -> Result<HelperEvent, String> {
+ let mut line = String::new();
+ let count = reader
+ .read_line(&mut line)
+ .map_err(|error| format!("read protected helper event: {error}"))?;
+ if count == 0 {
+ return Err("protected helper closed its private channel".to_owned());
+ }
+ serde_json::from_str(&line).map_err(|error| format!("invalid protected helper event: {error}"))
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
index 2b345bdc68..931eb885ec 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
@@ -343,6 +343,7 @@ mod tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: None,
+ protected_consent_provider: None,
})
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index b880b8d021..f61a208e39 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -447,7 +447,9 @@ fn authenticate_embedded_host_connection(stream: &tokio::net::UnixStream) -> any
}
fn service_authorization_status(trusted_host_connection: bool) -> serde_json::Value {
- let mut status = cua_driver_core::authorization::status_json();
+ let provider_id =
+ crate::protected_consent::native_provider().map(|provider| provider.provider_id());
+ let mut status = cua_driver_core::authorization::status_json_with_provider(provider_id);
if trusted_host_connection {
let object = status
.as_object_mut()
@@ -1666,8 +1668,11 @@ pub fn run_status_cmd(socket_path: &str, pid_file_path: &str) {
println!(" managed policy sha256: {hash}");
}
println!(
- " protected consent collector: {}",
+ " confirmation collector: {} ({})",
status["protected_consent_collector"]
+ .as_str()
+ .unwrap_or("unavailable"),
+ status["protected_consent_assurance"]
.as_str()
.unwrap_or("unavailable")
);
@@ -1858,6 +1863,7 @@ mod gate_tests {
claude_code_compatibility: false,
prepare_desktop_environment: false,
register_host_tools: Some(register_probe),
+ protected_consent_provider: None,
});
let direct_driver = driver.clone();
let sdk = crate::sdk_adapter::SdkAdapter::load(driver)
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 9db18a1861..d213e571b6 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
@@ -765,7 +765,11 @@ fn configure_test_browser_sandbox(command: &mut Command) {
const TEST_BROWSER_WINDOW_SIZE: &str = "900,640";
#[cfg(target_os = "windows")]
const TEST_BROWSER_HIGH_DPI_WINDOW_SIZE: &str = "440,300";
-#[cfg(not(target_os = "windows"))]
+#[cfg(target_os = "linux")]
+const TEST_BROWSER_WINDOW_SIZE: &str = "980,760";
+#[cfg(target_os = "linux")]
+const TEST_BROWSER_HIGH_DPI_WINDOW_SIZE: &str = "420,280";
+#[cfg(target_os = "macos")]
const TEST_BROWSER_WINDOW_SIZE: &str = "980,760";
#[cfg(target_os = "windows")]
@@ -783,29 +787,37 @@ fn command_for_browser(
) -> Command {
let mut command = Command::new(&spec.executable);
let output = browser_stderr();
- #[cfg(target_os = "windows")]
+ #[cfg(any(target_os = "windows", target_os = "linux"))]
let window_size = if _force_high_device_scale {
// Chromium applies the forced scale to the native window as well as
- // the page and enforces a scaled minimum outer width. Keep the
- // resulting physical bounds inside the 1024x768 interactive runner so
- // the full-desktop sentinel can occlude every sampled point during the
- // strict background-action proof.
+ // the page and enforces a scaled minimum outer size. Keep the resulting
+ // physical bounds inside the interactive runner so the full-desktop
+ // sentinel can occlude every sampled point during the strict
+ // background-action proof.
TEST_BROWSER_HIGH_DPI_WINDOW_SIZE
} else {
TEST_BROWSER_WINDOW_SIZE
};
#[cfg(target_os = "windows")]
let window_position = if _force_high_device_scale {
- // A scaled (40,40) origin plus Chromium's minimum high-DPI outer width
- // can extend past the runner even when --window-size is smaller.
+ // A scaled inset origin plus Chromium's minimum high-DPI outer width
+ // can extend past a small runner even when --window-size is smaller.
// Anchor this test-owned window at the display origin instead.
(0, 0)
} else {
position
};
- #[cfg(not(target_os = "windows"))]
+ #[cfg(target_os = "linux")]
+ // GNOME may horizontally maximize Chromium after applying server-side
+ // frame extents. Anchor this disposable fixture at the display origin so
+ // the full-screen sentinel covers the complete compositor-declared frame.
+ let window_position = {
+ let _ = position;
+ (0, 0)
+ };
+ #[cfg(target_os = "macos")]
let window_position = position;
- #[cfg(not(target_os = "windows"))]
+ #[cfg(target_os = "macos")]
let window_size = TEST_BROWSER_WINDOW_SIZE;
command
.arg(format!("--remote-debugging-port={cdp_port}"))
diff --git a/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml b/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml
new file mode 100644
index 0000000000..19f692d37b
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "overlay-ui"
+version.workspace = true
+edition.workspace = true
+
+[dependencies]
+base64 = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+resvg = { version = "0.44", default-features = false }
+tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
+usvg = { version = "0.44", default-features = false, features = ["text", "system-fonts"] }
+
+[dev-dependencies]
+image = { workspace = true }
+cursor-overlay = { path = "../cursor-overlay" }
diff --git a/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs b/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs
new file mode 100644
index 0000000000..8d407bda4a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/examples/preview.rs
@@ -0,0 +1,101 @@
+use cursor_overlay::{theme::paint_default_theme, CursorVisualState};
+use overlay_ui::{
+ render_consent, render_indicator, ConsentCard, ConsentVisualState, IndicatorCard,
+};
+use tiny_skia::{Color, Paint, Pixmap, PixmapPaint, Rect, Transform};
+
+fn main() {
+ let output = std::env::args()
+ .nth(1)
+ .expect("usage: cargo run -p overlay-ui --example preview -- <output.png>");
+ let mut canvas = Pixmap::new(1200, 720).expect("canvas");
+ canvas.fill(Color::from_rgba8(231, 231, 227, 255));
+
+ // A quiet Codex-like application backdrop to show the real overlay scale.
+ rounded_panel(&mut canvas, 78.0, 80.0, 1044.0, 560.0, [250, 250, 248, 255]);
+ rounded_panel(&mut canvas, 79.0, 81.0, 238.0, 558.0, [242, 242, 239, 255]);
+ rounded_panel(&mut canvas, 107.0, 116.0, 178.0, 32.0, [229, 229, 225, 255]);
+ rounded_panel(&mut canvas, 107.0, 171.0, 178.0, 18.0, [235, 235, 232, 255]);
+ rounded_panel(&mut canvas, 107.0, 205.0, 142.0, 18.0, [235, 235, 232, 255]);
+ rounded_panel(&mut canvas, 355.0, 116.0, 716.0, 46.0, [246, 246, 243, 255]);
+ rounded_panel(&mut canvas, 355.0, 190.0, 590.0, 14.0, [231, 231, 227, 255]);
+ rounded_panel(&mut canvas, 355.0, 218.0, 654.0, 14.0, [238, 238, 234, 255]);
+ rounded_panel(&mut canvas, 355.0, 246.0, 520.0, 14.0, [238, 238, 234, 255]);
+
+ let consent = render_consent(
+ &ConsentCard {
+ operation: "browser.existing_profile.attach".to_owned(),
+ risk_label: "authenticated session".to_owned(),
+ summary:
+ "Cua can access signed-in sites in the “Work” profile until you stop the session."
+ .to_owned(),
+ request_digest: "preview".to_owned(),
+ expires_unix_ms: 0,
+ },
+ 1.0,
+ ConsentVisualState {
+ accept_armed: true,
+ accept_hovered: false,
+ decline_hovered: false,
+ },
+ )
+ .expect("consent render");
+ canvas.draw_pixmap(
+ 518,
+ 288,
+ consent.as_ref(),
+ &PixmapPaint::default(),
+ Transform::identity(),
+ None,
+ );
+
+ let indicator = render_indicator(
+ &IndicatorCard {
+ indicator_id: "preview".to_owned(),
+ summary: "Chrome - Work".to_owned(),
+ },
+ 1.0,
+ false,
+ )
+ .expect("indicator render");
+ canvas.draw_pixmap(
+ 706,
+ 100,
+ indicator.as_ref(),
+ &PixmapPaint::default(),
+ Transform::identity(),
+ None,
+ );
+
+ draw_cursor(&mut canvas, 491.0, 270.0);
+
+ image::save_buffer(
+ output,
+ canvas.data(),
+ canvas.width(),
+ canvas.height(),
+ image::ColorType::Rgba8,
+ )
+ .expect("write preview");
+}
+
+fn rounded_panel(pixmap: &mut Pixmap, x: f32, y: f32, width: f32, height: f32, rgba: [u8; 4]) {
+ let Some(rect) = Rect::from_xywh(x, y, width, height) else {
+ return;
+ };
+ let mut paint = Paint::default();
+ paint.set_color_rgba8(rgba[0], rgba[1], rgba[2], rgba[3]);
+ pixmap.fill_rect(rect, &paint, Transform::identity(), None);
+}
+
+fn draw_cursor(pixmap: &mut Pixmap, x: f32, y: f32) {
+ paint_default_theme(
+ pixmap,
+ &CursorVisualState::default(),
+ x,
+ y,
+ std::f32::consts::FRAC_PI_4,
+ 1.0,
+ 1.0,
+ );
+}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg b/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg
new file mode 100644
index 0000000000..fcfebb8052
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/cua-driver-mark.svg
@@ -0,0 +1,10 @@
+<svg width="1500" height="1500" viewBox="0 0 1500 1500" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M766.859 217.167C766.912 229.775 758.896 237.053 748.476 237.348C738.056 237.644 728.992 230.057 728.952 217.744L728.509 70.3073C728.469 58.6252 736.149 50.5148 747.08 50.3537C756.909 50.206 766.107 57.8195 766.16 69.3674L766.845 217.167H766.859Z" fill="white"/>
+<path d="M855.267 263.171C848.849 271.657 837.838 271.322 830.667 267.172C822.92 262.688 818.972 250.374 824.612 241.821C836.213 224.19 850.205 208.547 864.143 192.461L885.855 167.418C891.656 160.717 902.586 161.402 908.548 166.196C914.712 171.151 917.008 181.638 911.502 188.902L855.281 263.171H855.267Z" fill="white"/>
+<path d="M674.61 238.946C681.297 248.023 679.645 259.316 671.911 265.788C664.754 271.764 652.159 271.952 645.458 263.116L589.464 189.264C583.637 181.583 586.349 170.68 592.539 165.993C600.932 159.642 611.016 162.448 617.408 170.049C636.703 192.983 656.482 214.374 674.61 238.96V238.946Z" fill="white"/>
+<path d="M764.952 1353.4L737.13 1353.26C733.262 1353.25 730.295 1355.97 728.939 1359.72C721.943 1379 713.336 1397.92 697.451 1411.78C667.144 1438.19 624.081 1447.58 585.624 1437.22C556.352 1429.34 534.008 1408.52 524.192 1379.86C514.377 1351.21 519.117 1322.55 524.192 1292.86C518.378 1290.67 509.314 1292.1 502.775 1291.33C495.121 1290.45 487.548 1288.92 480.149 1286.77C458.289 1280.44 437.986 1268.41 420.799 1253.6C381.496 1219.76 388.223 1168.11 407.116 1125.1C413.628 1110.27 422.759 1096.28 430.601 1081.47C392.144 1061.93 356.05 1040.72 324.804 1011.15C272.959 962.084 238.396 897.698 220.47 828.733C218.577 821.455 221.356 813.6 226.016 809.088C230.93 804.322 238.692 802.254 246.117 804.657C314.236 826.733 421.054 874.012 482.177 911.26C485.024 912.992 489.28 914.429 492.234 912.764C521.01 896.503 555.425 904.291 575.943 931.053C579.81 925.144 582.993 918.659 585.423 911.958C507.408 894.516 431.393 876.751 369.746 824.477C352.116 809.532 336.701 793.378 326.697 772.646C323.636 766.308 320.01 761.796 313.256 759.137C292.577 751 275.846 735.384 267.709 714.436C256.121 684.627 278.599 671.723 256.295 646.519C244.157 632.796 231.011 619.448 222.927 602.556C214.575 585.073 218.308 564.113 226.728 547.409C232.381 536.17 234.354 524.783 231.118 512.456C220.792 473.113 203.269 433.461 203.914 395.326C204.706 348.611 232.152 299.103 285.514 301.063C310.879 301.99 335.519 308.811 357.285 321.809C375.332 332.578 388.787 347.322 402.738 362.629C411.802 372.579 420.074 381.844 425.633 395.071C457.161 366.658 491.912 346.248 530.221 329.758C612.587 294.282 697.249 287.125 786.557 290.549C889.763 294.51 995.036 324.36 1074.5 394.507C1080.37 382.073 1088.1 372.418 1097.07 362.374C1112.25 345.375 1127.18 329.02 1147.45 317.821C1169.22 305.803 1193.86 299.17 1218.73 298.995C1246.26 298.794 1268.33 313.35 1281.81 336.875C1313.23 391.727 1287.79 448.889 1271.19 505.836C1266.59 521.627 1267.4 535.431 1275.03 549.893C1283.13 565.241 1285.49 585.691 1277.38 601.415C1268.73 618.173 1255.94 631.399 1243.83 645.216C1222.37 669.735 1243.99 680.76 1233.78 710.099C1226.29 731.61 1209.68 748.14 1188.81 756.734C1182.11 759.486 1178.28 763.864 1175.28 770.269C1165.18 791.834 1149.6 808.78 1131.44 824.141C1068.97 876.952 994.419 894.207 915.302 911.891C917.867 918.471 920.781 924.648 924.447 931.281C943.608 906.507 975.042 897.295 1002.82 909.958C1005.51 911.18 1011.69 914.966 1014.28 913.422C1051.54 891.186 1088.75 872.535 1128.48 854.837C1170.07 836.32 1210.77 818.864 1253.98 804.832C1261.54 802.375 1269.51 803.919 1274.6 808.713C1279.41 813.238 1282.01 821.899 1280.08 829.297C1261.99 898.611 1227.12 963.105 1174.74 1012.17C1143.78 1041.17 1108.34 1062.09 1070.3 1081.28C1078.06 1096.85 1087.31 1110.72 1093.88 1125.71C1112.3 1167.81 1118.88 1218.93 1080.97 1252.55C1061.03 1270.25 1036.74 1283.16 1010.45 1289.79C999.306 1292.59 987.557 1291.17 975.915 1292.26C985.825 1324.19 985.919 1357.95 972.948 1388.82C963.213 1411.98 943.554 1428.12 919.196 1435.88C879.329 1448.6 833.474 1438.76 802.16 1410.71C775.345 1386.68 774.647 1353.45 764.912 1353.41L764.952 1353.4ZM751.457 880.202C827.968 877.651 903.755 872.508 976.238 852.017C1055.47 829.62 1142.1 775.076 1159.98 688.521C1165.84 603.523 1134.38 525.709 1083.12 459.43C1020.43 378.367 916.215 339.601 816.944 330.389C794.345 328.295 773.331 325.032 750.745 324.938C728.59 324.844 708.032 328.187 685.849 330.175C587.504 338.997 482.808 376.97 419.913 456.637C368.363 521.923 332.592 605.604 341.736 690.159C344.099 711.979 355.553 731.422 367.289 749.04C402.819 802.415 470.28 837.528 530.718 853.789C601.496 872.817 676.96 877.959 751.47 880.202H751.457ZM1220.03 614.668C1224.87 607.001 1231.23 599.723 1231.92 590.807C1235.74 541.769 1216.33 540.91 1236.98 490.488C1253 451.373 1276.88 400.966 1256.56 360.911C1249.01 346.06 1235.89 336.553 1218.53 336.902C1197.8 337.318 1176.39 342.568 1158.55 353.7C1144.78 362.294 1133.62 373.372 1121.81 384.275C1111.37 393.916 1103.8 405.706 1098.79 419.174C1125.18 448.93 1145.33 481.062 1162.59 516.108C1183.11 557.788 1194.73 600.797 1198.05 647.956C1207.1 637.079 1212.67 626.323 1220.02 614.655L1220.03 614.668ZM276.37 608.102C285.46 621.543 291.879 634.42 302.581 647.875C306.032 601.106 317.325 558.795 337.426 517.572C354.949 481.599 375.588 448.648 402.362 418.757C397.824 409.425 393.42 400.522 386.518 393.513C354.385 360.897 330.376 340.339 282.668 338.997C265.091 338.5 251.824 347.832 244.157 363.005C223.881 403.181 247.769 453.535 263.748 492.57C283.097 539.835 267.763 537.754 268.246 586.322C268.327 594.07 271.885 601.482 276.356 608.089L276.37 608.102ZM463.996 1027.32C465.204 1024.4 458.96 1019.11 457.295 1016.4C442.686 992.605 444.808 962.192 462.317 939.217L413.521 916.188C365.57 893.549 318.6 871.152 266.917 852.165C284.359 901.028 310.866 943.017 345.483 978.761C372.929 1005.08 403.571 1024.76 437.14 1042.31C440.148 1044.24 447.909 1049.55 450.877 1046.88C456.194 1042.1 461.082 1034.34 463.996 1027.32ZM1051.06 1048.69C1088.56 1029.93 1121.94 1009.78 1151.83 981.984C1188.44 945.89 1215.65 902.358 1233.96 852.138C1177.79 872.749 1126.27 897.577 1073.8 922.539L1038.41 939.378C1058.44 965.629 1058.42 1001.55 1035.88 1026.08C1039.99 1034.42 1044.56 1041.58 1051.06 1048.69ZM905.232 1258.72C905.326 1258.65 905.406 1258.57 905.5 1258.5C919.599 1247.03 928.166 1229.77 933.846 1212.86C959.654 1136.15 933.014 1062.59 906.521 990.215L882.109 923.573C881.075 920.754 877.436 918.686 874.267 919.236C780.434 935.43 720.801 935.417 627.036 919.33C622.927 918.632 619.65 920.512 618.334 924.137L595.104 987.771C570.827 1054.25 545.247 1121.61 560.944 1193.23C564.489 1209.37 569.833 1225.32 578.843 1239.17C595.319 1264.49 619.905 1272 647.58 1279.69C680.975 1288.98 714.544 1294.11 749.322 1294.33C785.819 1294.56 823.148 1288.67 858.154 1278.58C873.864 1274.04 892.247 1269.12 905.218 1258.72H905.232ZM556.567 982.978C560.138 973.659 557.923 967.281 553.572 959.721C545.596 945.863 531.309 938.371 514.981 943.876C501.177 948.522 489.925 960.956 486.434 975.351C482.942 989.745 490.059 1001.96 503.017 1007.55C524.421 1016.78 548.134 1004.95 556.58 982.964L556.567 982.978ZM992.015 1009.52C1003.52 1006.66 1011 999.306 1013.81 990.672C1017.04 980.709 1014.4 971.081 1008.84 962.594C998.877 947.408 981.515 937.041 963.266 944.628C953.894 948.522 943.272 960.728 942.977 971.739C942.319 997.117 968.06 1015.47 992.015 1009.52ZM508.656 1188.54L512.282 1142.92C517.505 1110.65 524.958 1079.7 534.72 1047.62C520.433 1049.14 508.079 1048.68 494.208 1044.97L446.593 1130.7C444.499 1134.46 445.009 1139.59 447.493 1142.82C460.84 1160.24 487.011 1184.45 508.67 1188.53L508.656 1188.54ZM1054.13 1141.51C1056.15 1138.81 1056.16 1134.31 1054.43 1131.18L1006.66 1045.13C992.794 1048.41 980.011 1049.3 966.1 1047.54C980.387 1096.12 990.363 1137.58 992.297 1188.62C1015.18 1183.51 1040.54 1159.71 1054.13 1141.51ZM509.22 1212.26C507.663 1208.89 498.505 1208.13 495 1206.78C473.046 1198.28 454.69 1182.82 438.846 1164.21C433.582 1202.21 481.6 1233.85 514.86 1237.25C513.128 1228.71 512.859 1220.14 509.22 1212.26ZM986.496 1237.33C1012.01 1232.84 1033.57 1221.27 1049.06 1202.83C1058.07 1191.75 1064.14 1178.86 1061.85 1164.4C1044.85 1183.47 1027.33 1199.02 1003.94 1207.29C1000.65 1208.46 992.015 1209.58 990.874 1212.98C988.322 1220.55 987.329 1228.65 986.496 1237.33ZM640.53 1396.49C651.085 1398.32 676.638 1358 680.961 1347.84C635.146 1338.13 597.266 1331.08 558.191 1303.99C555.694 1315.84 554.485 1327.37 556.124 1340.53C569.175 1344.56 581.515 1347.74 594.473 1350.43C615.286 1354.75 601.885 1377.35 611.835 1382.28L640.517 1396.5L640.53 1396.49ZM889.951 1381.65C897.229 1377.98 887.453 1354.36 904.52 1350.8C917.88 1348.01 930.449 1344.73 944.454 1340.84C946.71 1328.41 945.3 1316.38 942.332 1304.12C902.976 1330.96 867.11 1337.82 820.113 1347.82C824.799 1358.38 850.218 1401.67 862.451 1395.51L889.964 1381.63L889.951 1381.65ZM590.176 1389.66C588.484 1382.96 588.753 1375.61 587.894 1368.62L558.89 1362.35C562.784 1385.78 583.65 1401.17 605.793 1401.94C601.281 1396.67 591.868 1396.4 590.176 1389.66ZM907.877 1393.56L893.536 1402.3C916.994 1401.09 937.686 1386.29 941.661 1362.42L914.779 1368.56C909.461 1369.76 914.591 1389.46 907.877 1393.56Z" fill="white"/>
+<path d="M941.675 1362.42C937.7 1386.29 916.995 1401.08 893.55 1402.3L907.891 1393.56" fill="white"/>
+<path d="M839.503 838.924C780.286 856.246 718.008 855.185 659.974 837.018C643.001 831.7 628.499 820.22 620.536 805.369C617.609 799.903 616.159 795.204 608.921 795.365L569.162 796.251C524.353 797.258 467.366 797.607 426.855 777.506C400.536 764.454 396.051 737.478 396.562 709.709L398.737 593.143C399.328 561.467 402.792 529.442 435.18 515.799C481.492 496.289 559.776 489.091 611.298 483.841C701.949 474.616 798.185 474.576 888.89 483.801C937.431 488.742 1033.16 497.094 1073.53 520.217C1089.9 529.59 1098.44 547.623 1100.11 566.825C1103.55 606.745 1102.81 645.968 1103.77 686.305C1104.62 721.526 1108.03 761.715 1072.42 778.258C1038.17 794.183 989.504 797.661 951.732 796.708L893.979 795.257C885.855 795.056 884.109 798.87 881.155 805.342C873.784 821.495 858.154 833.459 839.503 838.911V838.924ZM828.411 627.115C854.891 666.19 880.551 724.654 886.486 771.477C891.924 773.29 898.397 772.162 904.466 772.699C950.496 776.741 1021.06 778.406 1062.89 759.016C1073.4 754.142 1079.31 745.239 1080.93 733.866C1083.7 714.57 1082.37 695.892 1081.97 676.1C1081.23 639.657 1081.66 604.06 1078.64 568.087C1077.25 551.638 1068.41 539.58 1053.55 534.007C1012.64 518.632 942.99 510.63 898.061 506.48C768.725 494.53 733.96 494.463 604.611 506.306C567.134 509.73 531.591 514.268 494.759 521.076C475.476 524.635 457.08 528.932 439.571 537.874C428.318 543.622 422.504 556.942 421.779 570.128C418.878 622.912 417.858 675.187 418.852 727.85C419.147 743.44 427.499 755.243 440.887 760.574C492.087 780.957 547.181 774.122 596.971 772.739L613.957 772.269C617.891 725.017 656.093 634.554 691.086 605.309C734.592 568.946 796.762 580.454 828.398 627.129L828.411 627.115Z" fill="white"/>
+<path d="M525.28 720.451C514.055 734.59 495.216 735.154 482.849 722.787C475.168 715.106 469.555 705.505 465.768 694.696C453.187 658.764 451.495 619.837 461.498 583.071C464.466 572.181 469.394 562.164 476.417 554.215C487.911 541.217 506.173 540.908 517.976 553.356C550.847 588.013 555.573 682.329 525.28 720.437V720.451Z" fill="white"/>
+<path d="M1017.82 722.788C1005.38 735.357 987.275 734.161 976.144 721.19C945.461 685.419 949.449 589.008 982.347 553.652C994.244 540.869 1013.14 541.003 1024.66 554.525C1032.06 563.213 1037.08 574.103 1039.99 585.771C1048.84 621.301 1047.26 658.429 1035.57 693.046C1031.77 704.298 1026.24 714.302 1017.84 722.788H1017.82Z" fill="white"/>
+</svg>
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs b/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs
new file mode 100644
index 0000000000..dcf24c8f37
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/interaction.rs
@@ -0,0 +1,159 @@
+use std::time::{Duration, Instant};
+
+use crate::{Point, Rect};
+
+pub const CONTROL_ARM_DELAY: Duration = Duration::from_millis(400);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PointerButton {
+ Primary,
+ Other,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InteractionOutcome {
+ None,
+ Accept,
+ Decline,
+ Cancel,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Target {
+ Accept,
+ Decline,
+}
+
+/// Consent interaction state with defenses against a click already queued at
+/// the pointer position before the protected card appeared.
+pub struct ConsentInteraction {
+ shown_at: Instant,
+ accept_rect: Rect,
+ decline_rect: Rect,
+ accept_entered_after_arm: bool,
+ pressed: Option<Target>,
+}
+
+impl ConsentInteraction {
+ pub fn new(shown_at: Instant, accept_rect: Rect, decline_rect: Rect) -> Self {
+ Self {
+ shown_at,
+ accept_rect,
+ decline_rect,
+ accept_entered_after_arm: false,
+ pressed: None,
+ }
+ }
+
+ pub fn accept_armed(&self, now: Instant) -> bool {
+ now.saturating_duration_since(self.shown_at) >= CONTROL_ARM_DELAY
+ && self.accept_entered_after_arm
+ }
+
+ pub fn pointer_moved(&mut self, point: Point, now: Instant) {
+ if now.saturating_duration_since(self.shown_at) >= CONTROL_ARM_DELAY
+ && self.accept_rect.contains(point)
+ {
+ self.accept_entered_after_arm = true;
+ }
+ }
+
+ pub fn pointer_down(
+ &mut self,
+ point: Point,
+ button: PointerButton,
+ now: Instant,
+ ) -> InteractionOutcome {
+ if button != PointerButton::Primary {
+ return InteractionOutcome::None;
+ }
+ self.pressed = if self.decline_rect.contains(point) {
+ Some(Target::Decline)
+ } else if self.accept_rect.contains(point) && self.accept_armed(now) {
+ Some(Target::Accept)
+ } else {
+ None
+ };
+ InteractionOutcome::None
+ }
+
+ pub fn pointer_up(&mut self, point: Point) -> InteractionOutcome {
+ match self.pressed.take() {
+ Some(Target::Accept) if self.accept_rect.contains(point) => InteractionOutcome::Accept,
+ Some(Target::Decline) if self.decline_rect.contains(point) => {
+ InteractionOutcome::Decline
+ }
+ _ => InteractionOutcome::None,
+ }
+ }
+
+ pub fn escape(&mut self) -> InteractionOutcome {
+ self.pressed = None;
+ InteractionOutcome::Cancel
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn interaction(now: Instant) -> ConsentInteraction {
+ ConsentInteraction::new(
+ now,
+ Rect {
+ x: 220.0,
+ y: 190.0,
+ width: 170.0,
+ height: 44.0,
+ },
+ Rect {
+ x: 30.0,
+ y: 190.0,
+ width: 170.0,
+ height: 44.0,
+ },
+ )
+ }
+
+ #[test]
+ fn queued_accept_click_is_rejected() {
+ let now = Instant::now();
+ let mut state = interaction(now);
+ let point = Point { x: 300.0, y: 210.0 };
+ state.pointer_down(point, PointerButton::Primary, now);
+ assert_eq!(state.pointer_up(point), InteractionOutcome::None);
+ }
+
+ #[test]
+ fn accept_requires_post_arm_entry_and_press_release() {
+ let now = Instant::now();
+ let later = now + CONTROL_ARM_DELAY;
+ let point = Point { x: 300.0, y: 210.0 };
+ let mut state = interaction(now);
+ state.pointer_moved(point, later);
+ state.pointer_down(point, PointerButton::Primary, later);
+ assert_eq!(state.pointer_up(point), InteractionOutcome::Accept);
+ }
+
+ #[test]
+ fn dragging_out_cancels_accept() {
+ let now = Instant::now();
+ let later = now + CONTROL_ARM_DELAY;
+ let mut state = interaction(now);
+ state.pointer_moved(Point { x: 300.0, y: 210.0 }, later);
+ state.pointer_down(Point { x: 300.0, y: 210.0 }, PointerButton::Primary, later);
+ assert_eq!(
+ state.pointer_up(Point { x: 10.0, y: 10.0 }),
+ InteractionOutcome::None
+ );
+ }
+
+ #[test]
+ fn decline_is_available_immediately() {
+ let now = Instant::now();
+ let mut state = interaction(now);
+ let point = Point { x: 100.0, y: 210.0 };
+ state.pointer_down(point, PointerButton::Primary, now);
+ assert_eq!(state.pointer_up(point), InteractionOutcome::Decline);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs b/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs
new file mode 100644
index 0000000000..f21203bdfb
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/lib.rs
@@ -0,0 +1,92 @@
+//! Shared native overlay UI for Cua Driver.
+//!
+//! This crate deliberately contains no windowing toolkit and no web runtime.
+//! It turns small, bounded UI models into premultiplied RGBA pixmaps and owns
+//! the placement and interaction state machines. Platform crates supply only
+//! native windows, pointer/key events, and capture/privacy controls.
+
+mod interaction;
+mod placement;
+mod render;
+mod sanitize;
+
+pub use interaction::{ConsentInteraction, InteractionOutcome, PointerButton, CONTROL_ARM_DELAY};
+pub use placement::{place_near_pointer, surface_fits, Point, Rect, Size};
+pub use render::{
+ render_consent, render_indicator, ConsentVisualState, RenderError, ACCEPT_RECT, CONSENT_SIZE,
+ DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
+};
+pub use sanitize::{sanitize_label, sanitize_summary};
+
+use serde::{Deserialize, Serialize};
+
+/// Input sent over the inherited private pipe to the protected helper.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "surface", rename_all = "snake_case")]
+pub enum HelperRequest {
+ Consent(ConsentCard),
+ Indicator(IndicatorCard),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ConsentCard {
+ pub operation: String,
+ pub risk_label: String,
+ pub summary: String,
+ pub request_digest: String,
+ /// JSON-private-wire timestamp. Milliseconds since Unix epoch fit in
+ /// `u64`; using `u128` here makes serde_json reject every helper request.
+ pub expires_unix_ms: u64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct IndicatorCard {
+ pub indicator_id: String,
+ pub summary: String,
+}
+
+/// Output emitted by the helper. The parent accepts events only from the
+/// child connected to its inherited pipe, never from public stdio or a tool
+/// argument.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+pub enum HelperEvent {
+ Ready,
+ Decision {
+ action: HelperDecision,
+ request_digest: String,
+ },
+ Stop {
+ indicator_id: String,
+ },
+ Failed {
+ reason: String,
+ },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum HelperDecision {
+ Accept,
+ Decline,
+ Cancel,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn consent_helper_request_round_trips_through_json() {
+ let request = HelperRequest::Consent(ConsentCard {
+ operation: "browser.existing_profile.attach".to_owned(),
+ risk_label: "authenticated session".to_owned(),
+ summary: "Attach to the signed-in profile.".to_owned(),
+ request_digest: "digest".to_owned(),
+ expires_unix_ms: 4_102_444_800_000,
+ });
+ let encoded = serde_json::to_vec(&request).unwrap();
+ let decoded: HelperRequest = serde_json::from_slice(&encoded).unwrap();
+ assert_eq!(decoded, request);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs b/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs
new file mode 100644
index 0000000000..9b2cc2f0d2
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/placement.rs
@@ -0,0 +1,147 @@
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Point {
+ pub x: f64,
+ pub y: f64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Size {
+ pub width: f64,
+ pub height: f64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Rect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl Rect {
+ pub fn contains(self, point: Point) -> bool {
+ point.x >= self.x
+ && point.x <= self.x + self.width
+ && point.y >= self.y
+ && point.y <= self.y + self.height
+ }
+}
+
+const EDGE: f64 = 12.0;
+
+pub fn surface_fits(work_area: Rect, surface: Size) -> bool {
+ work_area.width.is_finite()
+ && work_area.height.is_finite()
+ && surface.width.is_finite()
+ && surface.height.is_finite()
+ && surface.width > 0.0
+ && surface.height > 0.0
+ && work_area.width >= surface.width + EDGE * 2.0
+ && work_area.height >= surface.height + EDGE * 2.0
+}
+
+/// Place a surface close to the physical pointer while keeping both the
+/// pointer and the whole card visible. Coordinates use a top-left origin.
+pub fn place_near_pointer(pointer: Point, work_area: Rect, surface: Size) -> Point {
+ const GAP: f64 = 18.0;
+
+ let right = pointer.x + GAP;
+ let left = pointer.x - GAP - surface.width;
+ let below = pointer.y + GAP;
+ let above = pointer.y - GAP - surface.height;
+
+ let x = if right + surface.width <= work_area.x + work_area.width - EDGE {
+ right
+ } else if left >= work_area.x + EDGE {
+ left
+ } else {
+ (pointer.x - surface.width / 2.0).clamp(
+ work_area.x + EDGE,
+ work_area.x + work_area.width - surface.width - EDGE,
+ )
+ };
+ let y = if below + surface.height <= work_area.y + work_area.height - EDGE {
+ below
+ } else if above >= work_area.y + EDGE {
+ above
+ } else {
+ (pointer.y - surface.height / 2.0).clamp(
+ work_area.y + EDGE,
+ work_area.y + work_area.height - surface.height - EDGE,
+ )
+ };
+ Point { x, y }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const WORK: Rect = Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 1440.0,
+ height: 900.0,
+ };
+ const CARD: Size = Size {
+ width: 420.0,
+ height: 250.0,
+ };
+
+ #[test]
+ fn prefers_below_and_right() {
+ assert_eq!(
+ place_near_pointer(Point { x: 200.0, y: 200.0 }, WORK, CARD),
+ Point { x: 218.0, y: 218.0 }
+ );
+ }
+
+ #[test]
+ fn flips_at_bottom_right_edge() {
+ assert_eq!(
+ place_near_pointer(
+ Point {
+ x: 1400.0,
+ y: 860.0
+ },
+ WORK,
+ CARD
+ ),
+ Point { x: 962.0, y: 592.0 }
+ );
+ }
+
+ #[test]
+ fn respects_offset_work_areas() {
+ let work = Rect {
+ x: -1920.0,
+ y: -200.0,
+ width: 1920.0,
+ height: 1080.0,
+ };
+ let point = place_near_pointer(
+ Point {
+ x: -1910.0,
+ y: -190.0,
+ },
+ work,
+ CARD,
+ );
+ assert!(point.x >= work.x + 12.0);
+ assert!(point.y >= work.y + 12.0);
+ }
+
+ #[test]
+ fn reports_work_areas_that_cannot_contain_the_surface() {
+ assert!(!surface_fits(
+ Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 320.0,
+ height: 200.0,
+ },
+ CARD
+ ));
+ assert!(surface_fits(WORK, CARD));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/render.rs b/libs/cua-driver/rust/crates/overlay-ui/src/render.rs
new file mode 100644
index 0000000000..2894716914
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/render.rs
@@ -0,0 +1,290 @@
+use std::sync::{Arc, OnceLock};
+
+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
+use tiny_skia::{Pixmap, Transform};
+
+use crate::{sanitize_label, sanitize_summary, ConsentCard, IndicatorCard, Rect, Size};
+
+pub const CONSENT_SIZE: Size = Size {
+ width: 424.0,
+ height: 274.0,
+};
+pub const INDICATOR_SIZE: Size = Size {
+ width: 380.0,
+ height: 76.0,
+};
+
+pub const DECLINE_RECT: Rect = Rect {
+ x: 32.0,
+ y: 202.0,
+ width: 172.0,
+ height: 44.0,
+};
+pub const ACCEPT_RECT: Rect = Rect {
+ x: 220.0,
+ y: 202.0,
+ width: 172.0,
+ height: 44.0,
+};
+pub const STOP_RECT: Rect = Rect {
+ x: 296.0,
+ y: 14.0,
+ width: 64.0,
+ height: 44.0,
+};
+
+const CUA_DRIVER_MARK_SVG: &str = include_str!("cua-driver-mark.svg");
+
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ConsentVisualState {
+ pub accept_armed: bool,
+ pub accept_hovered: bool,
+ pub decline_hovered: bool,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum RenderError {
+ #[error("invalid render scale")]
+ InvalidScale,
+ #[error("could not allocate overlay pixmap")]
+ Allocation,
+ #[error("could not parse generated overlay SVG: {0}")]
+ Svg(String),
+}
+
+pub fn render_consent(
+ card: &ConsentCard,
+ scale: f32,
+ state: ConsentVisualState,
+) -> Result<Pixmap, RenderError> {
+ let title = operation_title(&sanitize_label(&card.operation));
+ let summary = sanitize_summary(&card.summary);
+ let risk_label = sanitize_label(&card.risk_label);
+ let lines = wrap_text(&summary, 50, 2);
+ let accept_fill = if state.accept_armed {
+ if state.accept_hovered {
+ "#2A2A29"
+ } else {
+ "#111110"
+ }
+ } else {
+ "#D9D9D5"
+ };
+ let accept_text = if state.accept_armed {
+ "#FFFFFF"
+ } else {
+ "#969691"
+ };
+ let decline_fill = if state.decline_hovered {
+ "#E7E7E3"
+ } else {
+ "#F5F5F2"
+ };
+ let summary_svg = text_lines_svg(&lines, 112.0, 14.0, 19.0, "#5F5F5A");
+ let brand_mark = brand_mark_data_uri();
+ let svg = format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="424" height="274" viewBox="0 0 424 274">
+<rect x="10" y="12" width="404" height="252" rx="20" fill="#171716" opacity=".13"/>
+<rect x="6" y="6" width="412" height="256" rx="20" fill="#FBFBF9" stroke="#D5D5D1" stroke-width="1"/>
+<circle cx="34" cy="32" r="10" fill="#1C1C1B"/>
+<image x="27" y="23.5" width="14" height="17" preserveAspectRatio="xMidYMid meet" href="{brand_mark}"/>
+<text x="52" y="36" fill="#767670" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12" font-weight="600">Cua Driver</text>
+<text x="32" y="82" fill="#1C1C1A" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="20" font-weight="600">{title}</text>
+{summary_svg}
+<path d="M34 169v-2.5a4 4 0 018 0v2.5m-9 0h10v8h-10z" fill="none" stroke="#8A8A84" stroke-width="1.2" stroke-linejoin="round"/>
+<text x="51" y="176" fill="#777771" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="11.5">Local desktop confirmation · {risk_label}</text>
+<rect x="32" y="202" width="172" height="44" rx="10" fill="{decline_fill}" stroke="#D6D6D2"/>
+<text x="118" y="229" text-anchor="middle" fill="#2B2B29" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="13.5" font-weight="600">Don’t allow</text>
+<rect x="220" y="202" width="172" height="44" rx="10" fill="{accept_fill}"/>
+<text x="306" y="229" text-anchor="middle" fill="{accept_text}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="13.5" font-weight="600">Allow once</text>
+</svg>"##,
+ risk_label = escape_xml(&risk_label)
+ );
+ render_svg(&svg, CONSENT_SIZE, scale)
+}
+
+pub fn render_indicator(
+ card: &IndicatorCard,
+ scale: f32,
+ stop_hovered: bool,
+) -> Result<Pixmap, RenderError> {
+ let summary = sanitize_summary(&card.summary);
+ let label = ellipsize(&summary, 31);
+ let stop_fill = if stop_hovered { "#E7E7E3" } else { "#F5F5F2" };
+ let brand_mark = brand_mark_data_uri();
+ let svg = format!(
+ r##"<svg xmlns="http://www.w3.org/2000/svg" width="380" height="76" viewBox="0 0 380 76">
+<rect x="8" y="9" width="364" height="60" rx="18" fill="#171716" opacity=".12"/>
+<rect x="4" y="4" width="372" height="64" rx="18" fill="#FBFBF9" stroke="#D5D5D1"/>
+<circle cx="28" cy="36" r="9" fill="#1C1C1B"/>
+<image x="22" y="28.75" width="12" height="14.5" preserveAspectRatio="xMidYMid meet" href="{brand_mark}"/>
+<text x="48" y="31" fill="#252523" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12.5" font-weight="600">Cua is driving this session</text>
+<text x="48" y="49" fill="#777771" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="10.5">{label}</text>
+<rect x="296" y="14" width="64" height="44" rx="10" fill="{stop_fill}" stroke="#D6D6D2"/>
+<text x="328" y="41" text-anchor="middle" fill="#242422" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="12.5" font-weight="600">Stop</text>
+</svg>"##
+ );
+ render_svg(&svg, INDICATOR_SIZE, scale)
+}
+
+fn brand_mark_data_uri() -> &'static str {
+ static DATA_URI: OnceLock<String> = OnceLock::new();
+ DATA_URI
+ .get_or_init(|| {
+ format!(
+ "data:image/svg+xml;base64,{}",
+ BASE64.encode(CUA_DRIVER_MARK_SVG)
+ )
+ })
+ .as_str()
+}
+
+fn render_svg(svg: &str, size: Size, scale: f32) -> Result<Pixmap, RenderError> {
+ if !scale.is_finite() || scale <= 0.0 || scale > 4.0 {
+ return Err(RenderError::InvalidScale);
+ }
+ let mut options = usvg::Options::default();
+ options.fontdb = font_database();
+ let tree =
+ usvg::Tree::from_str(svg, &options).map_err(|error| RenderError::Svg(error.to_string()))?;
+ let width = (size.width as f32 * scale).round() as u32;
+ let height = (size.height as f32 * scale).round() as u32;
+ let mut pixmap = Pixmap::new(width, height).ok_or(RenderError::Allocation)?;
+ resvg::render(
+ &tree,
+ Transform::from_scale(scale, scale),
+ &mut pixmap.as_mut(),
+ );
+ Ok(pixmap)
+}
+
+fn font_database() -> Arc<usvg::fontdb::Database> {
+ static DATABASE: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
+ DATABASE
+ .get_or_init(|| {
+ let mut database = usvg::fontdb::Database::new();
+ database.load_system_fonts();
+ Arc::new(database)
+ })
+ .clone()
+}
+
+fn operation_title(operation: &str) -> String {
+ match operation {
+ "browser.existing_profile.attach" => "Allow Cua to use Chrome?".to_owned(),
+ other if !other.is_empty() => other.replace(['.', '_'], " "),
+ _ => "Allow a protected action".to_owned(),
+ }
+}
+
+fn wrap_text(input: &str, max_columns: usize, max_lines: usize) -> Vec<String> {
+ if input.is_empty() {
+ return vec!["Review this protected action before continuing.".to_owned()];
+ }
+ let mut lines = Vec::new();
+ let mut line = String::new();
+ for word in input.split_whitespace() {
+ let extra = usize::from(!line.is_empty());
+ if line.chars().count() + extra + word.chars().count() > max_columns && !line.is_empty() {
+ lines.push(line);
+ line = String::new();
+ if lines.len() == max_lines {
+ break;
+ }
+ }
+ if !line.is_empty() {
+ line.push(' ');
+ }
+ line.push_str(word);
+ }
+ if lines.len() < max_lines && !line.is_empty() {
+ lines.push(line);
+ }
+ if lines.len() == max_lines {
+ if let Some(last) = lines.last_mut() {
+ *last = ellipsize(last, max_columns);
+ }
+ }
+ lines
+}
+
+fn ellipsize(input: &str, max_chars: usize) -> String {
+ if input.chars().count() <= max_chars {
+ return input.to_owned();
+ }
+ let mut output = input
+ .chars()
+ .take(max_chars.saturating_sub(1))
+ .collect::<String>();
+ output.push('…');
+ output
+}
+
+fn text_lines_svg(lines: &[String], y: f64, size: f64, line_height: f64, fill: &str) -> String {
+ lines
+ .iter()
+ .enumerate()
+ .map(|(index, line)| {
+ format!(
+ r#"<text x="32" y="{}" fill="{}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif" font-size="{}">{}</text>"#,
+ y + index as f64 * line_height,
+ fill,
+ size,
+ escape_xml(line)
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("")
+}
+
+fn escape_xml(input: &str) -> String {
+ input
+ .replace('&', "&amp;")
+ .replace('<', "&lt;")
+ .replace('>', "&gt;")
+ .replace('"', "&quot;")
+ .replace('\'', "&apos;")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn card() -> ConsentCard {
+ ConsentCard {
+ operation: "browser.existing_profile.attach".to_owned(),
+ risk_label: "authenticated session".to_owned(),
+ summary: "Attach to Chrome profile “Work” for this session.".to_owned(),
+ request_digest: "abc".to_owned(),
+ expires_unix_ms: 1,
+ }
+ }
+
+ #[test]
+ fn consent_renders_at_requested_scale() {
+ let pixmap = render_consent(&card(), 2.0, ConsentVisualState::default()).unwrap();
+ assert_eq!((pixmap.width(), pixmap.height()), (848, 548));
+ assert!(pixmap.data().iter().any(|byte| *byte != 0));
+ }
+
+ #[test]
+ fn untrusted_xml_is_escaped() {
+ let mut card = card();
+ card.summary = "<script>&\"".to_owned();
+ render_consent(&card, 1.0, ConsentVisualState::default()).unwrap();
+ }
+
+ #[test]
+ fn indicator_renders() {
+ let pixmap = render_indicator(
+ &IndicatorCard {
+ indicator_id: "one".to_owned(),
+ summary: "Chrome — Work".to_owned(),
+ },
+ 1.0,
+ false,
+ )
+ .unwrap();
+ assert_eq!((pixmap.width(), pixmap.height()), (380, 76));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs b/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs
new file mode 100644
index 0000000000..3cc36a4f0f
--- /dev/null
+++ b/libs/cua-driver/rust/crates/overlay-ui/src/sanitize.rs
@@ -0,0 +1,87 @@
+const MAX_LABEL_CHARS: usize = 72;
+const MAX_SUMMARY_CHARS: usize = 280;
+
+/// Strip control and bidirectional-override characters from short labels.
+pub fn sanitize_label(input: &str) -> String {
+ sanitize(input, MAX_LABEL_CHARS, false)
+}
+
+/// Strip controls, collapse whitespace, and bound untrusted resource text.
+pub fn sanitize_summary(input: &str) -> String {
+ sanitize(input, MAX_SUMMARY_CHARS, true)
+}
+
+fn sanitize(input: &str, max_chars: usize, collapse_whitespace: bool) -> String {
+ let mut output = String::with_capacity(input.len().min(max_chars));
+ let mut previous_space = false;
+ for ch in input.chars() {
+ if output.chars().count() >= max_chars {
+ break;
+ }
+ if is_bidi_control(ch) || ch.is_control() {
+ if collapse_whitespace && ch.is_whitespace() && !previous_space && !output.is_empty() {
+ output.push(' ');
+ previous_space = true;
+ }
+ continue;
+ }
+ if collapse_whitespace && ch.is_whitespace() {
+ if !previous_space && !output.is_empty() {
+ output.push(' ');
+ previous_space = true;
+ }
+ } else {
+ output.push(match ch {
+ '—' | '–' => '-',
+ other => other,
+ });
+ previous_space = false;
+ }
+ }
+ let output = output.trim().to_owned();
+ if input.chars().count() > max_chars && !output.is_empty() {
+ format!("{}…", output.trim_end_matches('…'))
+ } else {
+ output
+ }
+}
+
+fn is_bidi_control(ch: char) -> bool {
+ matches!(
+ ch,
+ '\u{061c}'
+ | '\u{200e}'
+ | '\u{200f}'
+ | '\u{202a}'..='\u{202e}'
+ | '\u{2066}'..='\u{2069}'
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn summary_removes_controls_and_collapses_lines() {
+ assert_eq!(
+ sanitize_summary("Chrome\n\u{202e}evil\t profile"),
+ "Chrome evil profile"
+ );
+ }
+
+ #[test]
+ fn text_uses_plain_hyphens_instead_of_long_dashes() {
+ assert_eq!(
+ sanitize_summary("Chrome — Work – tab"),
+ "Chrome - Work - tab"
+ );
+ assert_eq!(sanitize_label("high—risk"), "high-risk");
+ }
+
+ #[test]
+ fn label_is_bounded() {
+ let label = sanitize_label(&"a".repeat(100));
+ assert_eq!(label.chars().count(), 73);
+ assert!(label.ends_with('…'));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index 538f2419d2..6706e80410 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -14,6 +14,7 @@ async-trait = "0.1"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
+overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
# tiny-skia for cursor rendering (shared cross-platform)
tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index 77a65cb645..62a7e72408 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -12,6 +12,18 @@
use cua_driver_core::tool::ToolRegistry;
+#[cfg(target_os = "linux")]
+pub mod protected_consent;
+
+#[cfg(target_os = "linux")]
+pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
+ let mut stdout = std::io::stdout().lock();
+ serde_json::to_writer(&mut stdout, event)?;
+ std::io::Write::write_all(&mut stdout, b"\n")?;
+ std::io::Write::flush(&mut stdout)?;
+ Ok(())
+}
+
pub mod health_report;
pub mod overlay;
pub mod pip;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs
new file mode 100644
index 0000000000..50ae63144b
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/protected_consent.rs
@@ -0,0 +1,465 @@
+//! Protected consent surface for interactive Linux X11/XWayland sessions.
+//!
+//! Pure Wayland deliberately fails closed: the protocol does not expose global
+//! cursor coordinates or arbitrary window positioning, and GNOME does not
+//! implement layer-shell. A future portal/compositor protocol can replace this
+//! limitation without changing the shared UI or provider contract.
+
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use overlay_ui::{
+ place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
+ ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
+ Rect, ACCEPT_RECT, CONSENT_SIZE, CONTROL_ARM_DELAY, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
+};
+use x11rb::connection::Connection;
+use x11rb::protocol::shape::{ConnectionExt as ShapeConnectionExt, SK, SO};
+use x11rb::protocol::xproto::{
+ AtomEnum, ClipOrdering, ColormapAlloc, ConfigureWindowAux, ConnectionExt, CreateGCAux,
+ CreateWindowAux, EventMask, ImageFormat, InputFocus, MapState, PropMode, Rectangle, StackMode,
+ VisualClass, WindowClass,
+};
+use x11rb::protocol::Event;
+use x11rb::wrapper::ConnectionExt as WrapperConnectionExt;
+
+pub fn interactive_surface_available() -> bool {
+ std::env::var_os("DISPLAY").is_some() && x11rb::connect(None).is_ok()
+}
+
+pub fn run(request: HelperRequest) -> anyhow::Result<()> {
+ if !interactive_surface_available() {
+ anyhow::bail!(
+ "protected Linux UI requires X11/XWayland; pure Wayland has no certified protected-positioning path"
+ );
+ }
+ run_x11(request)
+}
+
+enum SurfaceMode {
+ Consent {
+ card: overlay_ui::ConsentCard,
+ interaction: ConsentInteraction,
+ },
+ Indicator {
+ card: overlay_ui::IndicatorCard,
+ stop_pressed: bool,
+ },
+}
+
+fn run_x11(request: HelperRequest) -> anyhow::Result<()> {
+ let (connection, screen_number) = x11rb::connect(None)?;
+ let screen = &connection.setup().roots[screen_number];
+ let root = screen.root;
+ let logical_size = match &request {
+ HelperRequest::Consent(_) => CONSENT_SIZE,
+ HelperRequest::Indicator(_) => INDICATOR_SIZE,
+ };
+ let pointer = connection.query_pointer(root)?.reply()?;
+ let work = Rect {
+ x: 0.0,
+ y: 0.0,
+ width: screen.width_in_pixels as f64,
+ height: screen.height_in_pixels as f64,
+ };
+ if !surface_fits(work, logical_size) {
+ anyhow::bail!("the active display work area is too small for the local confirmation");
+ }
+ let origin = match &request {
+ HelperRequest::Consent(_) => place_near_pointer(
+ Point {
+ x: pointer.root_x as f64,
+ y: pointer.root_y as f64,
+ },
+ work,
+ logical_size,
+ ),
+ HelperRequest::Indicator(_) => Point {
+ x: work.width - logical_size.width - 18.0,
+ y: 18.0,
+ },
+ };
+ let (visual, depth, base_colormap) = find_argb_visual(screen).unwrap_or((
+ screen.root_visual,
+ screen.root_depth,
+ screen.default_colormap,
+ ));
+ let colormap = if visual != screen.root_visual {
+ let id = connection.generate_id()?;
+ connection.create_colormap(ColormapAlloc::NONE, id, root, visual)?;
+ id
+ } else {
+ base_colormap
+ };
+ let window = connection.generate_id()?;
+ connection.create_window(
+ depth,
+ window,
+ root,
+ origin.x.round() as i16,
+ origin.y.round() as i16,
+ logical_size.width as u16,
+ logical_size.height as u16,
+ 0,
+ WindowClass::INPUT_OUTPUT,
+ visual,
+ &CreateWindowAux::new()
+ .background_pixel(0)
+ .border_pixel(0)
+ .colormap(colormap)
+ .override_redirect(1)
+ .event_mask(
+ EventMask::POINTER_MOTION
+ | EventMask::BUTTON_PRESS
+ | EventMask::BUTTON_RELEASE
+ | EventMask::KEY_PRESS
+ | EventMask::EXPOSURE
+ | EventMask::STRUCTURE_NOTIFY,
+ ),
+ )?;
+ connection.change_property8(
+ PropMode::REPLACE,
+ window,
+ AtomEnum::WM_NAME,
+ AtomEnum::STRING,
+ b"Cua local confirmation",
+ )?;
+ set_window_metadata(
+ &connection,
+ window,
+ matches!(&request, HelperRequest::Indicator(_)),
+ )?;
+ let gc = connection.generate_id()?;
+ connection.create_gc(gc, window, &CreateGCAux::new())?;
+
+ let mut mode = match request {
+ HelperRequest::Consent(card) => SurfaceMode::Consent {
+ card,
+ interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
+ },
+ HelperRequest::Indicator(card) => SurfaceMode::Indicator {
+ card,
+ stop_pressed: false,
+ },
+ };
+ let mut local_pointer = Point { x: -1.0, y: -1.0 };
+ let mut outcome = None;
+ paint(&connection, window, depth, gc, &mode, local_pointer)?;
+ connection.map_window(window)?;
+ connection.configure_window(
+ window,
+ &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE),
+ )?;
+ let _ = connection.set_input_focus(InputFocus::PARENT, window, x11rb::CURRENT_TIME);
+ connection.flush()?;
+ let visibility_deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ if connection.get_window_attributes(window)?.reply()?.map_state == MapState::VIEWABLE {
+ break;
+ }
+ if Instant::now() >= visibility_deadline {
+ anyhow::bail!("the local confirmation window did not become viewable");
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ paint(&connection, window, depth, gc, &mode, local_pointer)?;
+ crate::protected_consent_event(&HelperEvent::Ready)?;
+
+ let shown = Instant::now();
+ let mut armed_redrawn = false;
+ loop {
+ while let Some(event) = connection.poll_for_event()? {
+ match event {
+ Event::MotionNotify(event) => {
+ local_pointer = Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ };
+ if let SurfaceMode::Consent { interaction, .. } = &mut mode {
+ interaction.pointer_moved(local_pointer, Instant::now());
+ }
+ paint(&connection, window, depth, gc, &mode, local_pointer)?;
+ }
+ Event::ButtonPress(event) if event.detail == 1 => match &mut mode {
+ SurfaceMode::Consent { interaction, .. } => {
+ interaction.pointer_down(
+ Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ },
+ overlay_ui::PointerButton::Primary,
+ Instant::now(),
+ );
+ }
+ SurfaceMode::Indicator { stop_pressed, .. } => {
+ *stop_pressed = STOP_RECT.contains(Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ });
+ }
+ },
+ Event::ButtonRelease(event) if event.detail == 1 => {
+ let point = Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ };
+ outcome = match &mut mode {
+ SurfaceMode::Consent { card, interaction } => {
+ let action = match interaction.pointer_up(point) {
+ InteractionOutcome::Accept => Some(HelperDecision::Accept),
+ InteractionOutcome::Decline => Some(HelperDecision::Decline),
+ _ => None,
+ };
+ action.map(|action| HelperEvent::Decision {
+ action,
+ request_digest: card.request_digest.clone(),
+ })
+ }
+ SurfaceMode::Indicator { card, stop_pressed } => {
+ let pressed = std::mem::take(stop_pressed);
+ (pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ })
+ }
+ };
+ }
+ // The canonical Xorg Escape keycode. Pointer decline remains
+ // available when a non-Xorg keymap uses another code.
+ Event::KeyPress(event) if event.detail == 9 => {
+ outcome = Some(fallback_outcome(&mode));
+ }
+ Event::DestroyNotify(_) => {
+ outcome = Some(fallback_outcome(&mode));
+ }
+ _ => {}
+ }
+ if outcome.is_some() {
+ break;
+ }
+ }
+ if outcome.is_some() {
+ break;
+ }
+ if !armed_redrawn && shown.elapsed() >= CONTROL_ARM_DELAY {
+ paint(&connection, window, depth, gc, &mode, local_pointer)?;
+ armed_redrawn = true;
+ }
+ if consent_expired(&mode) {
+ outcome = Some(fallback_outcome(&mode));
+ break;
+ }
+ match mode {
+ SurfaceMode::Indicator { .. } => {
+ // Persistent indicator is fully event-driven: zero repaint or
+ // timer wakeups while idle.
+ let event = connection.wait_for_event()?;
+ // Feed the blocking event through the same loop on the next
+ // iteration by handling it directly here.
+ match event {
+ Event::MotionNotify(event) => {
+ local_pointer = Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ };
+ paint(&connection, window, depth, gc, &mode, local_pointer)?;
+ }
+ Event::ButtonPress(event) if event.detail == 1 => {
+ if let SurfaceMode::Indicator { stop_pressed, .. } = &mut mode {
+ *stop_pressed = STOP_RECT.contains(Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ });
+ }
+ }
+ Event::ButtonRelease(event) if event.detail == 1 => {
+ if let SurfaceMode::Indicator { card, stop_pressed } = &mut mode {
+ let point = Point {
+ x: event.event_x as f64,
+ y: event.event_y as f64,
+ };
+ if std::mem::take(stop_pressed) && STOP_RECT.contains(point) {
+ outcome = Some(HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ });
+ }
+ }
+ }
+ Event::DestroyNotify(_) => outcome = Some(fallback_outcome(&mode)),
+ _ => {}
+ }
+ }
+ SurfaceMode::Consent { .. } => std::thread::sleep(Duration::from_millis(25)),
+ }
+ }
+ connection.destroy_window(window).ok();
+ connection.flush().ok();
+ crate::protected_consent_event(&outcome.unwrap_or_else(|| fallback_outcome(&mode)))?;
+ Ok(())
+}
+
+fn set_window_metadata(
+ connection: &impl Connection,
+ window: u32,
+ indicator: bool,
+) -> anyhow::Result<()> {
+ let atom = |name: &str| -> anyhow::Result<u32> {
+ Ok(connection
+ .intern_atom(false, name.as_bytes())?
+ .reply()?
+ .atom)
+ };
+ let wm_class = atom("WM_CLASS")?;
+ connection.change_property8(
+ PropMode::REPLACE,
+ window,
+ wm_class,
+ AtomEnum::STRING,
+ b"cua-driver\0CuaDriver\0",
+ )?;
+
+ let cardinal = AtomEnum::CARDINAL;
+ connection.change_property32(
+ PropMode::REPLACE,
+ window,
+ atom("_NET_WM_PID")?,
+ cardinal,
+ &[std::process::id()],
+ )?;
+
+ let window_type = atom("_NET_WM_WINDOW_TYPE")?;
+ let concrete_type = atom(if indicator {
+ "_NET_WM_WINDOW_TYPE_NOTIFICATION"
+ } else {
+ "_NET_WM_WINDOW_TYPE_DIALOG"
+ })?;
+ connection.change_property32(
+ PropMode::REPLACE,
+ window,
+ window_type,
+ AtomEnum::ATOM,
+ &[concrete_type],
+ )?;
+
+ let state = atom("_NET_WM_STATE")?;
+ let states = [
+ atom("_NET_WM_STATE_ABOVE")?,
+ atom("_NET_WM_STATE_STICKY")?,
+ atom("_NET_WM_STATE_SKIP_TASKBAR")?,
+ atom("_NET_WM_STATE_SKIP_PAGER")?,
+ ];
+ connection.change_property32(PropMode::REPLACE, window, state, AtomEnum::ATOM, &states)?;
+ Ok(())
+}
+
+fn find_argb_visual(screen: &x11rb::protocol::xproto::Screen) -> Option<(u32, u8, u32)> {
+ for entry in &screen.allowed_depths {
+ if entry.depth != 32 {
+ continue;
+ }
+ for visual in &entry.visuals {
+ if visual.class == VisualClass::TRUE_COLOR {
+ return Some((visual.visual_id, 32, screen.default_colormap));
+ }
+ }
+ }
+ None
+}
+
+fn paint(
+ connection: &impl Connection,
+ window: u32,
+ depth: u8,
+ gc: u32,
+ mode: &SurfaceMode,
+ pointer: Point,
+) -> anyhow::Result<()> {
+ let pixmap = match mode {
+ SurfaceMode::Consent { card, interaction } => render_consent(
+ card,
+ 1.0,
+ ConsentVisualState {
+ accept_armed: interaction.accept_armed(Instant::now()),
+ accept_hovered: ACCEPT_RECT.contains(pointer),
+ decline_hovered: DECLINE_RECT.contains(pointer),
+ },
+ )?,
+ SurfaceMode::Indicator { card, .. } => {
+ render_indicator(card, 1.0, STOP_RECT.contains(pointer))?
+ }
+ };
+ let mut bgra = Vec::with_capacity(pixmap.data().len());
+ let mut shape = Vec::new();
+ for (y, row) in pixmap
+ .data()
+ .chunks_exact((pixmap.width() * 4) as usize)
+ .enumerate()
+ {
+ let mut run = None;
+ for (x, pixel) in row.chunks_exact(4).enumerate() {
+ bgra.extend_from_slice(&[pixel[2], pixel[1], pixel[0], pixel[3]]);
+ if pixel[3] != 0 {
+ run.get_or_insert(x);
+ } else if let Some(start) = run.take() {
+ shape.push(Rectangle {
+ x: start as i16,
+ y: y as i16,
+ width: (x - start) as u16,
+ height: 1,
+ });
+ }
+ }
+ if let Some(start) = run {
+ shape.push(Rectangle {
+ x: start as i16,
+ y: y as i16,
+ width: pixmap.width() as u16 - start as u16,
+ height: 1,
+ });
+ }
+ }
+ connection.shape_rectangles(
+ SO::SET,
+ SK::BOUNDING,
+ ClipOrdering::UNSORTED,
+ window,
+ 0,
+ 0,
+ &shape,
+ )?;
+ connection.put_image(
+ ImageFormat::Z_PIXMAP,
+ window,
+ gc,
+ pixmap.width() as u16,
+ pixmap.height() as u16,
+ 0,
+ 0,
+ 0,
+ depth,
+ &bgra,
+ )?;
+ connection.flush()?;
+ Ok(())
+}
+
+fn consent_expired(mode: &SurfaceMode) -> bool {
+ let SurfaceMode::Consent { card, .. } = mode else {
+ return false;
+ };
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or(Duration::ZERO)
+ .as_millis();
+ now >= u128::from(card.expires_unix_ms)
+}
+
+fn fallback_outcome(mode: &SurfaceMode) -> HelperEvent {
+ match mode {
+ SurfaceMode::Consent { card, .. } => HelperEvent::Decision {
+ action: HelperDecision::Cancel,
+ request_digest: card.request_digest.clone(),
+ },
+ SurfaceMode::Indicator { card, .. } => HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ },
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index 08526ab3f4..3a295c57db 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -4372,6 +4372,7 @@ impl Tool for DragTool {
to_x.round() as i32,
to_y.round() as i32,
steps as u32,
+ duration_ms,
button,
)
} else {
@@ -4535,7 +4536,7 @@ impl Tool for DragTool {
(to_x.round() as i32, to_y.round() as i32),
));
tokio::task::spawn_blocking(move || {
- crate::wayland::drag(xid, fxi, fyi, txi, tyi, steps_u32, button)
+ crate::wayland::drag(xid, fxi, fyi, txi, tyi, steps_u32, duration_ms, button)
})
.await
};
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
index ff024108cf..a2691a0c3c 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs
@@ -137,6 +137,7 @@ enum Cmd {
to_x: f64,
to_y: f64,
steps: u32,
+ duration_ms: u64,
button: Button,
reply: Sender<anyhow::Result<()>>,
},
@@ -376,6 +377,7 @@ pub fn drag(
to_x: f64,
to_y: f64,
steps: u32,
+ duration_ms: u64,
button: Button,
) -> anyhow::Result<()> {
ensure_started()?;
@@ -387,6 +389,7 @@ pub fn drag(
to_x,
to_y,
steps,
+ duration_ms,
button,
reply: tx_r,
})
@@ -998,6 +1001,7 @@ impl EisState {
to_x,
to_y,
steps,
+ duration_ms,
button,
..
} => {
@@ -1024,16 +1028,26 @@ impl EisState {
device.frame(serial, event_time_us());
btn.button(button.to_evdev(), reis::ei::button::ButtonState::Press);
device.frame(serial, event_time_us());
+ if let Some(context) = self.context.as_ref() {
+ let _ = context.flush();
+ }
// Bound the interpolation: run_command executes synchronously in
// the worker loop, so a huge step count would block EIS event
// processing (incl. Ping) and balloon the unflushed request queue.
let n = (*steps).max(1).min(500);
+ let delay = drag_step_delay(*duration_ms, n);
for s in 1..=n {
let t = s as f32 / n as f32;
let ix = from_rx + (to_rx - from_rx) * t;
let iy = from_ry + (to_ry - from_ry) * t;
ptr_abs.motion_absolute(ix, iy);
device.frame(serial, event_time_us());
+ if let Some(context) = self.context.as_ref() {
+ let _ = context.flush();
+ }
+ if !delay.is_zero() {
+ std::thread::sleep(delay);
+ }
}
btn.button(button.to_evdev(), reis::ei::button::ButtonState::Released);
device.frame(serial, event_time_us());
@@ -1338,6 +1352,17 @@ fn device_interface<T: reis::Interface>(
.downcast()
}
+fn drag_step_delay(duration_ms: u64, steps: u32) -> std::time::Duration {
+ let frames = u64::from(steps.max(1).min(500));
+ std::time::Duration::from_micros(
+ duration_ms
+ .min(10_000)
+ .saturating_mul(1_000)
+ .checked_div(frames)
+ .unwrap_or(0),
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1361,6 +1386,14 @@ mod tests {
);
}
+ #[test]
+ fn drag_duration_is_distributed_across_motion_frames() {
+ let delay = drag_step_delay(500, 30);
+ assert_eq!(delay, std::time::Duration::from_micros(16_666));
+ assert!(delay.saturating_mul(30) <= std::time::Duration::from_millis(500));
+ assert_eq!(drag_step_delay(0, 30), std::time::Duration::from_millis(0));
+ }
+
#[test]
fn key_sequence_preserves_transition_order_and_assigns_frames() {
let transitions = [
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
index 2383a1f3b2..3747af3608 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs
@@ -1564,6 +1564,7 @@ pub fn drag(
to_x: i32,
to_y: i32,
steps: u32,
+ duration_ms: u64,
button: u8,
) -> anyhow::Result<()> {
with_libei_fallback(
@@ -1571,7 +1572,7 @@ pub fn drag(
|| {
libei_wait_pointer_ready()?;
activate_window_for_input(window_id)?;
- libei_drag(from_x, from_y, to_x, to_y, steps, button)
+ libei_drag(from_x, from_y, to_x, to_y, steps, duration_ms, button)
},
)
}
@@ -1583,13 +1584,14 @@ pub fn drag_desktop(
to_x: i32,
to_y: i32,
steps: u32,
+ duration_ms: u64,
button: u8,
) -> anyhow::Result<()> {
with_libei_fallback(
|| drag_vptr(None, from_x, from_y, to_x, to_y, steps, button),
|| {
libei_wait_pointer_ready()?;
- libei_drag(from_x, from_y, to_x, to_y, steps, button)
+ libei_drag(from_x, from_y, to_x, to_y, steps, duration_ms, button)
},
)
}
@@ -2009,6 +2011,7 @@ fn libei_drag(
_to_x: i32,
_to_y: i32,
_steps: u32,
+ _duration_ms: u64,
_button: u8,
) -> anyhow::Result<()> {
unreachable!("libei fallback compiled out (no portal-input feature)")
@@ -2099,6 +2102,7 @@ fn libei_drag(
to_x: i32,
to_y: i32,
steps: u32,
+ duration_ms: u64,
button: u8,
) -> anyhow::Result<()> {
// ei_button exposes separate Press/Released states, so the libei worker can
@@ -2117,6 +2121,7 @@ fn libei_drag(
cx(to_x) as f64,
cy(to_y) as f64,
steps,
+ duration_ms,
btn,
)?;
record_synth_cursor(cx(to_x), cy(to_y));
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 0185d390d6..154177245b 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
@@ -283,14 +283,20 @@ fn wait_timeout(mut child: std::process::Child, dur: Duration) -> Option<std::pr
})
}
-/// Screen origin of the Wayland surface buffer backing `pid`.
+/// Screen origin of the compositor frame backing `pid`.
///
-/// GTK's AT-SPI `CoordType::Window` includes client-side shadow extents, while
-/// Mutter's frame rectangle excludes them. The buffer origin preserves those
-/// extents so accessibility frames line up with pixels. Older helpers omit the
-/// buffer fields and fall back to the frame origin.
+/// `screenshot_window_dispatch` crops the Shell stage to this same frame
+/// rectangle, and GTK's AT-SPI `CoordType::Window` coordinates are relative to
+/// that frame. Using Mutter's larger surface-buffer rectangle here shifts
+/// elements up and left by the client-side shadow extents whenever the window
+/// is floating, so pixel actions derived from the returned screenshot miss
+/// their target.
pub fn window_origin_for_pid(pid: u32) -> Option<(i32, i32)> {
let raw = gdbus_call("GetRects", &[])?;
+ parse_window_origin(&raw, pid)
+}
+
+fn parse_window_origin(raw: &str, pid: u32) -> Option<(i32, i32)> {
// gdbus prints a GVariant tuple like `('[{"pid":..,"x":..}]',)`. Pull the
// JSON array out robustly (first '[' .. last ']') rather than parsing the
// GVariant wrapper, so an apostrophe in a window title can't break it.
@@ -300,16 +306,8 @@ pub fn window_origin_for_pid(pid: u32) -> Option<(i32, i32)> {
let arr: Vec<serde_json::Value> = serde_json::from_str(json).ok()?;
for w in &arr {
if w.get("pid").and_then(|p| p.as_u64()) == Some(pid as u64) {
- let x = w
- .get("buffer_x")
- .and_then(serde_json::Value::as_i64)
- .or_else(|| w.get("x").and_then(serde_json::Value::as_i64))?
- as i32;
- let y = w
- .get("buffer_y")
- .and_then(serde_json::Value::as_i64)
- .or_else(|| w.get("y").and_then(serde_json::Value::as_i64))?
- as i32;
+ let x = w.get("x").and_then(serde_json::Value::as_i64)? as i32;
+ let y = w.get("y").and_then(serde_json::Value::as_i64)? as i32;
return Some((x, y));
}
}
@@ -548,6 +546,13 @@ mod tests {
assert_eq!(windows[0].z_index, Some(2));
}
+ #[test]
+ fn accessibility_origin_matches_the_frame_cropped_screenshot() {
+ let raw = r#"('[{"id":46,"pid":6079,"title":"Floating GTK","x":14,"y":12,"w":560,"h":736,"buffer_x":0,"buffer_y":0}]',)"#;
+
+ assert_eq!(parse_window_origin(raw, 6079), Some((14, 12)));
+ }
+
#[test]
fn marks_minimized_shell_windows_off_screen() {
let raw = r#"('[{"id":47,"pid":6080,"title":"Hidden","x":0,"y":0,"w":100,"h":100,"minimized":true,"visible":false,"stacking":1}]',)"#;
diff --git a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
index 629a4f5408..f891fc58cb 100644
--- a/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-macos/Cargo.toml
@@ -21,6 +21,7 @@ indexmap = "2"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
+overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
index 196077bd9e..1899dee425 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/lib.rs
@@ -27,6 +27,8 @@ pub mod permissions;
#[cfg(target_os = "macos")]
pub mod pip;
#[cfg(target_os = "macos")]
+pub mod protected_consent;
+#[cfg(target_os = "macos")]
pub mod recording_hooks;
#[cfg(target_os = "macos")]
pub mod session;
@@ -43,6 +45,15 @@ pub mod windows;
use cua_driver_core::tool::ToolRegistry;
+#[cfg(target_os = "macos")]
+pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
+ let mut stdout = std::io::stdout().lock();
+ serde_json::to_writer(&mut stdout, event)?;
+ std::io::Write::write_all(&mut stdout, b"\n")?;
+ std::io::Write::flush(&mut stdout)?;
+ Ok(())
+}
+
/// Register all macOS tools. For programs that don't restructure `main`
/// (e.g. test harnesses), the overlay is skipped.
pub fn register_tools() -> ToolRegistry {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs
new file mode 100644
index 0000000000..b9499f4e4a
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/protected_consent.rs
@@ -0,0 +1,506 @@
+//! Capture-excluded, automation-hidden protected consent surface for macOS.
+
+use std::cell::RefCell;
+use std::ffi::c_void;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use objc2::runtime::{AnyClass, AnyObject};
+use objc2::{class, msg_send};
+use objc2_foundation::{MainThreadMarker, NSPoint, NSRect, NSSize};
+use overlay_ui::{
+ place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
+ ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
+ Rect, ACCEPT_RECT, CONSENT_SIZE, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
+};
+
+thread_local! {
+ static CONTEXT: RefCell<Option<SurfaceContext>> = const { RefCell::new(None) };
+ static OUTCOME: RefCell<Option<HelperEvent>> = const { RefCell::new(None) };
+}
+
+struct SurfaceContext {
+ mode: SurfaceMode,
+ layer: usize,
+ scale: f32,
+ pointer: Point,
+}
+
+enum SurfaceMode {
+ Consent {
+ card: overlay_ui::ConsentCard,
+ interaction: ConsentInteraction,
+ },
+ Indicator {
+ card: overlay_ui::IndicatorCard,
+ stop_pressed: bool,
+ },
+}
+
+pub fn run(request: HelperRequest) -> anyhow::Result<()> {
+ MainThreadMarker::new()
+ .ok_or_else(|| anyhow::anyhow!("protected UI must run on main thread"))?;
+ unsafe { run_appkit(request) }
+}
+
+unsafe fn run_appkit(request: HelperRequest) -> anyhow::Result<()> {
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let _: bool = msg_send![app, setActivationPolicy: 1i64];
+ let _: () = msg_send![app, finishLaunching];
+
+ let mouse: NSPoint = msg_send![class!(NSEvent), mouseLocation];
+ let screen = screen_for_point(mouse);
+ if screen.is_null() {
+ anyhow::bail!("no interactive NSScreen is available");
+ }
+ let visible: NSRect = msg_send![screen, visibleFrame];
+ let scale = {
+ let value: f64 = msg_send![screen, backingScaleFactor];
+ if value > 0.0 {
+ value as f32
+ } else {
+ 1.0
+ }
+ };
+ let logical_size = match &request {
+ HelperRequest::Consent(_) => CONSENT_SIZE,
+ HelperRequest::Indicator(_) => INDICATOR_SIZE,
+ };
+ let work_area = Rect {
+ x: 0.0,
+ y: 0.0,
+ width: visible.size.width,
+ height: visible.size.height,
+ };
+ if !surface_fits(work_area, logical_size) {
+ anyhow::bail!("the active display work area is too small for the local confirmation");
+ }
+ let pointer = Point {
+ x: mouse.x - visible.origin.x,
+ y: visible.origin.y + visible.size.height - mouse.y,
+ };
+ let top_left = match &request {
+ HelperRequest::Consent(_) => place_near_pointer(pointer, work_area, logical_size),
+ HelperRequest::Indicator(_) => Point {
+ x: (visible.size.width - logical_size.width - 18.0).max(18.0),
+ y: 18.0,
+ },
+ };
+ let frame = NSRect {
+ origin: NSPoint {
+ x: visible.origin.x + top_left.x,
+ y: visible.origin.y + visible.size.height - top_left.y - logical_size.height,
+ },
+ size: NSSize {
+ width: logical_size.width,
+ height: logical_size.height,
+ },
+ };
+
+ let allocated: *mut AnyObject = msg_send![class!(NSWindow), alloc];
+ let window: *mut AnyObject = msg_send![allocated,
+ initWithContentRect: frame
+ styleMask: 0u64
+ backing: 2u64
+ defer: false
+ ];
+ if window.is_null() {
+ anyhow::bail!("could not create protected NSWindow");
+ }
+ let _: () = msg_send![window, setOpaque: false];
+ let clear: *mut AnyObject = msg_send![class!(NSColor), clearColor];
+ let _: () = msg_send![window, setBackgroundColor: clear];
+ let _: () = msg_send![window, setHasShadow: false];
+ let _: () = msg_send![window, setIgnoresMouseEvents: false];
+ // NSWindowSharingNone: omit the protected pixels from capture APIs.
+ let _: () = msg_send![window, setSharingType: 0u64];
+ // NSStatusWindowLevel: above ordinary app and agent overlay windows.
+ let _: () = msg_send![window, setLevel: 25i64];
+ let _: () = msg_send![window, setCollectionBehavior: (1u64 | (1 << 8) | (1 << 4))];
+ let _: () = msg_send![window, setReleasedWhenClosed: false];
+ let _: () = msg_send![window, setHidesOnDeactivate: false];
+ let _: () = msg_send![window, setAcceptsMouseMovedEvents: true];
+
+ let view: *mut AnyObject = msg_send![protected_view_class(), alloc];
+ let bounds = NSRect {
+ origin: NSPoint { x: 0.0, y: 0.0 },
+ size: frame.size,
+ };
+ let view: *mut AnyObject = msg_send![view, initWithFrame: bounds];
+ // `setAcceptsMouseMovedEvents:` only tells the window not to discard
+ // movement events; AppKit still needs a tracking area to route them to a
+ // custom NSView. Without this, the post-arm entry required by
+ // `ConsentInteraction` can never happen and Allow once stays disabled.
+ let tracking_area: *mut AnyObject = msg_send![class!(NSTrackingArea), alloc];
+ let tracking_area: *mut AnyObject = msg_send![tracking_area,
+ initWithRect: bounds
+ options: (0x01u64 | 0x02u64 | 0x80u64 | 0x200u64)
+ owner: view
+ userInfo: std::ptr::null::<AnyObject>()
+ ];
+ if tracking_area.is_null() {
+ anyhow::bail!("could not create protected consent tracking area");
+ }
+ let _: () = msg_send![view, addTrackingArea: tracking_area];
+ let _: () = msg_send![view, setWantsLayer: true];
+ let _: () = msg_send![view, setAccessibilityElement: false];
+ let _: () = msg_send![window, setContentView: view];
+ let _: () = msg_send![window, makeFirstResponder: view];
+ let layer: *mut AnyObject = msg_send![view, layer];
+ let _: () = msg_send![layer, setContentsScale: scale as f64];
+
+ let context = match request {
+ HelperRequest::Consent(card) => SurfaceContext {
+ mode: SurfaceMode::Consent {
+ card,
+ interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
+ },
+ layer: layer as usize,
+ scale,
+ pointer: Point { x: -1.0, y: -1.0 },
+ },
+ HelperRequest::Indicator(card) => SurfaceContext {
+ mode: SurfaceMode::Indicator {
+ card,
+ stop_pressed: false,
+ },
+ layer: layer as usize,
+ scale,
+ pointer: Point { x: -1.0, y: -1.0 },
+ },
+ };
+ CONTEXT.with(|slot| *slot.borrow_mut() = Some(context));
+ redraw();
+
+ let _: () = msg_send![window, makeKeyAndOrderFront: std::ptr::null::<AnyObject>()];
+ let _: () = msg_send![app, activateIgnoringOtherApps: true];
+ let _: () = msg_send![window, display];
+ let visible_now: bool = msg_send![window, isVisible];
+ if !visible_now {
+ anyhow::bail!("the local confirmation window did not become visible");
+ }
+ if matches!(
+ CONTEXT.with(|slot| slot
+ .borrow()
+ .as_ref()
+ .map(|ctx| matches!(ctx.mode, SurfaceMode::Consent { .. }))),
+ Some(true)
+ ) {
+ schedule_expiry_timer();
+ }
+ crate::protected_consent_event(&HelperEvent::Ready)?;
+ let _: i64 = msg_send![app, runModalForWindow: window];
+ let _: () = msg_send![window, orderOut: std::ptr::null::<AnyObject>()];
+
+ let outcome = OUTCOME
+ .with(|slot| slot.borrow_mut().take())
+ .unwrap_or_else(|| fallback_outcome());
+ crate::protected_consent_event(&outcome)?;
+ Ok(())
+}
+
+unsafe fn screen_for_point(point: NSPoint) -> *mut AnyObject {
+ let screens: *mut AnyObject = msg_send![class!(NSScreen), screens];
+ let count: usize = msg_send![screens, count];
+ for index in 0..count {
+ let screen: *mut AnyObject = msg_send![screens, objectAtIndex: index];
+ let frame: NSRect = msg_send![screen, frame];
+ if point.x >= frame.origin.x
+ && point.x <= frame.origin.x + frame.size.width
+ && point.y >= frame.origin.y
+ && point.y <= frame.origin.y + frame.size.height
+ {
+ return screen;
+ }
+ }
+ msg_send![class!(NSScreen), mainScreen]
+}
+
+fn protected_view_class() -> &'static AnyClass {
+ use objc2::declare::ClassBuilder;
+ use std::sync::OnceLock;
+ static CLASS: OnceLock<&'static AnyClass> = OnceLock::new();
+ CLASS.get_or_init(|| {
+ let mut builder = ClassBuilder::new("CuaProtectedConsentView", class!(NSView))
+ .expect("CuaProtectedConsentView already registered");
+ unsafe {
+ builder.add_method(
+ objc2::sel!(acceptsFirstResponder),
+ accepts_first_responder as extern "C" fn(_, _) -> objc2::runtime::Bool,
+ );
+ builder.add_method(
+ objc2::sel!(mouseMoved:),
+ mouse_moved as extern "C" fn(_, _, _),
+ );
+ builder.add_method(
+ objc2::sel!(mouseEntered:),
+ mouse_moved as extern "C" fn(_, _, _),
+ );
+ builder.add_method(
+ objc2::sel!(mouseDown:),
+ mouse_down as extern "C" fn(_, _, _),
+ );
+ builder.add_method(objc2::sel!(mouseUp:), mouse_up as extern "C" fn(_, _, _));
+ builder.add_method(objc2::sel!(keyDown:), key_down as extern "C" fn(_, _, _));
+ builder.add_method(
+ objc2::sel!(expiryTick:),
+ expiry_tick as extern "C" fn(_, _, _),
+ );
+ }
+ builder.register()
+ })
+}
+
+extern "C" fn accepts_first_responder(
+ _this: *mut AnyObject,
+ _cmd: objc2::runtime::Sel,
+) -> objc2::runtime::Bool {
+ objc2::runtime::Bool::YES
+}
+
+extern "C" fn mouse_moved(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
+ let point = event_point(event);
+ CONTEXT.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ let Some(context) = slot.as_mut() else { return };
+ context.pointer = point;
+ if let SurfaceMode::Consent { interaction, .. } = &mut context.mode {
+ interaction.pointer_moved(point, Instant::now());
+ }
+ });
+ unsafe { redraw() };
+}
+
+extern "C" fn mouse_down(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
+ let point = event_point(event);
+ CONTEXT.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ let Some(context) = slot.as_mut() else { return };
+ context.pointer = point;
+ match &mut context.mode {
+ SurfaceMode::Consent { interaction, .. } => {
+ interaction.pointer_down(point, overlay_ui::PointerButton::Primary, Instant::now());
+ }
+ SurfaceMode::Indicator { stop_pressed, .. } => {
+ *stop_pressed = STOP_RECT.contains(point);
+ }
+ }
+ });
+}
+
+extern "C" fn mouse_up(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
+ let point = event_point(event);
+ let outcome = CONTEXT.with(|slot| {
+ let mut slot = slot.borrow_mut();
+ let Some(context) = slot.as_mut() else {
+ return None;
+ };
+ match &mut context.mode {
+ SurfaceMode::Consent { card, interaction } => {
+ let action = match interaction.pointer_up(point) {
+ InteractionOutcome::Accept => Some(HelperDecision::Accept),
+ InteractionOutcome::Decline => Some(HelperDecision::Decline),
+ _ => None,
+ }?;
+ Some(HelperEvent::Decision {
+ action,
+ request_digest: card.request_digest.clone(),
+ })
+ }
+ SurfaceMode::Indicator { card, stop_pressed } => {
+ let was_pressed = std::mem::take(stop_pressed);
+ (was_pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ })
+ }
+ }
+ });
+ if let Some(outcome) = outcome {
+ finish(outcome);
+ }
+}
+
+extern "C" fn key_down(_this: *mut AnyObject, _cmd: objc2::runtime::Sel, event: *mut AnyObject) {
+ let key_code: u16 = unsafe { msg_send![event, keyCode] };
+ if key_code == 53 {
+ finish(fallback_outcome());
+ }
+}
+
+extern "C" fn expiry_tick(
+ _this: *mut AnyObject,
+ _cmd: objc2::runtime::Sel,
+ _timer: *mut AnyObject,
+) {
+ finish(fallback_outcome());
+}
+
+fn event_point(event: *mut AnyObject) -> Point {
+ let point: NSPoint = unsafe { msg_send![event, locationInWindow] };
+ let height = CONTEXT.with(|slot| {
+ slot.borrow()
+ .as_ref()
+ .map(|context| match context.mode {
+ SurfaceMode::Consent { .. } => CONSENT_SIZE.height,
+ SurfaceMode::Indicator { .. } => INDICATOR_SIZE.height,
+ })
+ .unwrap_or(0.0)
+ });
+ Point {
+ x: point.x,
+ y: height - point.y,
+ }
+}
+
+fn fallback_outcome() -> HelperEvent {
+ CONTEXT.with(
+ |slot| match slot.borrow().as_ref().map(|context| &context.mode) {
+ Some(SurfaceMode::Consent { card, .. }) => HelperEvent::Decision {
+ action: HelperDecision::Cancel,
+ request_digest: card.request_digest.clone(),
+ },
+ Some(SurfaceMode::Indicator { card, .. }) => HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ },
+ None => HelperEvent::Failed {
+ reason: "protected surface closed without context".to_owned(),
+ },
+ },
+ )
+}
+
+fn finish(outcome: HelperEvent) {
+ OUTCOME.with(|slot| *slot.borrow_mut() = Some(outcome));
+ unsafe {
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ let _: () = msg_send![app, stopModal];
+ }
+}
+
+unsafe fn redraw() {
+ CONTEXT.with(|slot| {
+ let slot = slot.borrow();
+ let Some(context) = slot.as_ref() else { return };
+ let pixmap = match &context.mode {
+ SurfaceMode::Consent { card, interaction } => render_consent(
+ card,
+ context.scale,
+ ConsentVisualState {
+ accept_armed: interaction.accept_armed(Instant::now()),
+ accept_hovered: ACCEPT_RECT.contains(context.pointer),
+ decline_hovered: DECLINE_RECT.contains(context.pointer),
+ },
+ ),
+ SurfaceMode::Indicator { card, .. } => {
+ render_indicator(card, context.scale, STOP_RECT.contains(context.pointer))
+ }
+ };
+ let Ok(pixmap) = pixmap else { return };
+ let Some(image) = pixmap_to_cgimage(&pixmap) else {
+ return;
+ };
+ let layer = context.layer as *mut AnyObject;
+ let _: () = msg_send![layer, setContents: image as *mut AnyObject];
+ CGImageRelease(image as *mut c_void);
+ });
+}
+
+unsafe fn schedule_expiry_timer() {
+ let delay = CONTEXT.with(|slot| {
+ slot.borrow()
+ .as_ref()
+ .and_then(|context| match &context.mode {
+ SurfaceMode::Consent { card, .. } => Some(card.expires_unix_ms),
+ _ => None,
+ })
+ .map(|expires| {
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or(Duration::ZERO)
+ .as_millis();
+ u128::from(expires).saturating_sub(now) as f64 / 1000.0
+ })
+ .unwrap_or(0.1)
+ .max(0.1)
+ });
+ let target: *mut AnyObject = msg_send![protected_view_class(), alloc];
+ let target: *mut AnyObject = msg_send![target, init];
+ let timer: *mut AnyObject = msg_send![class!(NSTimer),
+ timerWithTimeInterval: delay
+ target: target
+ selector: objc2::sel!(expiryTick:)
+ userInfo: std::ptr::null::<AnyObject>()
+ repeats: false
+ ];
+ let run_loop: *mut AnyObject = msg_send![class!(NSRunLoop), currentRunLoop];
+ let mode = ns_string("NSModalPanelRunLoopMode");
+ let _: () = msg_send![run_loop, addTimer: timer forMode: mode];
+}
+
+unsafe fn ns_string(text: &str) -> *mut AnyObject {
+ let text = std::ffi::CString::new(text).unwrap_or_default();
+ msg_send![class!(NSString), stringWithUTF8String: text.as_ptr() as *const c_void]
+}
+
+fn pixmap_to_cgimage(pixmap: &tiny_skia::Pixmap) -> Option<usize> {
+ let width = pixmap.width() as usize;
+ let height = pixmap.height() as usize;
+ if width == 0 || height == 0 {
+ return None;
+ }
+ unsafe extern "C" fn release_data(info: *mut c_void, _data: *const c_void, _size: usize) {
+ drop(Box::from_raw(info as *mut Vec<u8>));
+ }
+ unsafe {
+ extern "C" {
+ fn CGColorSpaceCreateDeviceRGB() -> *mut c_void;
+ fn CGColorSpaceRelease(space: *mut c_void);
+ fn CGDataProviderCreateWithData(
+ info: *mut c_void,
+ data: *const c_void,
+ size: usize,
+ release: Option<unsafe extern "C" fn(*mut c_void, *const c_void, usize)>,
+ ) -> *mut c_void;
+ fn CGDataProviderRelease(provider: *mut c_void);
+ fn CGImageCreate(
+ width: usize,
+ height: usize,
+ bits_per_component: usize,
+ bits_per_pixel: usize,
+ bytes_per_row: usize,
+ color_space: *mut c_void,
+ bitmap_info: u32,
+ provider: *mut c_void,
+ decode: *const f64,
+ should_interpolate: bool,
+ intent: u32,
+ ) -> *mut c_void;
+ }
+ let data = Box::new(pixmap.data().to_vec());
+ let ptr = data.as_ptr();
+ let len = data.len();
+ let info = Box::into_raw(data);
+ let color_space = CGColorSpaceCreateDeviceRGB();
+ let provider =
+ CGDataProviderCreateWithData(info.cast(), ptr.cast(), len, Some(release_data));
+ let image = CGImageCreate(
+ width,
+ height,
+ 8,
+ 32,
+ width * 4,
+ color_space,
+ 0x4001,
+ provider,
+ std::ptr::null(),
+ false,
+ 0,
+ );
+ CGColorSpaceRelease(color_space);
+ CGDataProviderRelease(provider);
+ (!image.is_null()).then_some(image as usize)
+ }
+}
+
+extern "C" {
+ fn CGImageRelease(image: *mut c_void);
+}
diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
index b85ff0cbcb..f8be223ec5 100644
--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml
@@ -14,6 +14,7 @@ async-trait = "0.1"
cua-driver-core = { path = "../cua-driver-core" }
cua-driver-contract = { path = "../cua-driver-contract" }
cursor-overlay = { path = "../cursor-overlay" }
+overlay-ui = { path = "../overlay-ui" }
pip-preview = { path = "../pip-preview" }
# IndexMap gives the keyed cursor render collection deterministic
# insertion-ordered iteration = stable per-session cursor z-order frame to
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
index 98fc222269..f70f9eaa69 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
@@ -18,10 +18,21 @@
use cua_driver_core::tool::ToolRegistry;
+#[cfg(target_os = "windows")]
+pub fn protected_consent_event(event: &overlay_ui::HelperEvent) -> anyhow::Result<()> {
+ let mut stdout = std::io::stdout().lock();
+ serde_json::to_writer(&mut stdout, event)?;
+ std::io::Write::write_all(&mut stdout, b"\n")?;
+ std::io::Write::flush(&mut stdout)?;
+ Ok(())
+}
+
pub mod diagnostics;
pub mod health_report;
pub mod overlay;
pub mod pip;
+#[cfg(target_os = "windows")]
+pub mod protected_consent;
pub mod recording_hooks;
pub mod terminal;
pub mod tools;
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs b/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs
new file mode 100644
index 0000000000..72e7d11817
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-windows/src/protected_consent.rs
@@ -0,0 +1,408 @@
+//! Capture-excluded, automation-hidden protected consent surface for Windows.
+
+use std::sync::Mutex;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use overlay_ui::{
+ place_near_pointer, render_consent, render_indicator, surface_fits, ConsentInteraction,
+ ConsentVisualState, HelperDecision, HelperEvent, HelperRequest, InteractionOutcome, Point,
+ Rect, ACCEPT_RECT, CONSENT_SIZE, CONTROL_ARM_DELAY, DECLINE_RECT, INDICATOR_SIZE, STOP_RECT,
+};
+use windows::core::PCWSTR;
+use windows::Win32::Foundation::*;
+use windows::Win32::Graphics::Gdi::*;
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::System::RemoteDesktop::ProcessIdToSessionId;
+use windows::Win32::System::Threading::GetCurrentProcessId;
+use windows::Win32::UI::HiDpi::GetDpiForSystem;
+use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
+use windows::Win32::UI::WindowsAndMessaging::*;
+
+static CONTEXT: Mutex<Option<SurfaceContext>> = Mutex::new(None);
+
+struct SurfaceContext {
+ mode: SurfaceMode,
+ hwnd: HWND,
+ scale: f32,
+ pointer: Point,
+ outcome: Option<HelperEvent>,
+}
+
+// The HWND is accessed only by the message-loop thread.
+unsafe impl Send for SurfaceContext {}
+
+enum SurfaceMode {
+ Consent {
+ card: overlay_ui::ConsentCard,
+ interaction: ConsentInteraction,
+ },
+ Indicator {
+ card: overlay_ui::IndicatorCard,
+ stop_pressed: bool,
+ },
+}
+
+pub fn interactive_surface_available() -> bool {
+ let mut session = 0u32;
+ unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session).is_ok() && session != 0 }
+}
+
+pub fn run(request: HelperRequest) -> anyhow::Result<()> {
+ if !interactive_surface_available() {
+ anyhow::bail!("protected Windows UI requires an interactive non-session-0 desktop");
+ }
+ unsafe { run_win32(request) }
+}
+
+unsafe fn run_win32(request: HelperRequest) -> anyhow::Result<()> {
+ let dpi = GetDpiForSystem().max(96);
+ let scale = dpi as f32 / 96.0;
+ let logical_size = match &request {
+ HelperRequest::Consent(_) => CONSENT_SIZE,
+ HelperRequest::Indicator(_) => INDICATOR_SIZE,
+ };
+ let mut cursor = POINT::default();
+ GetCursorPos(&mut cursor)?;
+ let monitor = MonitorFromPoint(cursor, MONITOR_DEFAULTTONEAREST);
+ let mut info = MONITORINFO {
+ cbSize: std::mem::size_of::<MONITORINFO>() as u32,
+ ..Default::default()
+ };
+ GetMonitorInfoW(monitor, &mut info).ok()?;
+ let work = info.rcWork;
+ let work_rect = Rect {
+ x: work.left as f64,
+ y: work.top as f64,
+ width: (work.right - work.left) as f64,
+ height: (work.bottom - work.top) as f64,
+ };
+ let physical_size = overlay_ui::Size {
+ width: logical_size.width * scale as f64,
+ height: logical_size.height * scale as f64,
+ };
+ if !surface_fits(work_rect, physical_size) {
+ anyhow::bail!("the active display work area is too small for the local confirmation");
+ }
+ let origin = match &request {
+ HelperRequest::Consent(_) => place_near_pointer(
+ Point {
+ x: cursor.x as f64,
+ y: cursor.y as f64,
+ },
+ work_rect,
+ physical_size,
+ ),
+ HelperRequest::Indicator(_) => Point {
+ x: work_rect.x + work_rect.width - physical_size.width - 18.0,
+ y: work_rect.y + 18.0,
+ },
+ };
+
+ let class_name = wide("Cua.ProtectedConsentSurface");
+ let title = wide("Cua protected consent");
+ let instance = GetModuleHandleW(PCWSTR::null())?;
+ RegisterClassExW(&WNDCLASSEXW {
+ cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
+ style: CS_HREDRAW | CS_VREDRAW,
+ lpfnWndProc: Some(window_proc),
+ hInstance: instance.into(),
+ lpszClassName: PCWSTR(class_name.as_ptr()),
+ hCursor: LoadCursorW(None, IDC_ARROW)?,
+ ..Default::default()
+ });
+ let hwnd = CreateWindowExW(
+ WS_EX_LAYERED | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
+ PCWSTR(class_name.as_ptr()),
+ PCWSTR(title.as_ptr()),
+ WS_POPUP,
+ origin.x.round() as i32,
+ origin.y.round() as i32,
+ physical_size.width.round() as i32,
+ physical_size.height.round() as i32,
+ None,
+ None,
+ instance,
+ None,
+ )?;
+ let mode = match request {
+ HelperRequest::Consent(card) => SurfaceMode::Consent {
+ card,
+ interaction: ConsentInteraction::new(Instant::now(), ACCEPT_RECT, DECLINE_RECT),
+ },
+ HelperRequest::Indicator(card) => SurfaceMode::Indicator {
+ card,
+ stop_pressed: false,
+ },
+ };
+ *CONTEXT.lock().unwrap() = Some(SurfaceContext {
+ mode,
+ hwnd,
+ scale,
+ pointer: Point { x: -1.0, y: -1.0 },
+ outcome: None,
+ });
+ let _ = SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
+ redraw();
+ ShowWindow(hwnd, SW_SHOW);
+ UpdateWindow(hwnd).ok()?;
+ if !IsWindowVisible(hwnd).as_bool() {
+ anyhow::bail!("the local confirmation window did not become visible");
+ }
+ let _ = SetForegroundWindow(hwnd);
+ SetTimer(hwnd, 1, CONTROL_ARM_DELAY.as_millis() as u32, None);
+ if let Some(delay) = consent_expiry_delay() {
+ SetTimer(
+ hwnd,
+ 2,
+ delay.as_millis().min(u32::MAX as u128) as u32,
+ None,
+ );
+ }
+ crate::protected_consent_event(&HelperEvent::Ready)?;
+
+ let mut message = MSG::default();
+ while GetMessageW(&mut message, None, 0, 0).as_bool() {
+ let _ = TranslateMessage(&message);
+ DispatchMessageW(&message);
+ }
+ let outcome = CONTEXT
+ .lock()
+ .unwrap()
+ .take()
+ .and_then(|context| context.outcome)
+ .unwrap_or_else(fallback_outcome);
+ crate::protected_consent_event(&outcome)?;
+ Ok(())
+}
+
+unsafe extern "system" fn window_proc(
+ hwnd: HWND,
+ message: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+) -> LRESULT {
+ match message {
+ WM_GETOBJECT => return LRESULT(0),
+ WM_MOUSEMOVE => {
+ update_pointer(lparam);
+ redraw();
+ return LRESULT(0);
+ }
+ WM_LBUTTONDOWN => {
+ let point = update_pointer(lparam);
+ let _ = SetCapture(hwnd);
+ with_context(|context| match &mut context.mode {
+ SurfaceMode::Consent { interaction, .. } => {
+ interaction.pointer_down(
+ point,
+ overlay_ui::PointerButton::Primary,
+ Instant::now(),
+ );
+ }
+ SurfaceMode::Indicator { stop_pressed, .. } => {
+ *stop_pressed = STOP_RECT.contains(point);
+ }
+ });
+ return LRESULT(0);
+ }
+ WM_LBUTTONUP => {
+ let _ = ReleaseCapture();
+ let point = update_pointer(lparam);
+ let event = with_context(|context| match &mut context.mode {
+ SurfaceMode::Consent { card, interaction } => {
+ let action = match interaction.pointer_up(point) {
+ InteractionOutcome::Accept => Some(HelperDecision::Accept),
+ InteractionOutcome::Decline => Some(HelperDecision::Decline),
+ _ => None,
+ }?;
+ Some(HelperEvent::Decision {
+ action,
+ request_digest: card.request_digest.clone(),
+ })
+ }
+ SurfaceMode::Indicator { card, stop_pressed } => {
+ let pressed = std::mem::take(stop_pressed);
+ (pressed && STOP_RECT.contains(point)).then(|| HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ })
+ }
+ });
+ if let Some(event) = event {
+ finish(event);
+ }
+ return LRESULT(0);
+ }
+ WM_KEYDOWN if wparam.0 as u32 == u32::from(VK_ESCAPE.0) => {
+ finish(fallback_outcome());
+ return LRESULT(0);
+ }
+ WM_TIMER => {
+ let _ = KillTimer(hwnd, wparam.0);
+ if wparam.0 == 1 {
+ redraw();
+ } else if wparam.0 == 2 {
+ finish(fallback_outcome());
+ }
+ return LRESULT(0);
+ }
+ WM_CLOSE => {
+ finish(fallback_outcome());
+ return LRESULT(0);
+ }
+ WM_DESTROY => {
+ PostQuitMessage(0);
+ return LRESULT(0);
+ }
+ _ => {}
+ }
+ DefWindowProcW(hwnd, message, wparam, lparam)
+}
+
+fn with_context<T>(action: impl FnOnce(&mut SurfaceContext) -> T) -> T {
+ let mut context = CONTEXT.lock().unwrap();
+ action(context.as_mut().expect("protected context initialized"))
+}
+
+fn update_pointer(lparam: LPARAM) -> Point {
+ let x = (lparam.0 as u32 & 0xffff) as i16 as f64;
+ let y = ((lparam.0 as u32 >> 16) & 0xffff) as i16 as f64;
+ with_context(|context| {
+ let point = Point {
+ x: x / context.scale as f64,
+ y: y / context.scale as f64,
+ };
+ context.pointer = point;
+ if let SurfaceMode::Consent { interaction, .. } = &mut context.mode {
+ interaction.pointer_moved(point, Instant::now());
+ }
+ point
+ })
+}
+
+fn finish(event: HelperEvent) {
+ let hwnd = with_context(|context| {
+ context.outcome = Some(event);
+ context.hwnd
+ });
+ unsafe {
+ let _ = DestroyWindow(hwnd);
+ }
+}
+
+fn fallback_outcome() -> HelperEvent {
+ let context = CONTEXT.lock().unwrap();
+ match context.as_ref().map(|context| &context.mode) {
+ Some(SurfaceMode::Consent { card, .. }) => HelperEvent::Decision {
+ action: HelperDecision::Cancel,
+ request_digest: card.request_digest.clone(),
+ },
+ Some(SurfaceMode::Indicator { card, .. }) => HelperEvent::Stop {
+ indicator_id: card.indicator_id.clone(),
+ },
+ None => HelperEvent::Failed {
+ reason: "protected surface closed without context".to_owned(),
+ },
+ }
+}
+
+fn consent_expiry_delay() -> Option<Duration> {
+ CONTEXT.lock().unwrap().as_ref().and_then(|context| {
+ let SurfaceMode::Consent { card, .. } = &context.mode else {
+ return None;
+ };
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or(Duration::ZERO)
+ .as_millis();
+ Some(Duration::from_millis(
+ u128::from(card.expires_unix_ms)
+ .saturating_sub(now)
+ .clamp(100, u128::from(u64::MAX)) as u64,
+ ))
+ })
+}
+
+unsafe fn redraw() {
+ with_context(|context| {
+ let pixmap = match &context.mode {
+ SurfaceMode::Consent { card, interaction } => render_consent(
+ card,
+ context.scale,
+ ConsentVisualState {
+ accept_armed: interaction.accept_armed(Instant::now()),
+ accept_hovered: ACCEPT_RECT.contains(context.pointer),
+ decline_hovered: DECLINE_RECT.contains(context.pointer),
+ },
+ ),
+ SurfaceMode::Indicator { card, .. } => {
+ render_indicator(card, context.scale, STOP_RECT.contains(context.pointer))
+ }
+ };
+ if let Ok(pixmap) = pixmap {
+ update_layered_window(context.hwnd, &pixmap);
+ }
+ });
+}
+
+unsafe fn update_layered_window(hwnd: HWND, pixmap: &tiny_skia::Pixmap) {
+ let width = pixmap.width() as i32;
+ let height = pixmap.height() as i32;
+ let screen = GetDC(None);
+ let memory = CreateCompatibleDC(screen);
+ let info = BITMAPINFO {
+ bmiHeader: BITMAPINFOHEADER {
+ biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
+ biWidth: width,
+ biHeight: -height,
+ biPlanes: 1,
+ biBitCount: 32,
+ biCompression: BI_RGB.0,
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let mut bits = std::ptr::null_mut();
+ let Ok(bitmap) = CreateDIBSection(memory, &info, DIB_RGB_COLORS, &mut bits, None, 0) else {
+ let _ = DeleteDC(memory);
+ ReleaseDC(None, screen);
+ return;
+ };
+ let _ = SelectObject(memory, bitmap);
+ let output = std::slice::from_raw_parts_mut(bits.cast::<u8>(), (width * height * 4) as usize);
+ for (source, target) in pixmap
+ .data()
+ .chunks_exact(4)
+ .zip(output.chunks_exact_mut(4))
+ {
+ target.copy_from_slice(&[source[2], source[1], source[0], source[3]]);
+ }
+ let source = POINT { x: 0, y: 0 };
+ let size = SIZE {
+ cx: width,
+ cy: height,
+ };
+ let blend = BLENDFUNCTION {
+ BlendOp: 0,
+ BlendFlags: 0,
+ SourceConstantAlpha: 255,
+ AlphaFormat: 1,
+ };
+ let _ = UpdateLayeredWindow(
+ hwnd,
+ screen,
+ None,
+ Some(&size),
+ memory,
+ Some(&source),
+ COLORREF(0),
+ Some(&blend),
+ ULW_ALPHA,
+ );
+ let _ = DeleteObject(bitmap);
+ let _ = DeleteDC(memory);
+ ReleaseDC(None, screen);
+}
+
+fn wide(value: &str) -> Vec<u16> {
+ value.encode_utf16().chain(std::iter::once(0)).collect()
+}
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 ba7c75efda..82e1cf17c6 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
@@ -117,7 +117,14 @@ function createWindow() {
}));
mainWindow.webContents.on('did-create-window', child => {
child.once('ready-to-show', () => {
- child.showInactive();
+ // Mutter may activate a newly mapped native-Wayland child even when
+ // Electron requests showInactive(), which makes a background AX action
+ // appear to steal focus. The scenario's behavioral oracle is child
+ // creation, so keep the child hidden on native Wayland and preserve the
+ // visible non-activating window contract on the other backends.
+ if (!nativeWayland || customCuaCompositor) {
+ child.showInactive();
+ }
});
});