Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
chore(cua-driver): add experimental Hyprland plugin foundation (#3547)
Francesco Bonacci7c58a4d5b078
diff --git a/.github/workflows/ci-hyprland-plugin.yml b/.github/workflows/ci-hyprland-plugin.ymlnew file mode 100644index 0000000000..240f430bde--- /dev/null+++ b/.github/workflows/ci-hyprland-plugin.yml@@ -0,0 +1,58 @@+name: "CI: Hyprland plugin unit and mock"++on:+ pull_request:+ paths:+ - "libs/cua-driver/hyprland-plugin/**"+ - ".github/workflows/ci-hyprland-plugin.yml"+ push:+ branches: [main]+ paths:+ - "libs/cua-driver/hyprland-plugin/**"+ - ".github/workflows/ci-hyprland-plugin.yml"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: ci-hyprland-plugin-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ unit:+ name: Linux protocol, transport, and mocked plugin API+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ defaults:+ run:+ working-directory: libs/cua-driver/hyprland-plugin+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ persist-credentials: false+ - name: Install portable test toolchain+ run: |+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends clang-18 ninja-build python3-venv+ python3 -m venv "$RUNNER_TEMP/hyprland-plugin-tools"+ "$RUNNER_TEMP/hyprland-plugin-tools/bin/python" -m pip install cmake==3.31.6+ echo "$RUNNER_TEMP/hyprland-plugin-tools/bin" >> "$GITHUB_PATH"+ - name: Check helper syntax+ run: |+ python3 -c 'import ast; from pathlib import Path; [ast.parse(p.read_text()) for p in Path("tests").glob("*.py")]'+ bash -n packaging/arch/PKGBUILD+ - name: Check lifecycle runner cleanup+ run: python3 -m unittest discover -s tests -p '*_test.py' -v+ # No real Hyprland headers, module load, or desktop certification in this job.+ - name: Configure unit and mock tests+ run: |+ cmake -S . -B "$RUNNER_TEMP/hyprland-plugin-build" -G Ninja \+ -DCMAKE_BUILD_TYPE=Debug \+ -DCMAKE_CXX_COMPILER=clang++-18 \+ -DCUA_HYPRLAND_BUILD_PLUGIN=OFF \+ -DBUILD_TESTING=ON+ - name: Build with compiler warnings as errors+ run: cmake --build "$RUNNER_TEMP/hyprland-plugin-build" --parallel 2+ - name: Run protocol, Linux transport, and mock CTest suite+ run: ctest --test-dir "$RUNNER_TEMP/hyprland-plugin-build" --output-on-failure --no-tests=error --timeout 120diff --git a/docs/content/docs/concepts/index.mdx b/docs/content/docs/concepts/index.mdxindex 3a194c02cf..245bbb82ba 100644--- a/docs/content/docs/concepts/index.mdx+++ b/docs/content/docs/concepts/index.mdx@@ -7,4 +7,8 @@ Use these pages when you want the model behind Cua rather than a step-by-step guFor sandbox compatibility lookup, use [Sandbox runtime support](/reference/sandbox-sdk/runtime-support). For the relationship between an SDK image and a pool's boot artifact, read [How Fleet images work](/concepts/how-fleet-images-work).+For Linux, read [Linux desktops and computer use](/concepts/linux-desktops-and-computer-use)+to understand X11, Wayland, XWayland, and the relationship between Omarchy and+Hyprland before choosing a support-matrix row.+Start with [What is computer use?](/concepts/what-is-computer-use) for the basic model. If you are adding Cua Driver to an agent or product, use [Choose a Cua Driver integration](/concepts/choose-a-cua-driver-integration) before reading the deeper [SDK, MCP, and process hosting](/concepts/sdk-mcp-and-hosting) model. Read [Best-effort background](/concepts/the-no-foreground-contract) to understand Cua Driver's default behavior on a shared machine, then [Capture and delivery modalities](/concepts/capture-and-delivery-modalities) for the action axes. [How we continuously validate Cua Driver](/concepts/how-cua-driver-is-validated) explains why desktop support requires application-owned E2E evidence in addition to unit tests. Read [How sandboxes work](/concepts/how-sandboxes-work) when you need the model for disposable computers, then [Sandbox lifecycle](/concepts/sandbox-lifecycle) for the lifetime and connection patterns. Read [How Lume creates local macOS sandboxes](/concepts/how-lume-unattended-setup-works) for the local VM setup model, and [How SIP works in Lume VMs](/concepts/how-sip-works-in-lume-vms) for signed boot-policy changes. For evaluation, start with [What is Cua-Bench?](/concepts/what-is-cua-bench), then read [The Cua-Bench task lifecycle](/concepts/cua-bench-task-lifecycle).diff --git a/docs/content/docs/concepts/linux-desktops-and-computer-use.mdx b/docs/content/docs/concepts/linux-desktops-and-computer-use.mdxnew file mode 100644index 0000000000..44840ffe4d--- /dev/null+++ b/docs/content/docs/concepts/linux-desktops-and-computer-use.mdx@@ -0,0 +1,141 @@+---+title: Linux desktops and computer use+description: How X11, Wayland, desktop environments, and compositors affect Cua Driver's capture and input routes.+---++X11, Wayland, Hyprland, and Omarchy describe different parts of a Linux+desktop, not interchangeable operating systems. For Cua Driver, the important+questions are which display session is running, how the target application+connects to it, and which capture and input routes that combination exposes.++This page explains those layers. For accepted capabilities and limitations,+use the [Linux support matrix](/reference/cua-driver/platform-support#linux-window-systems).++## Where the names fit++A **distribution**, such as Ubuntu, Fedora, or Arch Linux, supplies the+operating system and packages. A **desktop environment**, such as GNOME, KDE+Plasma, or Xfce, supplies the shell and desktop applications. The same+distribution can run different desktop environments and display sessions.++**X11** and **Wayland** are display protocols. They define how applications+communicate with the software that displays their windows and delivers input.++- In an X11 session, an X server such as **Xorg** manages the display and input.+ A window manager handles placement and focus. A compositing manager may add+ visual effects. **Xvfb** is an X server backed by a virtual framebuffer,+ useful for automated desktops; it does not reproduce every physical Xorg+ input path.+- In a Wayland session, the **compositor** combines display-server, window+ management, and composition responsibilities. **Sway** and **Hyprland** are+ different Wayland compositors. GNOME uses **Mutter**, and KDE Plasma uses+ **KWin** for its Wayland session.++**Omarchy** is an Arch-based desktop setup built around Hyprland and Wayland.+An Omarchy machine therefore needs Hyprland-specific validation, not just an+"Arch Linux works" or "Wayland works" result. A plugin for Hyprland is not+limited to Omarchy, but it must match the Hyprland build that loads it.++**wlroots** is a library for building Wayland compositors, including Sway. It+is not another display protocol. Modern Hyprland is not based on wlroots,+although it implements some protocols with `wlr` names. Shared protocol names+do not establish identical behavior or transfer Sway's test results to+Hyprland.++## XWayland is an application compatibility path++**XWayland** runs X11 applications inside a Wayland session. One desktop can+contain both native Wayland applications and X11 applications using XWayland.+Some toolkits can use either backend, so an application's name alone does not+identify its input path.++Cua Driver can use an X11 route only when the target exposes a real X11+window. XWayland does not make a native Wayland window addressable through+X11, and it does not guarantee that every X11 background-input technique works+unchanged inside a Wayland compositor.++## Capture, accessibility, and input are separate capabilities++Seeing an application's pixels does not imply permission or a safe route to+control it. Cua Driver combines several facilities:++- **AT-SPI** exposes application accessibility trees and semantic actions,+ such as invoking a button or editing an accessible text field. Availability+ depends on the application and its accessibility bridge as well as the+ desktop session.+- **Capture and window-discovery protocols** provide images, window identity,+ and geometry. Wayland compositors expose different combinations, sometimes+ requiring a compositor-specific adapter or helper.+- **Portals and libei** provide permission-mediated capture or emulated-input+ routes where the desktop implements them. An input grant does not by itself+ provide an arbitrary background-window target.+- **Compositor integrations** can expose capabilities absent from ordinary+ client protocols. They need their own compatibility, authorization, and+ behavioral tests.++This is why a successful `cua-driver doctor` check establishes prerequisites,+not proof that every action reaches every application.++## Wayland has coordinates, but controls input routing++Wayland compositors have output layouts and surface coordinates. What an+ordinary application generally lacks is unrestricted access to other windows'+global geometry and an API for sending raw input to any chosen window.++A compositor adapter can tell Cua Driver where a window is. That still does not+change which window receives input from the compositor's active **seat**, the+logical grouping of pointer, keyboard, and other input devices. Moving a+virtual pointer to a screen coordinate can target an occluding window instead+of the intended background window.++Isolated background input therefore requires more than coordinate conversion+or drawing a second cursor. It must keep the user's pointer focus, held+buttons, keyboard state, and active gestures independent from agent input.+Client applications must also accept the resulting events.++## Background actions are not all raw input++An AT-SPI action can invoke an accessible button without synthesizing a mouse+click. That can work while the window stays in the background. A pixel-addressed+request can also resolve to an accessible control and use a semantic action;+pixel addressing does not necessarily mean raw event injection.++A canvas drag or game keypress may require raw pointer or keyboard events+instead. When Cua Driver has no safe target-addressed route, the correct+outcome is a structured refusal, not a hidden focus change. Foreground+delivery is a separate, explicitly authorized operation.++See [Capture and delivery modalities](/concepts/capture-and-delivery-modalities)+for the action axes and [Best-effort background](/concepts/the-no-foreground-contract)+for the no-foreground contract.++## A private desktop is different from a shared desktop++A Fleet VM gives the agent a separate desktop. Foreground input inside that+VM does not take over the user's host desktop, but it can still interfere+with another actor inside the same VM. VM isolation does not prove isolated+background delivery within one desktop session.++Likewise, the experimental nested `cua-compositor` controls its own Wayland+session. Its input capabilities do not establish support on stock Sway,+Hyprland, GNOME, or KDE.++For an existing Linux host, use the support row for its compositor and the+target application's backend. For a separate Omarchy desktop, see+[Run Omarchy on Fleet](/how-to-guides/sandbox/run-omarchy-on-cloud-fleet) or+the experimental [Apple Silicon VM guide](/how-to-guides/lume/run-omarchy-arm64).+Those guides describe environments, not a broader input-support guarantee.++## Find the applicable support evidence++Use [Platform Support](/reference/cua-driver/platform-support) for accepted+behavior and [Platform Roadmap](/reference/cua-driver/platform-roadmap) for+engineering work and missing evidence. In particular, the+[Hyprland and Omarchy status](/reference/cua-driver/platform-support#hyprland-and-omarchy)+separates driver validation from the experimental plugin foundation.++A source-branch test result is not a released capability. Record the driver+version, compositor version, application backend, and tested source revision+when comparing results. [How Cua Driver is validated](/concepts/how-cua-driver-is-validated)+explains why a passing test must observe application state and desktop side+effects, not only a successful tool response.diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.jsonindex 8366f8eb19..40dc40a945 100644--- a/docs/content/docs/concepts/meta.json+++ b/docs/content/docs/concepts/meta.json@@ -9,6 +9,7 @@"sdk-mcp-and-hosting","the-no-foreground-contract","capture-and-delivery-modalities",+ "linux-desktops-and-computer-use","browser-targeting-and-background-delivery","how-permission-policies-work","how-cua-driver-is-validated",diff --git a/docs/content/docs/how-to-guides/driver/install.mdx b/docs/content/docs/how-to-guides/driver/install.mdxindex f908c5ce0b..719c6021c5 100644--- a/docs/content/docs/how-to-guides/driver/install.mdx+++ b/docs/content/docs/how-to-guides/driver/install.mdx@@ -6,10 +6,13 @@ description: Install Cua Driver on macOS, Windows, or Linux with a one-line scriimport { Tabs, Tab } from 'fumadocs-ui/components/tabs';import { Callout } from 'fumadocs-ui/components/callout';-Cua Driver supports macOS, Windows, and Linux. Use the same **one-line installer** on each platform; the script selects the right install path for the host and *does not require administrator access*.+Cua Driver supports macOS, Windows, and Linux. Use the same **one-line installer** on each platform; the script selects the right install path for the host and _does not require administrator access_.<Callout type="info">- Cua Driver sends content-free product telemetry by default. The installer shows this notice before the first event. Run `cua-driver telemetry disable` at any time to stop telemetry; the preference persists across upgrades. See [Telemetry and privacy](/reference/cua-driver/telemetry) for the exact event schema and identity controls.+ Cua Driver sends content-free product telemetry by default. The installer shows this notice before+ the first event. Run `cua-driver telemetry disable` at any time to stop telemetry; the preference+ persists across upgrades. See [Telemetry and privacy](/reference/cua-driver/telemetry) for the+ exact event schema and identity controls.</Callout><Tabs items={['macOS', 'Windows', 'Linux']}>@@ -46,7 +49,7 @@ To skip the PATH change, pass the no-update flag:</Tab><Tab value="Linux">-**Requirements:** an x86_64 Linux desktop session with X11 or XWayland, plus AT-SPI 2 for accessibility-tree tools. The window-driving tools (`click`, `type_text`, `get_window_state`) need a live display server and a running app, so a headless server has no windows to drive until you start a desktop session (for example `xfce4` under `Xvfb`).+**Requirements:** an x86_64 Linux desktop session with X11/XWayland or the opt-in native Wayland backend described below, plus AT-SPI 2 for accessibility-tree tools. The window-driving tools (`click`, `type_text`, `get_window_state`) need a live display server and a running app, so a headless server has no windows to drive until you start a desktop session (for example `xfce4` under `Xvfb`).On a minimal or server image, install the runtime libraries the binary links against first. Unlike the installer itself, this step needs `sudo`; without `libXi` the binary fails to launch with `libXi.so.6: cannot open shared object file`, before `doctor` can even run:@@ -65,16 +68,22 @@ PATH change. Installing the binary does not start the Linux daemon. Follow[Start the daemon on Linux](#start-the-daemon-on-linux) below before callingdesktop tools.-X11 is fully supported. Native Wayland remains opt-in with+X11 support has toolkit-specific limits. Native Wayland remains opt-in with`CUA_DRIVER_RS_ENABLE_WAYLAND=1` and has compositor-specific limits. Sway issupported with limits, GNOME requires the maintained WinRects helper, and KDE-remains experimental. Without the opt-in, Wayland sessions use XWayland routes+and Hyprland/Omarchy have separate experimental support entries. Without the+opt-in, Wayland sessions use XWayland routeswhere the target exposes a real X11 window. See[Platform support](/reference/cua-driver/platform-support#linux-window-systems)for the exact accepted surfaces. After installation, run `cua-driver doctor`to check distro-specific requirements such as the AT-SPI bus and displayserver.+If these names are unfamiliar, start with+[Linux desktops and computer use](/concepts/linux-desktops-and-computer-use).+The experimental Hyprland plugin is separate from this installer; installing+the driver does not enable isolated raw background input on Omarchy.+</Tab></Tabs>@@ -172,11 +181,11 @@ when an asset is missing, and cannot be combined with `--channel`.Cua Driver authorizes every agent action inside the native runtime, and the mode is fixed when that runtime starts. An agent cannot change it, and neither can you change it on a running daemon — you restart the daemon with different flags. Decide which mode you want before starting the daemon below.-| Mode | Use it when |-| ---- | ----------- |-| `standard` | Normal local CLI and MCP use. Observation, input, isolated browser use, recording, and validated file transfer run without prompts. Residual boundaries, such as attaching to an existing logged-in Chromium profile, still need an explicit grant. |-| `bounded` | An unattended agent, gateway, or embedded application must stay inside a reviewed manifest of tools, applications, browser origins, and directories. Anything outside the manifest is denied. |-| `unrestricted` | The machine is disposable or fully trusted and you accept every capability the built-in, managed, and user policy ceilings still allow. |+| Mode | Use it when |+| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `standard` | Normal local CLI and MCP use. Observation, input, isolated browser use, recording, and validated file transfer run without prompts. Residual boundaries, such as attaching to an existing logged-in Chromium profile, still need an explicit grant. |+| `bounded` | An unattended agent, gateway, or embedded application must stay inside a reviewed manifest of tools, applications, browser origins, and directories. Anything outside the manifest is denied. |+| `unrestricted` | The machine is disposable or fully trusted and you accept every capability the built-in, managed, and user policy ceilings still allow. |`standard` is the default and is what the rest of this guide assumes, so plain `cua-driver serve` needs no flags. For `bounded`, pass a manifest plus the review acknowledgement:@@ -276,7 +285,9 @@ cua-driver permissions status```<Callout type="info">- `cua-driver permissions status` reads the driver's actual grant state through the daemon. When no daemon is running, it reports `❓ unknown` instead of reporting your terminal's grants, and it does not claim `granted` unless the driver has that permission.+ `cua-driver permissions status` reads the driver's actual grant state through the daemon. When no+ daemon is running, it reports `❓ unknown` instead of reporting your terminal's grants, and it+ does not claim `granted` unless the driver has that permission.</Callout>## Verify desktop readinessdiff --git a/docs/content/docs/how-to-guides/lume/run-omarchy-arm64.mdx b/docs/content/docs/how-to-guides/lume/run-omarchy-arm64.mdxindex dd26fa4e3c..3a16448e3f 100644--- a/docs/content/docs/how-to-guides/lume/run-omarchy-arm64.mdx+++ b/docs/content/docs/how-to-guides/lume/run-omarchy-arm64.mdx@@ -9,6 +9,11 @@ the Omarchy shell, accepts keyboard and pointer input, runs native ARM64applications, and translates self-contained x86-64 Linux programs withRosetta.+For how Omarchy, Hyprland, and Wayland fit together, read+[Linux desktops and computer use](/concepts/linux-desktops-and-computer-use).+The VM results in this guide do not certify Cua Driver application support;+see the separate [Hyprland support entry](/reference/cua-driver/platform-support#hyprland-and-omarchy).+<Callout type="warn" title="Experimental compatibility install">This is official Omarchy source installed on an Arch Linux ARM base. It is not an official OmarchyARM64 release, and it does not use Omarchy's stock ISO installer. The published Omarchy ISO anddiff --git a/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdxindex 303fef347a..dc7df7597e 100644--- a/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx+++ b/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx@@ -10,6 +10,12 @@ Use the Cua Sandbox SDK to provision an amd64 Omarchy desktop onas a KubeVirt `containerDisk`; the guest starts Hyprland and exposes both the`cua-computer-server` API and the Cua Driver MCP service.+For the desktop stack and input boundaries, see+[Linux desktops and computer use](/concepts/linux-desktops-and-computer-use)+and [Hyprland support](/reference/cua-driver/platform-support#hyprland-and-omarchy).+Provisioning a private VM does not establish isolated background input between+applications inside that VM.+<Callout type="info">This guide is for the amd64 Fleet image. The [Omarchy on Apple Siliconguide](/how-to-guides/lume/run-omarchy-arm64) builds a separate ARM64 VM for local Lume use anddiff --git a/docs/content/docs/reference/cua-driver/platform-roadmap.mdx b/docs/content/docs/reference/cua-driver/platform-roadmap.mdxindex d6658a9610..6fdd570048 100644--- a/docs/content/docs/reference/cua-driver/platform-roadmap.mdx+++ b/docs/content/docs/reference/cua-driver/platform-roadmap.mdx@@ -10,10 +10,10 @@ desktop state.## Status vocabulary-| Status | Meaning |-| ----------------- | ------------------------------------------------------------------------------------------------- |-| Proven | Canonical harness evidence supports the current public claim. |-| Evidence gap | Code or platform APIs may support the behavior, but representative harness evidence is missing. |+| Status | Meaning |+| ----------------- | -------------------------------------------------------------------------------------------------- |+| Proven | Canonical harness evidence supports the current public claim. |+| Evidence gap | Code or platform APIs may support the behavior, but representative harness evidence is missing. || Engineering work | A concrete driver, fixture, observer, or runner change is required. || Experimental | An opt-in backend or environment has evidence but is not part of the general support contract. || Platform boundary | The ordinary OS security or windowing model does not expose a safe general route for the behavior. |@@ -24,22 +24,22 @@ inside an environment that owns the compositor.## Cross-platform priorities-| Area | Current state | Next acceptance condition |-| ---------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |-| Shared application catalog | Electron and Tauri use one typed Rust behavior catalog across operating systems. | Keep the same action, AX/PX, foreground/background, scope, and oracle dimensions on every representative host. |-| Native application catalogs | Windows, macOS, and Linux have toolkit-specific source-built harnesses. | Expand native rows toward the shared action cross-product where the toolkit exposes an equivalent behavior. |-| Background safety | Background cells attach focus, z-order, cursor, and leaked-input oracles. | Add the same side-effect owners to every new background delivery or refusal row. |-| Release evidence | Hosted GUI lanes retain typed results, trajectories, screenshots, logs, and per-cell video. | Require accepted exact-source-SHA runs for affected platforms before changing release support claims. |-| Representative environments | Hosted lanes cover Windows, Linux X11, Sway, and the nested compositor; macOS uses a logged-in host. | Close named GNOME, KDE, real-Xorg, and renderer evidence gaps without weakening fixtures or oracles. |+| Area | Current state | Next acceptance condition |+| --------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |+| Shared application catalog | Electron and Tauri use one typed Rust behavior catalog across operating systems. | Keep the same action, AX/PX, foreground/background, scope, and oracle dimensions on every representative host. |+| Native application catalogs | Windows, macOS, and Linux have toolkit-specific source-built harnesses. | Expand native rows toward the shared action cross-product where the toolkit exposes an equivalent behavior. |+| Background safety | Background cells attach focus, z-order, cursor, and leaked-input oracles. | Add the same side-effect owners to every new background delivery or refusal row. |+| Release evidence | Hosted GUI lanes retain typed results, trajectories, screenshots, logs, and per-cell video. | Require accepted exact-source-SHA runs for affected platforms before changing release support claims. |+| Representative environments | Hosted lanes cover Windows, Linux X11, Sway, and the nested compositor; macOS uses a logged-in host. | Close named GNOME, KDE, real-Xorg, and renderer evidence gaps without weakening fixtures or oracles. |## Windows-| Work item | Status | Acceptance condition |-| ------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| Broader WPF PX gestures and keyboard paths | Evidence gap | Typed foreground/background rows observe native control state and all required desktop side effects. |-| WinUI 3 pointer and background coverage | Evidence gap | Right click, double click, drag, scroll, and keyboard contracts are declared and empirically observed or refused. |-| WebView2 native-input coverage | Evidence gap | Native pointer and keyboard cells complement the existing page/CDP and background-left-click evidence. |-| Elevated-integrity boundary | Engineering work | A controlled fixture proves the `background_uipi_blocked` contract across process integrity levels. |+| Work item | Status | Acceptance condition |+| ------------------------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------------- |+| Broader WPF PX gestures and keyboard paths | Evidence gap | Typed foreground/background rows observe native control state and all required desktop side effects. |+| WinUI 3 pointer and background coverage | Evidence gap | Right click, double click, drag, scroll, and keyboard contracts are declared and empirically observed or refused. |+| WebView2 native-input coverage | Evidence gap | Native pointer and keyboard cells complement the existing page/CDP and background-left-click evidence. |+| Elevated-integrity boundary | Engineering work | A controlled fixture proves the `background_uipi_blocked` contract across process integrity levels. |Windows integrity isolation is a platform boundary: a lower-integrity processcannot generally inject input into a higher-integrity target. The roadmap item@@ -47,11 +47,11 @@ is to detect and prove that refusal, not bypass the operating-system boundary.## macOS-| Work item | Status | Acceptance condition |-| ---------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------- |-| Native AppKit action cross-product | Evidence gap | Press key, hotkey, AX-addressed pointer gestures, and additional controls have application-owned evidence. |-| SwiftUI transient-window discovery | Engineering work | The opened popover or panel is independently visible through targeted window and AX enumeration. |-| Installed-app confidence checks | Proven | Keep the typed Calculator and TextEdit rows as supporting evidence; repo-local fixtures remain the primary behavioral contract. |+| Work item | Status | Acceptance condition |+| ---------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |+| Native AppKit action cross-product | Evidence gap | Press key, hotkey, AX-addressed pointer gestures, and additional controls have application-owned evidence. |+| SwiftUI transient-window discovery | Engineering work | The opened popover or panel is independently visible through targeted window and AX enumeration. |+| Installed-app confidence checks | Proven | Keep the typed Calculator and TextEdit rows as supporting evidence; repo-local fixtures remain the primary behavioral contract. |Accessibility and Screen Recording consent remain platform prerequisites.Off-Space SwiftUI tree stripping, minimized keyboard commits, and applications@@ -72,13 +72,46 @@ remains required.## Linux Wayland-| Environment | Work item | Status | Acceptance condition |-| ----------------------- | --------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------- |-| Sway/wlroots | Preserve the accepted shared and native catalog | Proven | Keep every declared Electron, Tauri, and GTK cell delivering or returning its exact refusal through unchanged oracles. |-| GNOME/Mutter | Shared renderer catalog and portal video | Evidence gap | Electron and representative WebKitGTK rows pass with reporter-owned per-cell recordings. |-| KDE/KWin | Target-addressable activation and full matrix | Engineering work | A supported KWin adapter activates the selected target and an independent observer verifies it before portal input. |-| Nested `cua-compositor` | Complete shared catalog and protocol coverage | Experimental | One accepted full catalog proves renderer behavior, Unicode text, and canonical parallel drag. |-| Other wlroots | Representative compatibility | Evidence gap | Add a lane only after a user report demonstrates behavior that the Sway lane does not represent. |+| Environment | Work item | Status | Acceptance condition |+| ----------------------- | ----------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Sway/wlroots | Preserve the accepted shared and native catalog | Proven | Keep every declared Electron, Tauri, and GTK cell delivering or returning its exact refusal through unchanged oracles. |+| Hyprland / Omarchy | Driver integration and isolated-input plugin | Experimental | Accept integrated driver evidence separately from plugin transport tests; complete the design and behavior gates below before claiming isolated input. |+| GNOME/Mutter | Shared renderer catalog and portal video | Evidence gap | Electron and representative WebKitGTK rows pass with reporter-owned per-cell recordings. |+| KDE/KWin | Target-bound input and full matrix | Engineering work | Bind the input operation itself to the selected target and verify application state. The existing read-only helper and a pre-dispatch focus check cannot make later focus-bound portal input target-safe. |+| Nested `cua-compositor` | Complete shared catalog and protocol coverage | Experimental | One accepted full catalog proves renderer behavior, Unicode text, and canonical parallel drag. |+| Other wlroots | Representative compatibility | Evidence gap | Add a lane only after a user report demonstrates behavior that the Sway lane does not represent. |++### Hyprland and Omarchy++The [support reference](/reference/cua-driver/platform-support#hyprland-and-omarchy)+records the dated driver-branch and plugin evidence. The discovery-only plugin+is not an input implementation, and its lifecycle tests do not replace the+driver's representative desktop catalog.++Promotion requires distinct design, implementation, and validation work:++- Accept an RFC for the input and permission contract, including operator+ authorization, revocation, target identity, and compositor restart behavior.+ Same-UID socket access does not identify or authorize a particular agent.+- Review the nonshipping [input experiment #3572](https://github.com/trycua/cua/pull/3572)+ before adopting a production integration. Its independent synthetic seat and+ test-only authorization grants provide focused evidence, not a production+ approval mechanism or general client compatibility. A second cursor image or+ a successful transport request is not sufficient.+- Prove packaged installation, upgrade refusal, restart, and ABI compatibility+ on the exact Hyprland/plugin/toolchain combination. Preserve discovery and+ lifecycle checks as a separate gate.+- Run the representative application catalog at the integrated candidate SHA,+ with fixture-owned state plus focus, z-order, cursor, and leaked-input+ oracles. Include concurrent foreground grabs, keyboard state, native Wayland+ and XWayland clients, and explicit unsupported-action refusals.+- Complete the plugin's documented physical Omarchy acceptance baseline after+ Fleet validation. A VM run supplements that gate; it does not certify a+ bare-metal host or a different package combination.++These are acceptance conditions, not an approved protocol or a delivery date.+The plugin is Hyprland-specific rather than Omarchy-specific, and does not add+the same capability to Sway, GNOME, or KDE.### Standard Wayland boundarydiff --git a/docs/content/docs/reference/cua-driver/platform-support.mdx b/docs/content/docs/reference/cua-driver/platform-support.mdxindex e771513665..dbdbc06f40 100644--- a/docs/content/docs/reference/cua-driver/platform-support.mdx+++ b/docs/content/docs/reference/cua-driver/platform-support.mdx@@ -42,14 +42,14 @@ Browser mutation always starts from an exact native `(pid, window_id)` binding.The table records the strongest browser route currently proven by the Rustharnesses; an unlisted trust class or host shape is not implied.-| Surface | Proven page routes | Explicit limit |-| --- | --- | --- |-| Standalone Chrome and Edge on Windows | Snapshot, navigation, ref-bound typing, trusted background click, explicit DOM click and pointer actions, JavaScript dialogs, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Elevated-integrity and unsupported native-host relationships still refuse |-| Standalone Chrome on macOS | Snapshot, navigation, ref-bound typing, explicit DOM click and pointer actions, JavaScript dialogs, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Trusted CDP pointer input returns `browser_input_trust_unavailable` before dispatch |-| Standalone Chrome and Edge on Linux X11 | Snapshot, navigation, ref-bound typing, explicit DOM click and pointer actions, foreground JavaScript-dialog resolution, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Trusted CDP pointer input and background JavaScript-dialog resolution return `browser_input_trust_unavailable` before dispatch |-| Electron on Windows, macOS, X11, and validated Sway | Typed mutation while one proven native window maps to one CDP page | A second page or native window invalidates the bounded exact route |-| Tauri, WKWebView, WebKitGTK, and common split-process WebView2 | Browser identity plus a side-effect-free structured refusal | No exact native-host-to-engine relationship is currently proven |-| Safari and Firefox | Native discovery and native AX/PX fallbacks | No typed browser mutation engine is currently advertised |+| Surface | Proven page routes | Explicit limit |+| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| Standalone Chrome and Edge on Windows | Snapshot, navigation, ref-bound typing, trusted background click, explicit DOM click and pointer actions, JavaScript dialogs, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Elevated-integrity and unsupported native-host relationships still refuse |+| Standalone Chrome on macOS | Snapshot, navigation, ref-bound typing, explicit DOM click and pointer actions, JavaScript dialogs, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Trusted CDP pointer input returns `browser_input_trust_unavailable` before dispatch |+| Standalone Chrome and Edge on Linux X11 | Snapshot, navigation, ref-bound typing, explicit DOM click and pointer actions, foreground JavaScript-dialog resolution, file assignment, approved downloads, frames, multi-tab, and exact ambiguity refusal | Trusted CDP pointer input and background JavaScript-dialog resolution return `browser_input_trust_unavailable` before dispatch |+| Electron on Windows, macOS, X11, and validated Sway | Typed mutation while one proven native window maps to one CDP page | A second page or native window invalidates the bounded exact route |+| Tauri, WKWebView, WebKitGTK, and common split-process WebView2 | Browser identity plus a side-effect-free structured refusal | No exact native-host-to-engine relationship is currently proven |+| Safari and Firefox | Native discovery and native AX/PX fallbacks | No typed browser mutation engine is currently advertised |`browser_prepare` may launch a separate driver-owned Chromium profile after anapproved destructive call. `isolated_new` processes and their complete child@@ -72,14 +72,43 @@ Linux support is recorded per window system and Wayland compositor. "Wayland"is not one uniform automation API: compositors expose different discovery,capture, activation, and input protocols.-| Environment | State | What is proven | Main limits |-| ------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| X11/Xorg | Supported | Window discovery and capture, AT-SPI trees and actions, foreground pointer and keyboard input, semantic background delivery, desktop scope, and structured refusals | Raw background delivery depends on the target toolkit. X11 accepting an event does not prove the application handled it. |-| Sway (wlroots reference lane) | Supported with limits | The complete typed Electron, Tauri, GTK, capture, and desktop-scope catalog, including foreground/background and AX/PX outcomes | Focus-bound and raw background input shapes without a target-addressed protocol return structured refusals. Other wlroots compositors are expected to share protocol support but are not yet proven. |-| GNOME/Mutter | Supported with limits | AT-SPI actions, GTK controls, compositor-backed window geometry and capture, verified foreground activation, and portal/libei foreground input | The bundled WinRects Shell helper and one Shell-session restart are prerequisites for authoritative geometry and activation. Portal video recording remains incomplete. |-| KDE/KWin | Experimental | Plasma 6 session startup, GTK AT-SPI discovery, generic discovery where exposed, and portal interface availability | cua-driver does not yet have a target-addressable KWin activation adapter, and no complete behavioral matrix is accepted. Focus-bound input refuses rather than risking delivery to the wrong application. |-| `cua-compositor` nested session | Experimental | Native GTK behavior, capture and scope, private route metadata, independent observation, and per-cell video | The complete shared renderer matrix is not accepted. Unicode text and a canonical parallel-drag row remain unproven; this route does not establish a stock-Wayland capability. |-| XWayland | Supported with limits | X11 routes are used when the application exposes a real X11 window; native Wayland and AT-SPI fallbacks cover mixed sessions | Capabilities depend on whether the application is actually using X11 or native Wayland. |+For the relationship between distributions, desktops, and compositors, read+[Linux desktops and computer use](/concepts/linux-desktops-and-computer-use).++| Environment | State | What is proven | Main limits |+| ------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| X11/Xorg | Supported | Window discovery and capture, AT-SPI trees and actions, foreground pointer and keyboard input, semantic background delivery, desktop scope, and structured refusals | Raw background delivery depends on the target toolkit. X11 accepting an event does not prove the application handled it. |+| Sway (wlroots reference lane) | Supported with limits | The complete typed Electron, Tauri, GTK, capture, and desktop-scope catalog, including foreground/background and AX/PX outcomes | Focus-bound and raw background input shapes without a target-addressed protocol return structured refusals. Other wlroots compositors are expected to share protocol support but are not yet proven. |+| Hyprland / Omarchy | Experimental | Separate [driver-branch and plugin-foundation evidence](#hyprland-and-omarchy); neither establishes a released general Hyprland support claim | Do not inherit Sway coverage. The optional plugin is discovery-only and does not deliver input. Driver capture, activation, semantic actions, and raw background input require separate evidence. |+| GNOME/Mutter | Supported with limits | AT-SPI actions, GTK controls, compositor-backed window geometry and capture, verified foreground activation, and portal/libei foreground input | The bundled WinRects Shell helper and one Shell-session restart are prerequisites for authoritative geometry and activation. Portal video recording remains incomplete. |+| KDE/KWin | Experimental | Plasma 6 session startup, GTK AT-SPI discovery, generic discovery where exposed, and portal interface availability | The optional KWin helper exposes read-only window identity and state, not activation or input. Raw target-addressed input refuses until a target-bound KWin input path exists; no complete behavioral matrix is accepted. |+| `cua-compositor` nested session | Experimental | Native GTK behavior, capture and scope, private route metadata, independent observation, and per-cell video | The complete shared renderer matrix is not accepted. Unicode text and a canonical parallel-drag row remain unproven; this route does not establish a stock-Wayland capability. |+| XWayland | Supported with limits | X11 routes are used when the application exposes a real X11 window; native Wayland and AT-SPI fallbacks cover mixed sessions | Capabilities depend on whether the application is actually using X11 or native Wayland. |++### Hyprland and Omarchy++Omarchy uses Hyprland; it is not a separate display protocol. Modern Hyprland+is not based on wlroots, so its support must be recorded separately from Sway.++The following is a source-work status snapshot as of September 5, 2026, not an+installer or release-support matrix:++| Work | Evidence and boundary |+| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Driver capture and observation | [Draft PR #3557](https://github.com/trycua/cua/pull/3557) reports scale-1 GTK3 capture, semantic actions, and independent focus/cursor checks at source `b50a4f78f277d05700200e84c5d0f0ea72f10c47`. Its canonical native suite stopped at the foreground-key preflight; no matrix cells ran. This is focused branch evidence, not desktop certification or released support. |+| Optional Hyprland plugin | [PR #3547](https://github.com/trycua/cua/pull/3547) adds discovery and liveness only. Its [validation report](https://github.com/trycua/cua/blob/feat/hyprland-plugin-foundation/libs/cua-driver/hyprland-plugin/tests/validation.md) records native build and live lifecycle evidence on Hyprland `0.56.2`. All six input message types return `background_unavailable`; the foundation creates no synthetic seat and changes no Driver delivery route. |+| Isolated raw background input | [Draft experiment #3572](https://github.com/trycua/cua/pull/3572) contains a separately opted-in synthetic-seat integration. Its [desktop-transition report](https://github.com/trycua/cua/blob/e8542dece6c8195a8db50ba79aba9615a78340b1/libs/cua-driver/hyprland-plugin/tests/desktop-state-validation.md) records focused Fleet evidence and tested revisions. The experiment is not part of the discovery foundation, a released capability, or an accepted production input/authorization contract. |++The plugin is disabled by default and outside the portable driver installation+path. Switching driver channels alone does not install or enable it. Its+Hyprland ABI and compiler toolchain must match the compositor that loads it.++The recorded plugin Fleet environment used Omarchy `4.0.1-1` and Cua Driver+`0.22.2`. It does not certify the separate physical-host acceptance target of+Omarchy `4.0.2-1` with Cua Driver `0.23.2`, or application control through+either driver version. See the+[Hyprland roadmap](/reference/cua-driver/platform-roadmap#hyprland-and-omarchy)+for the remaining design and validation gates.### Wayland background AX and PXdiff --git a/libs/cua-driver/hyprland-plugin/CMakeLists.txt b/libs/cua-driver/hyprland-plugin/CMakeLists.txtnew file mode 100644index 0000000000..584ec9efaa--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/CMakeLists.txt@@ -0,0 +1,174 @@+cmake_minimum_required(VERSION 3.30)++project(cua_hyprland_plugin VERSION 0.1.0 LANGUAGES CXX)++option(CUA_HYPRLAND_BUILD_PLUGIN "Build the ABI-pinned Hyprland plugin" ON)+set(CUA_HYPRLAND_EXPECTED_VERSION "" CACHE STRING+ "Require an exact hyprland pkg-config version when building the plugin")++include(CTest)+include(cmake/DetectHyprlandAPI.cmake)++function(cua_hyprland_harden target)+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")+ target_compile_definitions(${target} PRIVATE+ $<$<CONFIG:Release,RelWithDebInfo,MinSizeRel>:_FORTIFY_SOURCE=3>+ _GLIBCXX_ASSERTIONS)+ target_compile_options(${target} PRIVATE -fstack-protector-strong)+ endif()+ target_compile_options(${target} PRIVATE -fno-lto)+endfunction()++add_library(cua_hyprland_protocol STATIC+ src/protocol.cpp+ src/session.cpp+ src/status.cpp)+target_compile_features(cua_hyprland_protocol PUBLIC cxx_std_26)+target_include_directories(cua_hyprland_protocol PUBLIC include)+target_compile_options(cua_hyprland_protocol PRIVATE -Wall -Wextra -Wpedantic -Werror)+cua_hyprland_harden(cua_hyprland_protocol)+set_target_properties(cua_hyprland_protocol PROPERTIES POSITION_INDEPENDENT_CODE ON)++if(BUILD_TESTING)+ add_test(NAME cua_hyprland_cmake_api_test+ COMMAND ${CMAKE_COMMAND}+ -S ${CMAKE_CURRENT_SOURCE_DIR}/tests/cmake-api+ -B ${CMAKE_CURRENT_BINARY_DIR}/cmake-api-test+ -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER})+ add_executable(cua_hyprland_protocol_test tests/protocol_test.cpp)+ target_link_libraries(cua_hyprland_protocol_test PRIVATE cua_hyprland_protocol)+ target_compile_options(cua_hyprland_protocol_test PRIVATE -Wall -Wextra -Wpedantic -Werror)+ add_test(NAME cua_hyprland_protocol_test COMMAND cua_hyprland_protocol_test)++ add_executable(cua_hyprland_status_test tests/status_test.cpp)+ target_link_libraries(cua_hyprland_status_test PRIVATE cua_hyprland_protocol)+ target_compile_options(cua_hyprland_status_test PRIVATE -Wall -Wextra -Wpedantic -Werror)+ add_test(NAME cua_hyprland_status_test COMMAND cua_hyprland_status_test)++ foreach(api_variant IN ITEMS socket1 legacy)+ if(api_variant STREQUAL "socket1")+ set(api_value 1)+ else()+ set(api_value 0)+ endif()+ add_library(cua_hyprland_plugin_api_${api_variant}_compile_test+ OBJECT src/plugin.cpp)+ target_compile_features(cua_hyprland_plugin_api_${api_variant}_compile_test+ PRIVATE cxx_std_26)+ target_compile_definitions(cua_hyprland_plugin_api_${api_variant}_compile_test+ PRIVATE+ CUA_HYPRLAND_PLUGIN_VERSION="${PROJECT_VERSION}"+ CUA_HYPRLAND_SOCKET1_API=${api_value})+ target_compile_options(cua_hyprland_plugin_api_${api_variant}_compile_test+ PRIVATE -Wall -Wextra -Wpedantic -Werror -Wno-return-type-c-linkage)+ target_include_directories(cua_hyprland_plugin_api_${api_variant}_compile_test+ PRIVATE tests/mock-hyprland include src)+ endforeach()+endif()++if(UNIX)+ find_package(Threads REQUIRED)+ add_library(cua_hyprland_transport STATIC src/inject_server.cpp)+ target_compile_features(cua_hyprland_transport PUBLIC cxx_std_26)+ target_compile_options(cua_hyprland_transport PRIVATE -Wall -Wextra -Wpedantic -Werror)+ if(CMAKE_SYSTEM_NAME STREQUAL "Linux")+ target_compile_definitions(cua_hyprland_transport PRIVATE _GNU_SOURCE)+ endif()+ target_include_directories(cua_hyprland_transport PUBLIC include src)+ target_link_libraries(cua_hyprland_transport PUBLIC+ cua_hyprland_protocol+ Threads::Threads)+ cua_hyprland_harden(cua_hyprland_transport)+ set_target_properties(cua_hyprland_transport PROPERTIES POSITION_INDEPENDENT_CODE ON)++ if(BUILD_TESTING)+ add_executable(cua_hyprland_transport_test tests/transport_test.cpp)+ target_compile_options(cua_hyprland_transport_test PRIVATE -Wall -Wextra -Wpedantic -Werror)+ target_link_libraries(cua_hyprland_transport_test PRIVATE cua_hyprland_transport)+ add_test(NAME cua_hyprland_transport_test COMMAND cua_hyprland_transport_test)++ foreach(api_variant IN ITEMS socket1 legacy)+ if(api_variant STREQUAL "socket1")+ set(api_value 1)+ else()+ set(api_value 0)+ endif()+ add_executable(cua_hyprland_plugin_api_${api_variant}_test+ tests/plugin_api_test.cpp+ $<TARGET_OBJECTS:cua_hyprland_plugin_api_${api_variant}_compile_test>)+ target_compile_features(cua_hyprland_plugin_api_${api_variant}_test+ PRIVATE cxx_std_26)+ target_compile_definitions(cua_hyprland_plugin_api_${api_variant}_test+ PRIVATE CUA_HYPRLAND_SOCKET1_API=${api_value})+ target_compile_options(cua_hyprland_plugin_api_${api_variant}_test PRIVATE+ -Wall -Wextra -Wpedantic -Werror -Wno-return-type-c-linkage)+ target_include_directories(cua_hyprland_plugin_api_${api_variant}_test PRIVATE+ tests tests/mock-hyprland include src)+ target_link_libraries(cua_hyprland_plugin_api_${api_variant}_test PRIVATE+ cua_hyprland_transport)+ add_test(NAME cua_hyprland_plugin_api_${api_variant}_test+ COMMAND cua_hyprland_plugin_api_${api_variant}_test)+ endforeach()+ endif()+endif()++if(CUA_HYPRLAND_BUILD_PLUGIN)+ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")+ message(FATAL_ERROR "The Hyprland plugin can only be built on Linux")+ endif()++ find_package(PkgConfig REQUIRED)+ if(CUA_HYPRLAND_EXPECTED_VERSION)+ pkg_check_modules(HYPRLAND REQUIRED IMPORTED_TARGET+ "hyprland=${CUA_HYPRLAND_EXPECTED_VERSION}")+ else()+ pkg_check_modules(HYPRLAND REQUIRED IMPORTED_TARGET hyprland)+ endif()+ message(STATUS "Building against Hyprland headers ${HYPRLAND_VERSION}")++ cua_detect_hyprland_api(cua_hyprland_socket1_api+ "${HYPRLAND_INCLUDE_DIRS}" "${HYPRLAND_CFLAGS_OTHER}")+ if(cua_hyprland_socket1_api STREQUAL "1")+ message(STATUS "Using Hyprland Socket1 status-command API")+ elseif(cua_hyprland_socket1_api STREQUAL "0")+ message(STATUS "Using Hyprland legacy status-command API")+ else()+ message(FATAL_ERROR+ "Hyprland headers expose no supported hyprctl plugin command API")+ endif()++ add_library(cua_hyprland_plugin MODULE src/plugin.cpp)+ target_compile_features(cua_hyprland_plugin PRIVATE cxx_std_26)+ target_compile_definitions(cua_hyprland_plugin PRIVATE+ CUA_HYPRLAND_PLUGIN_VERSION="${PROJECT_VERSION}"+ CUA_HYPRLAND_SOCKET1_API=${cua_hyprland_socket1_api}+ _GNU_SOURCE)+ target_compile_options(cua_hyprland_plugin PRIVATE+ -Wall -Wextra -Wpedantic -Werror -Wno-return-type-c-linkage)+ cua_hyprland_harden(cua_hyprland_plugin)+ target_link_options(cua_hyprland_plugin PRIVATE+ -Wl,-z,relro+ -Wl,-z,now+ -Wl,-z,noexecstack)+ target_link_libraries(cua_hyprland_plugin PRIVATE+ cua_hyprland_transport+ PkgConfig::HYPRLAND+ Threads::Threads)+ set_target_properties(cua_hyprland_plugin PROPERTIES+ CXX_VISIBILITY_PRESET hidden+ PREFIX ""+ OUTPUT_NAME "cua-hyprland-plugin")++ if(NOT CMAKE_READELF)+ message(FATAL_ERROR "readelf is required to verify the plugin C++ runtime")+ endif()+ add_custom_command(TARGET cua_hyprland_plugin POST_BUILD+ COMMAND ${CMAKE_COMMAND}+ -DREADELF=${CMAKE_READELF}+ -DMODULE=$<TARGET_FILE:cua_hyprland_plugin>+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/VerifyRuntime.cmake+ VERBATIM)++ install(TARGETS cua_hyprland_plugin+ LIBRARY DESTINATION lib/cua/hyprland)+endif()diff --git a/libs/cua-driver/hyprland-plugin/README.md b/libs/cua-driver/hyprland-plugin/README.mdnew file mode 100644index 0000000000..739209538f--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/README.md@@ -0,0 +1,213 @@+# Cua Hyprland plugin++This directory is the source of truth for an optional, experimental Hyprland+plugin. The plugin is disabled by default and is not part of the portable Cua+Driver installation. It must be built for the exact Hyprland version that will+load it; a plugin built against another Hyprland ABI must fail closed rather+than attempt to run. Load checks compare Hyprland's full client/server ABI+fingerprint, including the compositor commit and linked Hyprland library+versions, before calling other compositor APIs. The package and validation+record must also match the compiler toolchain because Hyprland passes C+++objects across the plugin API.++The module must dynamically link the C++ runtime used by the compositor. The+build checks its ELF dependencies and rejects a static C++ runtime; a compiler+copied without its runtime libraries can otherwise silently select a static+archive. Do not load a module from a failed build.++The current foundation is discovery-only. It advertises protocol status and+liveness, but it rejects every input mutation with the typed+`background_unavailable` result. Target-addressed mutation remains gated on+successful second-seat spikes and acceptance of the corresponding RFC.+Neither stable Cua Driver `0.23.2` nor nightly provides isolated background+input through this plugin. Here, discovery means negotiation, status, and+liveness; it does not mean application target discovery or input delivery.++This design builds on Dillon DuPont's Hyprland injection prototype. That credit+records the prototype lineage; it does not claim that the prototype or input+mutation support has shipped in Cua Driver.++## Build++Install the Hyprland headers for the exact installed compositor version, plus+CMake 3.30 or newer, Ninja, and the same compiler family and version used to+build Hyprland. The plugin and its libraries use Hyprland's C++26 language+mode. From this directory:++```bash+cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release+cmake --build build+```++For a pinned acceptance build, also set+`-DCUA_HYPRLAND_EXPECTED_VERSION=0.56.2` (or the exact intended pkg-config+version). The build refuses a different header version. The status-command+adapter supports both Hyprland `0.56.2`'s `SHyprCtlCommand` API and the newer+Socket1 API. CMake compile-checks the installed `PluginAPI.hpp` and selects a+declared tier; an unknown command API fails configuration. The probes use+C++26 and repeat on reconfiguration so a header upgrade cannot reuse a cached+tier. Both adapter paths run in the local mock suite. A separate configuration+test checks tier selection, compiler flags, and unsupported headers. Real-header+and live-load evidence remain required on Linux.++On a non-Linux review host, build only the portable protocol, transport shim,+and mocked plugin-API tests:++```bash+cmake -S . -B build -DCUA_HYPRLAND_BUILD_PLUGIN=OFF -DBUILD_TESTING=ON+cmake --build build+ctest --test-dir build --output-on-failure+```++That workflow is not Linux or Hyprland evidence. Release validation must use+the production `SOCK_SEQPACKET`/`SO_PEERCRED` path and real matching Hyprland+headers.++Do not retain or redistribute the resulting module across a Hyprland upgrade.+Rebuild it against the upgraded Hyprland package instead. The local Arch recipe+in `packaging/arch/` installs a version-pinned development package without+changing Hyprland configuration.++## Load, inspect, and unload++Loading is always an explicit operator action. For a local build, substitute+the actual module path emitted by CMake:++```bash+hyprctl plugin load "$PWD/build/cua-hyprland-plugin.so"+hyprctl -j cua:status+hyprctl plugin unload "$PWD/build/cua-hyprland-plugin.so"+```++For the Arch development package, use:++```bash+hyprctl plugin load /usr/lib/cua/hyprland/cua-hyprland-plugin.so+hyprctl -j cua:status+hyprctl plugin unload /usr/lib/cua/hyprland/cua-hyprland-plugin.so+```++Do not add a `plugin =` line to Hyprland configuration until the ABI match and+status output have been checked in a disposable session. A mismatched module+may be refused by Hyprland or fail during load. If load fails after a Hyprland+upgrade, leave it unloaded, rebuild against the new exact package, and retry.+The portable driver remains available without this plugin.++`hyprctl -j cua:status` is the authoritative runtime status surface. Consumers+must check its compositor epoch, protocol version, advertised capabilities,+socket path, discovery-only state, and ABI identity before connecting. A loaded+module alone is not evidence that target discovery or mutation is available.++The local transport is also disabled by default. To exercise negotiation in a+disposable session, set the following and reload the configuration after the+plugin loads. For Omarchy's Lua configuration, add:++```lua+hl.config({plugin = {cua = {enabled = true}}})+```++For a legacy Hyprland configuration, use:++```text+plugin:cua:enabled = true+```++Run `hyprctl reload` after editing the configuration. The plugin reconciles+transport state on config reload; a runtime `hyprctl eval` or `keyword` alone+does not start or stop it. To disable the transport, remove the setting or set+it to false in the configuration and reload. Unloading the plugin also closes+the socket and every connection immediately.++This enables same-user status and liveness packets only. It does not enable+pointer, keyboard, scroll, drag, target discovery, or another input route.++## Security boundary++- The socket lives at+ `$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/cua-inject-v2.sock` for+ the current Hyprland instance, not in a global temporary directory, and is+ created with mode `0600`.+- The server verifies `SO_PEERCRED` and accepts only peers with the compositor+ user's UID. This authenticates only the local Unix user, not a particular Cua+ process. Filesystem permissions are defense in depth, not authorization.+- Same-UID discovery is acceptable for this mutation-free foundation. Mutation+ capabilities stay disabled until the RFC defines an operator authorization,+ credential or lease lifetime, revocation, and replay-resistant binding to the+ negotiated compositor epoch.+- The transport is bounded, nonblocking Unix `SOCK_SEQPACKET`; oversized,+ truncated, malformed, or unsupported packets are rejected without mutation.+- A client must complete `HELLO` within five seconds. A negotiated client must+ send traffic such as `PING` at least once per minute or the plugin closes the+ idle connection; long-lived driver processes must reconnect and renegotiate.+- Future target handles must be opaque tokens scoped to one compositor epoch.+ Clients must discard them when the epoch changes and must not infer window+ identity from token contents. The discovery-only build issues no target+ handles.+- Protocol capabilities are negotiated explicitly. Absence of a capability is+ a refusal, never permission to try a weaker route.+- The plugin never redirects a target-addressed request to the primary seat,+ focused window, pointer location, or another target.+- A transport acknowledgement proves only receipt and validation. Application+ behavior requires a separate typed result and independent state evidence.++The wire contract is documented in `protocol/cua-inject-v2.md`.++## Relationship to current Hyprland support++Existing Cua Driver paths for capture, target identity, foreground input, and+AT-SPI semantic actions are separate from this plugin. A semantic action can+sometimes update a background application's accessibility object without raw+pointer or keyboard synthesis; that does not prove isolated synthetic input.++Validate stock Cua Driver `0.23.2` desktop capture, window enumeration,+foreground actions, and AT-SPI actions separately. Available protocols and+accessibility services establish prerequisites; successful actions require+application-state evidence. The host Hyprland/plugin ABI pair, plugin transport,+opaque target binding, and isolated raw background input each require their+own acceptance evidence on the exact host and candidate module.++Compositor administration also remains explicit. Integrations may invoke+`hyprctl` for an operator-requested workspace, monitor, window-rule, focus, or+DPMS operation, but a Cua background action must never hide a target-delivery+failure by changing compositor state. DPMS-on is a precondition for visual+delivery evidence; an all-black frame while DPMS is off is not success.++`hyprctl` is the compositor administration and plugin status boundary. The+plugin adds `hyprctl -j cua:status`, but it does not turn arbitrary `hyprctl`+commands into application-targeted input or application-delivery proof. Tests+must observe whether the stock foreground route explicitly activated a window+and must keep that behavior separate from plugin mutation, which remains+disabled.++Application enumeration and call authorization also stay in Cua Driver.+Filtering `list_apps`, choosing a one-shot `cua-driver call` versus a long-lived+`cua-driver serve` process, and enforcing per-call capability or policy rules+are not plugin capabilities. The plugin authenticates and negotiates its local+protocol; it does not replace the driver's tool policy or process lifecycle.++## Acceptance path++Promotion beyond discovery requires focused protocol and security tests, Fleet+image packaging and lifecycle tests, and the repository's representative Linux+catalogs. The final gate is a physical Omarchy machine running the exact+candidate Hyprland/plugin pair, with focus, z-order, cursor, input-isolation,+and fixture-state evidence. VM or Fleet evidence supplements but does not+replace that physical gate, which must run after the Fleet lane passes.++The exact initial host acceptance baseline is:++| Component | Required baseline |+| --------------------------- | ----------------- |+| Omarchy | `4.0.2-1` |+| Hyprland | `0.56.2` |+| xdg-desktop-portal-hyprland | `1.4.1` |+| Cua Driver | `0.23.2` |+| Session and display manager | UWSM / SDDM |++This baseline is an acceptance target, not a statement that the reported host+or its Hyprland/plugin ABI pair has passed validation. It is also not a claim+that isolated background input ships in stable `0.23.2` or nightly. The plugin+remains discovery-only. The final physical run has explicit foreground+activation observation, GTK3, GTK4, Qt6, LibreOffice, Chromium/Ozone, Electron,+DPMS-off refusal, and one-shot and long-lived graphical-session client rows;+see `tests/README.md` for the required evidence.diff --git a/libs/cua-driver/hyprland-plugin/cmake/DetectHyprlandAPI.cmake b/libs/cua-driver/hyprland-plugin/cmake/DetectHyprlandAPI.cmakenew file mode 100644index 0000000000..dbf8c7fb3d--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/cmake/DetectHyprlandAPI.cmake@@ -0,0 +1,29 @@+include(CheckCXXSourceCompiles)++function(cua_detect_hyprland_api output includes flags)+ # Probes must use the module's language mode; function scope preserves the+ # caller's try-compile settings, including settings that were unset.+ set(CMAKE_CXX_STANDARD 26)+ set(CMAKE_CXX_STANDARD_REQUIRED ON)+ set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)+ set(CMAKE_REQUIRED_INCLUDES ${includes})+ string(JOIN " " CMAKE_REQUIRED_FLAGS ${flags})+ # Reconfigure after a header upgrade must not reuse a previous ABI tier.+ unset(CUA_HYPRLAND_HAS_SOCKET1_STATUS_API CACHE)+ unset(CUA_HYPRLAND_HAS_LEGACY_STATUS_API CACHE)+ check_cxx_source_compiles(+ "#include <src/plugins/PluginAPI.hpp>\nint main() { IPC::Socket1::SCommand command{}; (void)command; }"+ CUA_HYPRLAND_HAS_SOCKET1_STATUS_API)+ if(CUA_HYPRLAND_HAS_SOCKET1_STATUS_API)+ set(${output} 1 PARENT_SCOPE)+ return()+ endif()+ check_cxx_source_compiles(+ "#include <src/plugins/PluginAPI.hpp>\nint main() { SHyprCtlCommand command{}; (void)command; }"+ CUA_HYPRLAND_HAS_LEGACY_STATUS_API)+ if(CUA_HYPRLAND_HAS_LEGACY_STATUS_API)+ set(${output} 0 PARENT_SCOPE)+ else()+ set(${output} unsupported PARENT_SCOPE)+ endif()+endfunction()diff --git a/libs/cua-driver/hyprland-plugin/cmake/VerifyRuntime.cmake b/libs/cua-driver/hyprland-plugin/cmake/VerifyRuntime.cmakenew file mode 100644index 0000000000..78b91d9fcb--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/cmake/VerifyRuntime.cmake@@ -0,0 +1,11 @@+execute_process(COMMAND "${CMAKE_COMMAND}" -E env LC_ALL=C "${READELF}" -d "${MODULE}"+ RESULT_VARIABLE result OUTPUT_VARIABLE dynamic ERROR_VARIABLE error)+if(NOT result EQUAL 0)+ message(FATAL_ERROR "Cannot inspect module runtime dependencies: ${error}")+endif()+# A partially staged GCC toolchain can silently select libstdc++.a. Its C+++# globals must not be embedded into a module loaded by another C++ process.+if(NOT dynamic MATCHES "Shared library: \\[(libstdc\\+\\+|libc\\+\\+)\\.so")+ message(FATAL_ERROR+ "Plugin lacks a shared C++ runtime dependency. Check the compiler's runtime search paths; do not load this module.")+endif()diff --git a/libs/cua-driver/hyprland-plugin/include/cua_hyprland/protocol.hpp b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/protocol.hppnew file mode 100644index 0000000000..e2c0769f11--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/protocol.hpp@@ -0,0 +1,118 @@+#pragma once++#include <array>+#include <cstddef>+#include <cstdint>+#include <span>+#include <string>+#include <variant>+#include <vector>++namespace cua::hyprland {++constexpr std::array<std::byte, 4> kMagic{+ std::byte{'C'}, std::byte{'U'}, std::byte{'A'}, std::byte{'2'}};+constexpr std::uint16_t kProtocolMajor = 2;+constexpr std::uint16_t kProtocolMinor = 0;+constexpr std::size_t kHeaderSize = 24;+constexpr std::size_t kMaxPayloadSize = 4096;+constexpr std::size_t kMaxFrameSize = kHeaderSize + kMaxPayloadSize;++enum class MessageType : std::uint16_t {+ hello = 1,+ welcome = 2,+ ping = 3,+ pong = 4,+ status_request = 5,+ status_response = 6,+ pointer_motion = 0x100,+ pointer_button = 0x101,+ pointer_axis = 0x102,+ pointer_drag = 0x103,+ keyboard_key = 0x110,+ keyboard_text = 0x111,+ error = 0xffff,+};++enum class Capability : std::uint64_t {+ discovery = 1ULL << 0,+ pointer_motion = 1ULL << 1,+ pointer_button = 1ULL << 2,+ pointer_axis = 1ULL << 3,+ pointer_drag = 1ULL << 4,+ keyboard_key = 1ULL << 5,+ keyboard_text = 1ULL << 6,+ observation = 1ULL << 7,+};++constexpr std::uint64_t capability(Capability value) {+ return static_cast<std::uint64_t>(value);+}++enum class ErrorCode : std::uint32_t {+ malformed_frame = 1,+ unsupported_version = 2,+ handshake_required = 3,+ capability_unavailable = 4,+ permission_denied = 5,+ stale_epoch = 6,+ server_busy = 7,+ background_unavailable = 8,+};++struct Header {+ std::uint16_t major = kProtocolMajor;+ std::uint16_t minor = kProtocolMinor;+ MessageType type = MessageType::error;+ std::uint16_t flags = 0;+ std::uint64_t request_id = 0;+ std::uint32_t payload_size = 0;+};++struct Frame {+ Header header;+ std::vector<std::byte> payload;+};++struct Hello {+ std::uint64_t requested_capabilities = 0;+ std::uint64_t required_capabilities = 0;+};++struct Welcome {+ std::uint64_t compositor_epoch = 0;+ std::uint64_t supported_capabilities = 0;+ std::uint64_t enabled_capabilities = 0;+ std::uint32_t max_frame_size = static_cast<std::uint32_t>(kMaxFrameSize);+};++struct ProtocolError {+ ErrorCode code = ErrorCode::malformed_frame;+ std::string detail;+};++enum class DecodeError {+ frame_too_small,+ bad_magic,+ unsupported_version,+ nonzero_flags,+ payload_too_large,+ size_mismatch,+ malformed_payload,+};++std::vector<std::byte> encode_frame(const Frame& frame);+std::variant<Frame, DecodeError> decode_frame(std::span<const std::byte> bytes);++std::vector<std::byte> encode_hello(const Hello& hello);+std::variant<Hello, DecodeError> decode_hello(std::span<const std::byte> payload);+std::vector<std::byte> encode_welcome(const Welcome& welcome);+std::variant<Welcome, DecodeError> decode_welcome(std::span<const std::byte> payload);+std::vector<std::byte> encode_error(const ProtocolError& error);+std::variant<ProtocolError, DecodeError> decode_error(std::span<const std::byte> payload);++Frame make_frame(MessageType type, std::uint64_t request_id,+ std::vector<std::byte> payload = {});+Frame make_error(std::uint64_t request_id, ErrorCode code, std::string detail);++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/include/cua_hyprland/session.hpp b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/session.hppnew file mode 100644index 0000000000..083bbab589--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/session.hpp@@ -0,0 +1,25 @@+#pragma once++#include "cua_hyprland/protocol.hpp"++#include <cstdint>++namespace cua::hyprland {++struct ServerInfo {+ std::uint64_t compositor_epoch = 0;+ std::uint64_t supported_capabilities = capability(Capability::discovery);+ std::uint64_t enabled_capabilities = capability(Capability::discovery);+};++class Session {+ public:+ Frame handle(const Frame& request, const ServerInfo& server);+ bool handshaken() const;++ private:+ bool m_handshaken = false;+ std::uint64_t m_negotiated_capabilities = 0;+};++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/include/cua_hyprland/status.hpp b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/status.hppnew file mode 100644index 0000000000..d560257895--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/include/cua_hyprland/status.hpp@@ -0,0 +1,31 @@+#pragma once++#include <cstdint>+#include <string>+#include <string_view>++namespace cua::hyprland {++struct StatusReport {+ std::string_view plugin_version{};+ std::uint64_t compositor_epoch = 0;+ std::string_view compiled_hash{};+ std::string_view runtime_hash{};+ bool configured = false;+ bool transport_ready = false;+ std::string_view socket_path{};+ std::string_view last_error{};+ bool discovery_enabled = false;+ std::uint64_t accepted_connections = 0;+ std::uint64_t rejected_peers = 0;+ std::uint64_t rejected_busy = 0;+ std::uint64_t timed_out_handshakes = 0;+ std::uint64_t timed_out_idle = 0;+ std::uint64_t malformed_frames = 0;+};++bool is_valid_utf8(std::string_view value);+std::string render_status_json(const StatusReport& report);+std::string render_status_text(const StatusReport& report);++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/packaging/arch/PKGBUILD b/libs/cua-driver/hyprland-plugin/packaging/arch/PKGBUILDnew file mode 100644index 0000000000..52aaa8cc17--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/packaging/arch/PKGBUILD@@ -0,0 +1,64 @@+# Local-development recipe. Build only from an explicit Cua monorepo checkout.+# shellcheck shell=bash disable=SC2034,SC2154+pkgname=cua-hyprland-plugin-local+pkgver=0.1.0+pkgrel=1+pkgdesc='Discovery-only Cua integration for an exact local Hyprland ABI'+arch=('x86_64' 'aarch64')+url='https://github.com/trycua/cua'+license=('MIT')+makedepends=('cmake' 'ninja' 'pkgconf' 'binutils')+options=('!strip' '!debug' '!lto')+source=()+sha256sums=()++: "${CUA_SOURCE_ROOT:?Set CUA_SOURCE_ROOT to the Cua monorepo root}"+: "${CUA_HYPRLAND_PACKAGE_VERSION:?Set CUA_HYPRLAND_PACKAGE_VERSION to the exact pacman package version}"+_source_root="$(realpath -e -- "$CUA_SOURCE_ROOT")"+_plugin_source="${_source_root}/libs/cua-driver/hyprland-plugin"+_hyprland_package_version="$CUA_HYPRLAND_PACKAGE_VERSION"+_hyprland_header_version="${CUA_HYPRLAND_HEADER_VERSION:-0.56.2}"+depends=("hyprland=${_hyprland_package_version}")++prepare() {+ [[ -f "${_plugin_source}/CMakeLists.txt" ]] || {+ printf 'error: CUA_SOURCE_ROOT does not contain the Hyprland plugin source\n' >&2+ return 1+ }++ local installed_hyprland+ installed_hyprland="$(LC_ALL=C pacman -Q hyprland 2>/dev/null | cut -d' ' -f2-)"+ [[ "$installed_hyprland" == "$_hyprland_package_version" ]] || {+ printf 'error: expected hyprland package %s, found %s\n' \+ "$_hyprland_package_version" "${installed_hyprland:-not installed}" >&2+ return 1+ }++ local header_version+ header_version="$(pkg-config --modversion hyprland 2>/dev/null)"+ [[ "$header_version" == "$_hyprland_header_version" ]] || {+ printf 'error: expected hyprland headers %s, found %s\n' \+ "$_hyprland_header_version" "${header_version:-not installed}" >&2+ return 1+ }+}++build() {+ cmake \+ -S "$_plugin_source" \+ -B "$srcdir/build" \+ -G Ninja \+ -DCMAKE_BUILD_TYPE=Release \+ -DCUA_HYPRLAND_EXPECTED_VERSION="$_hyprland_header_version"+ cmake --build "$srcdir/build"+}++check() {+ ctest --test-dir "$srcdir/build" --output-on-failure+}++package() {+ DESTDIR="$pkgdir" cmake --install "$srcdir/build" --prefix /usr+ install -Dm644 "$_source_root/LICENSE.md" \+ "$pkgdir/usr/share/licenses/$pkgname/LICENSE"+}diff --git a/libs/cua-driver/hyprland-plugin/packaging/arch/README.md b/libs/cua-driver/hyprland-plugin/packaging/arch/README.mdnew file mode 100644index 0000000000..f8b10d95aa--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/packaging/arch/README.md@@ -0,0 +1,57 @@+# Arch local-development package++This recipe builds the optional plugin directly from a Cua monorepo checkout.+It is intentionally unsuitable for an AUR or binary repository: there is no+remote source archive, checksum substitution, or promise of ABI compatibility+with another machine.++Install the exact Hyprland package and development files used by the running+Omarchy/Arch session. Point `CUA_SOURCE_ROOT` at the monorepo root and pass the+full package version reported by pacman; the package release suffix is part of+the pin and must not be guessed:++```bash+export CUA_SOURCE_ROOT=/path/to/cua+export CUA_HYPRLAND_PACKAGE_VERSION="$(pacman -Q hyprland | cut -d' ' -f2-)"+export CUA_HYPRLAND_HEADER_VERSION=0.56.2+makepkg -si+```++The recipe requires that exact installed package version and the exact+pkg-config header version, records the package dependency, builds from+`$CUA_SOURCE_ROOT/libs/cua-driver/hyprland-plugin`, runs the configured CTest+suite during `check()`, and installs only:++```text+/usr/lib/cua/hyprland/cua-hyprland-plugin.so+/usr/share/licenses/cua-hyprland-plugin-local/LICENSE+```++It does not edit Hyprland configuration or load the plugin. Load, check, and+unload it explicitly:++```bash+hyprctl plugin load /usr/lib/cua/hyprland/cua-hyprland-plugin.so+hyprctl -j cua:status+hyprctl plugin unload /usr/lib/cua/hyprland/cua-hyprland-plugin.so+```++After every Hyprland upgrade, remove or rebuild this local package before+loading it again. An exact dependency conflict is intentional protection+against carrying a stale compositor ABI module forward.++This is deliberately a monorepo-local development recipe, not an AUR or clean+chroot source package. Fleet must make the recorded candidate source available+at `CUA_SOURCE_ROOT` and record its Git SHA. Build with the same compiler family+and version used for Hyprland; matching the package, headers, full Hyprland ABI+fingerprint, and C++26 language mode does not make different C++ toolchains+interchangeable.++Fleet images should consume this same monorepo recipe or a derived reviewed+recipe, pin the image's exact Hyprland package, and keep the plugin unloaded by+default. The initial acceptance image must match Omarchy `4.0.2-1`, Hyprland+`0.56.2`, xdg-desktop-portal-hyprland `1.4.1`, Cua Driver `0.23.2`, and a+UWSM/SDDM session. This packages a discovery-only plugin; isolated background+input is not available in stable `0.23.2` or nightly. See+`../../tests/README.md` for the required Fleet and subsequent bare-metal+promotion evidence.diff --git a/libs/cua-driver/hyprland-plugin/protocol/cua-inject-v2.md b/libs/cua-driver/hyprland-plugin/protocol/cua-inject-v2.mdnew file mode 100644index 0000000000..062100cadf--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/protocol/cua-inject-v2.md@@ -0,0 +1,181 @@+# Cua Hyprland injection protocol v2++## Status and scope++This document defines the local protocol used by the optional Cua Hyprland+plugin. The monorepo copy is authoritative. The current v2 foundation exposes+status, negotiation, and liveness only. It advertises the `discovery`+capability and rejects every input message with typed+`background_unavailable`.++Target-bound input remains gated on the second-seat compatibility spikes and+acceptance of the governing RFC. The separate-seat design originates in Dillon+DuPont's Hyprland prototype; this records its lineage without claiming that the+prototype or mutation support has shipped in Cua Driver.++## Runtime discovery++The plugin publishes runtime metadata through:++```bash+hyprctl -j cua:status+```++The current JSON object contains:++| Field | Meaning |+| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `name` | `cua-hyprland-plugin`. |+| `plugin_version` | Plugin package version. |+| `state` | `discovery_only` in the current foundation. |+| `protocol.major`, `protocol.minor` | Wire protocol version. |+| `protocol.max_frame_bytes` | Maximum complete packet size. |+| `compositor_epoch` | Nonzero identifier for the current live plugin transport binding, or zero when no transport is ready. It changes after disable/enable and plugin/compositor restart. |+| `abi.compiled_hash` | Full Hyprland client ABI fingerprint from the build headers: compositor commit plus linked Hyprland library versions. |+| `abi.runtime_hash` | Full ABI fingerprint exported by the running compositor. |+| `abi.match` | Always true for a loaded instance; mismatch aborts load. |+| `configured` | Whether `plugin:cua:enabled` is true. |+| `transport` | Socket readiness, path, permission policy, and last error. |+| `capabilities` | Supported and currently enabled capability names. |+| `connections` | Bounded diagnostic counters with no application data. |++The plugin throws during initialization when the build and runtime Hyprland+hashes differ. In that case no command, socket, or capability remains+registered.++## Transport and peer authorization++The transport is a Unix-domain `SOCK_SEQPACKET` socket at+`$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/cua-inject-v2.sock`. It is+created only when `plugin:cua:enabled` is true.++Before binding, the plugin verifies that `XDG_RUNTIME_DIR`, its `hypr`+directory, and the current instance directory pathnames resolve to directories+owned by the compositor UID with no group or other permission bits; each of+those three final pathnames is rejected when it is itself a symlink. The final+socket inode is mode `0600`.++Immediately after `accept4`, the server reads `SO_PEERCRED`. The peer UID must+equal the compositor process UID. Missing credentials or a UID mismatch closes+the connection before a request is processed. This authenticates the local Unix+user but does not distinguish Cua from another process owned by that user.+Filesystem permissions are defense in depth, not authorization. The current+transport exposes no mutation. Before mutation capabilities can be enabled, the+governing RFC must define operator authorization, credential or lease lifetime,+revocation, and replay-resistant binding to the compositor epoch.++The server uses a dedicated bounded I/O thread. That thread never calls+Hyprland or Wayland APIs. It accepts at most eight concurrent clients and one+packet per ready client per polling pass. A client must send `HELLO` within five+seconds or the server closes it, preventing silent clients from holding all+connection slots. A negotiated client must send traffic such as `PING` at least+once per minute; the server closes an idle connection after 60 seconds. A wake+event interrupts the I/O poll so shutdown can join the worker thread promptly.+Mutation work, when added, must cross a separate bounded queue and execute on+the compositor event loop.++The server refuses a pre-existing socket path and records the device and inode+of the path it bound. On shutdown it unlinks only when the current path still+matches that identity. It never replaces or unlinks an unowned object.++## Packet envelope++Every `SOCK_SEQPACKET` packet contains one binary frame in network byte order.+There is no stream reassembly and no JSON parser on the compositor boundary.++| Offset | Size | Field |+| -----: | -------: | ------------------------------------ |+| 0 | 4 | ASCII magic `CUA2` |+| 4 | 2 | Protocol major, currently `2` |+| 6 | 2 | Protocol minor, currently `0` |+| 8 | 2 | Message type |+| 10 | 2 | Flags, currently required to be zero |+| 12 | 8 | Client-selected request ID |+| 20 | 4 | Payload length |+| 24 | variable | Message payload, at most 4096 bytes |++The maximum complete frame is 4120 bytes. The receiver rejects bad magic,+unsupported versions, nonzero flags, oversized payloads, and any packet whose+actual size does not exactly match the declared payload length.++## Handshake and liveness++`HELLO` (`0x0001`) must be the first message. Its 16-byte payload contains a+requested capability bitset followed by a required capability bitset. A+required capability that is not enabled returns `capability_unavailable` and+does not establish the session.++Successful negotiation returns `WELCOME` (`0x0002`) with this 32-byte payload:++| Offset | Size | Field |+| -----: | ---: | ------------------------------------------- |+| 0 | 8 | Compositor epoch |+| 8 | 8 | Capabilities supported by this server build |+| 16 | 8 | Capabilities enabled for this session |+| 24 | 4 | Maximum complete frame size |+| 28 | 4 | Reserved zero |++After negotiation, `PING` (`0x0003`) receives a correlated empty `PONG`+(`0x0004`). `STATUS_REQUEST` (`0x0005`) receives `STATUS_RESPONSE` (`0x0006`)+with the same payload shape as `WELCOME`.++The epoch is regenerated whenever the transport socket is created. Clients+must discard cached state after disconnect and accept target or capability+state only after a new `HELLO`/`WELCOME` exchange.++## Capabilities and mutation messages++Capability bits are stable within protocol v2:++| Bit | Name | Current behavior |+| --: | ---------------- | ---------------------------------------------- |+| 0 | `discovery` | Negotiation, status, and liveness are enabled. |+| 1 | `pointer_motion` | Not enabled. |+| 2 | `pointer_button` | Not enabled. |+| 3 | `pointer_axis` | Not enabled. |+| 4 | `pointer_drag` | Not enabled. |+| 5 | `keyboard_key` | Not enabled. |+| 6 | `keyboard_text` | Not enabled. |+| 7 | `observation` | Not enabled. |++The defined mutation message types are `0x0100` through `0x0103` and `0x0110`+through `0x0111`. The current server returns `background_unavailable` for each+of them. Other values in the reserved `0x0100` through `0x0111` range remain+undefined and return `malformed_frame`, as do server-only message types received+from a client. The server never reinterprets a request, changes focus, selects+the focused window, uses pointer-position routing, or falls back to the primary+seat.++Future target-bound mutation payloads must include the compositor epoch and an+opaque target token. Tokens must not expose a pointer, object address, Wayland+object ID, PID, or reusable ordering. A token becomes invalid immediately when+its target is destroyed or the epoch changes.++## Error payload++`ERROR` (`0xffff`) contains a four-byte numeric error code followed by a bounded+UTF-8 detail string. Detail is diagnostic only; clients branch on the code.++| Code | Name | Meaning |+| ---: | ------------------------ | ------------------------------------------------- |+| 1 | `malformed_frame` | Framing or payload validation failed. |+| 2 | `unsupported_version` | The major/minor pair is not supported. |+| 3 | `handshake_required` | A message arrived before `HELLO`. |+| 4 | `capability_unavailable` | A required capability is not enabled. |+| 5 | `permission_denied` | The authenticated peer lacks permission. |+| 6 | `stale_epoch` | A future target/action references another epoch. |+| 7 | `server_busy` | A bounded connection or work budget is exhausted. |+| 8 | `background_unavailable` | Target-bound mutation is unavailable. |++Connection loss and `server_busy` are transport outcomes, not proof of+application behavior. Even a future successful mutation result will mean only+that the compositor completed its defined dispatch path. Cua Driver and the+desktop harness must use independent application-state, focus, z-order,+workspace, cursor, and input-leak oracles.++## Versioning++Changes to framing, peer authorization, epoch or token lifetime, result+meaning, or operation semantics require a new protocol major version. Additive+capabilities may remain in v2 only when their absence is safe and every client+must explicitly negotiate them. Neither side may downgrade silently.diff --git a/libs/cua-driver/hyprland-plugin/src/inject_server.cpp b/libs/cua-driver/hyprland-plugin/src/inject_server.cppnew file mode 100644index 0000000000..5eda47ccab--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/inject_server.cpp@@ -0,0 +1,509 @@+#include "inject_server.hpp"++#include "cua_hyprland/protocol.hpp"++#include <array>+#include <cerrno>+#include <chrono>+#include <cstring>+#include <fcntl.h>+#include <poll.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/un.h>+#include <unistd.h>+#include <vector>++namespace cua::hyprland {+namespace {++constexpr std::size_t kMaxClients = 8;+constexpr std::size_t kMaxAcceptsPerPoll = 16;+constexpr int kPollTimeoutMs = 100;+constexpr auto kAcceptResourceBackoff = std::chrono::milliseconds{250};++struct Client {+ int fd = -1;+ Session session{};+ std::chrono::steady_clock::time_point accepted_at;+ std::chrono::steady_clock::time_point last_activity;+};++void close_client(Client& client) {+ if (client.fd >= 0)+ close(client.fd);+ client.fd = -1;+}++bool peer_is_owner(int fd) {+#ifdef __linux__+ ucred credentials{};+ socklen_t size = sizeof(credentials);+ if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &size) != 0)+ return false;+ return size == sizeof(credentials) && credentials.uid == getuid();+#else+ uid_t effective_uid = 0;+ gid_t effective_gid = 0;+ return getpeereid(fd, &effective_uid, &effective_gid) == 0 &&+ effective_uid == getuid();+#endif+}++#ifndef __linux__+bool set_nonblocking_cloexec(int fd) {+ const auto descriptor_flags = fcntl(fd, F_GETFD);+ const auto status_flags = fcntl(fd, F_GETFL);+ return descriptor_flags >= 0 && status_flags >= 0 &&+ fcntl(fd, F_SETFD, descriptor_flags | FD_CLOEXEC) == 0 &&+ fcntl(fd, F_SETFL, status_flags | O_NONBLOCK) == 0;+}+#endif++int create_socket() {+#ifdef __linux__+ return socket(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);+#else+ // The plugin only builds on Linux. SOCK_STREAM keeps the transport harness+ // executable on Unix hosts that do not implement AF_UNIX SOCK_SEQPACKET.+ constexpr int socket_type = SOCK_STREAM;+ const auto fd = socket(AF_UNIX, socket_type, 0);+ if (fd < 0)+ return -1;+ if (set_nonblocking_cloexec(fd))+ return fd;+ close(fd);+ return -1;+#endif+}++int accept_client(int listen_fd) {+#ifdef __linux__+ return accept4(listen_fd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);+#else+ const auto fd = accept(listen_fd, nullptr, nullptr);+ if (fd < 0)+ return -1;+ if (set_nonblocking_cloexec(fd))+ return fd;+ close(fd);+ errno = EIO;+ return -1;+#endif+}++bool create_wake_pipe(int (&wake_fds)[2]) {+#ifdef __linux__+ return pipe2(wake_fds, O_NONBLOCK | O_CLOEXEC) == 0;+#else+ return pipe(wake_fds) == 0 && set_nonblocking_cloexec(wake_fds[0]) &&+ set_nonblocking_cloexec(wake_fds[1]);+#endif+}++bool send_frame(int fd, const Frame& frame) {+ const auto bytes = encode_frame(frame);+ if (bytes.empty())+ return false;+#ifdef MSG_NOSIGNAL+ constexpr int no_signal = MSG_NOSIGNAL;+#else+ constexpr int no_signal = 0;+#endif+ ssize_t sent = -1;+ do {+ sent = send(fd, bytes.data(), bytes.size(), MSG_DONTWAIT | no_signal);+ } while (sent < 0 && errno == EINTR);+ return sent == static_cast<ssize_t>(bytes.size());+}++std::uint64_t request_id_from_frame_prefix(std::span<const std::byte> bytes) {+ if (bytes.size() < kHeaderSize ||+ !std::equal(kMagic.begin(), kMagic.end(), bytes.begin()))+ return 0;++ std::uint64_t request_id = 0;+ for (std::size_t index = 12; index < 20; ++index)+ request_id =+ (request_id << 8) | std::to_integer<std::uint64_t>(bytes[index]);+ return request_id;+}++ErrorCode protocol_error_for(DecodeError error) {+ return error == DecodeError::unsupported_version ?+ ErrorCode::unsupported_version :+ ErrorCode::malformed_frame;+}++bool is_accept_resource_error(int error) {+ return error == EMFILE || error == ENFILE || error == ENOBUFS ||+ error == ENOMEM;+}++} // namespace++InjectionServer::InjectionServer(std::string socket_path, ServerInfo info,+ ServerOptions options)+ : m_socket_path(std::move(socket_path)), m_info(info), m_options(options) {}++InjectionServer::~InjectionServer() {+ stop();+}++bool InjectionServer::start() {+ if (m_running.load())+ return true;+ if (m_thread.joinable() || m_listen_fd >= 0 || m_wake_read_fd >= 0 ||+ m_wake_write_fd >= 0 || m_owns_socket)+ stop();+ set_error({});++ sockaddr_un address{};+ address.sun_family = AF_UNIX;+ if (m_socket_path.size() >= sizeof(address.sun_path)) {+ set_error("socket path exceeds sockaddr_un capacity");+ return false;+ }++ struct stat existing{};+ if (lstat(m_socket_path.c_str(), &existing) == 0) {+ set_error("socket path already exists");+ return false;+ }+ if (errno != ENOENT) {+ set_error(std::string{"cannot inspect socket path: "} + std::strerror(errno));+ return false;+ }++ m_listen_fd = create_socket();+ if (m_listen_fd < 0) {+ set_error(std::string{"cannot create socket: "} + std::strerror(errno));+ return false;+ }+ int wake_fds[2] = {-1, -1};+ if (!create_wake_pipe(wake_fds)) {+ set_error(std::string{"cannot create wake event: "} + std::strerror(errno));+ if (wake_fds[0] >= 0)+ close(wake_fds[0]);+ if (wake_fds[1] >= 0)+ close(wake_fds[1]);+ close(m_listen_fd);+ m_listen_fd = -1;+ return false;+ }+ m_wake_read_fd = wake_fds[0];+ m_wake_write_fd = wake_fds[1];++ std::strncpy(address.sun_path, m_socket_path.c_str(), sizeof(address.sun_path) - 1);+ if (bind(m_listen_fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0) {+ set_error(std::string{"cannot bind socket: "} + std::strerror(errno));+ close(m_listen_fd);+ m_listen_fd = -1;+ close(m_wake_read_fd);+ close(m_wake_write_fd);+ m_wake_read_fd = -1;+ m_wake_write_fd = -1;+ return false;+ }++ struct stat path_metadata{};+ if (lstat(m_socket_path.c_str(), &path_metadata) != 0 ||+ !S_ISSOCK(path_metadata.st_mode) || path_metadata.st_uid != getuid()) {+ set_error("cannot verify ownership of bound socket path");+ close(m_listen_fd);+ m_listen_fd = -1;+ close(m_wake_read_fd);+ close(m_wake_write_fd);+ m_wake_read_fd = -1;+ m_wake_write_fd = -1;+ return false;+ }+ m_owns_socket = true;+ m_socket_device = path_metadata.st_dev;+ m_socket_inode = path_metadata.st_ino;+ if (chmod(m_socket_path.c_str(), S_IRUSR | S_IWUSR) != 0) {+ set_error(std::string{"cannot restrict socket permissions: "} ++ std::strerror(errno));+ close(m_listen_fd);+ m_listen_fd = -1;+ close(m_wake_read_fd);+ close(m_wake_write_fd);+ m_wake_read_fd = -1;+ m_wake_write_fd = -1;+ remove_owned_socket();+ return false;+ }+ if (listen(m_listen_fd, static_cast<int>(kMaxClients)) != 0) {+ set_error(std::string{"cannot listen on socket: "} + std::strerror(errno));+ close(m_listen_fd);+ m_listen_fd = -1;+ close(m_wake_read_fd);+ close(m_wake_write_fd);+ m_wake_read_fd = -1;+ m_wake_write_fd = -1;+ remove_owned_socket();+ return false;+ }++ m_stop_requested.store(false);+ m_running.store(true);+ try {+ m_thread = std::thread([this] { run(); });+ } catch (const std::exception& error) {+ m_running.store(false);+ set_error(std::string{"cannot start socket thread: "} + error.what());+ close(m_listen_fd);+ m_listen_fd = -1;+ close(m_wake_read_fd);+ close(m_wake_write_fd);+ m_wake_read_fd = -1;+ m_wake_write_fd = -1;+ remove_owned_socket();+ return false;+ }+ return true;+}++void InjectionServer::stop() {+ m_stop_requested.store(true);+ if (m_wake_write_fd >= 0) {+ const std::byte wake{1};+ const auto written = write(m_wake_write_fd, &wake, sizeof(wake));+ if (written < 0 && errno != EAGAIN && errno != EINTR)+ set_error(std::string{"cannot signal socket shutdown: "} ++ std::strerror(errno));+ }+ if (m_thread.joinable())+ m_thread.join();+ if (m_listen_fd >= 0) {+ close(m_listen_fd);+ m_listen_fd = -1;+ }+ if (m_wake_read_fd >= 0) {+ close(m_wake_read_fd);+ m_wake_read_fd = -1;+ }+ if (m_wake_write_fd >= 0) {+ close(m_wake_write_fd);+ m_wake_write_fd = -1;+ }+ remove_owned_socket();+ m_running.store(false);+}++ServerSnapshot InjectionServer::snapshot() const {+ std::lock_guard lock{m_error_mutex};+ return ServerSnapshot{+ .running = m_running.load(),+ .accepted_connections = m_accepted_connections.load(),+ .rejected_peers = m_rejected_peers.load(),+ .rejected_busy = m_rejected_busy.load(),+ .timed_out_handshakes = m_timed_out_handshakes.load(),+ .timed_out_idle = m_timed_out_idle.load(),+ .malformed_frames = m_malformed_frames.load(),+ .last_error = m_last_error,+ };+}++const std::string& InjectionServer::socket_path() const {+ return m_socket_path;+}++void InjectionServer::run() {+ std::vector<Client> clients;+ clients.reserve(kMaxClients);+ auto accept_retry_at = std::chrono::steady_clock::time_point::min();+ bool transport_failed = false;++ while (!m_stop_requested.load()) {+ const auto now = std::chrono::steady_clock::now();+ for (std::size_t index = clients.size(); index > 0; --index) {+ auto& client = clients[index - 1];+ const auto handshake_expired =+ !client.session.handshaken() &&+ now - client.accepted_at >= m_options.handshake_timeout;+ const auto idle_expired =+ client.session.handshaken() &&+ now - client.last_activity >= m_options.idle_timeout;+ if (!handshake_expired && !idle_expired)+ continue;+ close_client(client);+ clients.erase(clients.begin() ++ static_cast<std::ptrdiff_t>(index - 1));+ if (handshake_expired)+ ++m_timed_out_handshakes;+ else+ ++m_timed_out_idle;+ }+ const auto accept_ready = now >= accept_retry_at;+ std::vector<pollfd> poll_fds;+ poll_fds.reserve(2 + clients.size());+ poll_fds.push_back(pollfd{+ .fd = accept_ready ? m_listen_fd : -1,+ .events = POLLIN,+ .revents = 0,+ });+ poll_fds.push_back(pollfd{.fd = m_wake_read_fd, .events = POLLIN, .revents = 0});+ for (const auto& client : clients)+ poll_fds.push_back(pollfd{.fd = client.fd, .events = POLLIN, .revents = 0});++ const auto ready = poll(poll_fds.data(), poll_fds.size(), kPollTimeoutMs);+ if (ready < 0) {+ if (errno == EINTR)+ continue;+ set_error(std::string{"socket poll failed: "} + std::strerror(errno));+ transport_failed = true;+ break;+ }+ if ((poll_fds[1].revents & POLLIN) != 0)+ break;++ if (!poll_fds.empty() && (poll_fds[0].revents & POLLIN) != 0) {+ for (std::size_t accepted = 0; accepted < kMaxAcceptsPerPoll;+ ++accepted) {+ const auto fd = accept_client(m_listen_fd);+ if (fd < 0) {+ const auto accept_error = errno;+ if (accept_error == EINTR)+ continue;+ if (accept_error == EAGAIN || accept_error == EWOULDBLOCK)+ break;+ set_error(std::string{"socket accept failed: "} ++ std::strerror(accept_error));+ if (is_accept_resource_error(accept_error)) {+ accept_retry_at = std::chrono::steady_clock::now() ++ kAcceptResourceBackoff;+ } else {+ transport_failed = true;+ }+ break;+ }+ if (!peer_is_owner(fd)) {+ ++m_rejected_peers;+ close(fd);+ continue;+ }+ if (clients.size() >= kMaxClients) {+ ++m_rejected_busy;+ send_frame(fd, make_error(0, ErrorCode::server_busy,+ "concurrent client limit reached"));+ close(fd);+ continue;+ }+ clients.push_back(Client{+ .fd = fd,+ .accepted_at = std::chrono::steady_clock::now(),+ .last_activity = std::chrono::steady_clock::now(),+ });+ ++m_accepted_connections;+ }+ }++ for (std::size_t index = clients.size(); index > 0; --index) {+ auto& client = clients[index - 1];+ const auto poll_index = index + 1;+ const auto revents = poll_fds.size() > poll_index ?+ poll_fds[poll_index].revents :+ 0;+ const auto terminal_event =+ (revents & (POLLERR | POLLHUP | POLLNVAL)) != 0;+ if ((revents & POLLIN) == 0 && terminal_event) {+ close_client(client);+ clients.erase(clients.begin() + static_cast<std::ptrdiff_t>(index - 1));+ continue;+ }+ if ((revents & POLLIN) == 0)+ continue;++ std::array<std::byte, kMaxFrameSize + 1> buffer{};+ const auto received = recv(client.fd, buffer.data(), buffer.size(),+ MSG_DONTWAIT | MSG_TRUNC);+ if (received < 0 && errno == EINTR)+ continue;+ if (received < 0 &&+ (errno == EAGAIN || errno == EWOULDBLOCK)) {+ if (terminal_event) {+ close_client(client);+ clients.erase(clients.begin() ++ static_cast<std::ptrdiff_t>(index - 1));+ }+ continue;+ }+ if (received <= 0 || static_cast<std::size_t>(received) > kMaxFrameSize) {+ if (received > 0)+ ++m_malformed_frames;+ close_client(client);+ clients.erase(clients.begin() + static_cast<std::ptrdiff_t>(index - 1));+ continue;+ }++ const auto decoded = decode_frame(+ std::span<const std::byte>{buffer.data(), static_cast<std::size_t>(received)});+ if (!std::holds_alternative<Frame>(decoded)) {+ ++m_malformed_frames;+ const auto error = std::get<DecodeError>(decoded);+ const auto response = make_error(+ request_id_from_frame_prefix(std::span<const std::byte>{+ buffer.data(), static_cast<std::size_t>(received)}),+ protocol_error_for(error),+ "invalid cua-inject-v2 frame");+ send_frame(client.fd, response);+ close_client(client);+ clients.erase(clients.begin() + static_cast<std::ptrdiff_t>(index - 1));+ continue;+ }++ client.last_activity = std::chrono::steady_clock::now();+ const auto response = client.session.handle(std::get<Frame>(decoded), m_info);+ if (!send_frame(client.fd, response)) {+ close_client(client);+ clients.erase(clients.begin() + static_cast<std::ptrdiff_t>(index - 1));+ }+ }++ if (transport_failed)+ break;+ }++ m_running.store(false);+ for (auto& client : clients)+ close_client(client);+ if (m_listen_fd >= 0) {+ close(m_listen_fd);+ m_listen_fd = -1;+ }+ remove_owned_socket();+ if (transport_failed && !m_stop_requested.load() && snapshot().last_error.empty())+ set_error("transport thread exited unexpectedly");+}++void InjectionServer::remove_owned_socket() {+ if (!m_owns_socket)+ return;++ struct stat current{};+ if (lstat(m_socket_path.c_str(), ¤t) == 0) {+ if (S_ISSOCK(current.st_mode) && current.st_dev == m_socket_device &&+ current.st_ino == m_socket_inode) {+ if (unlink(m_socket_path.c_str()) != 0 && errno != ENOENT)+ set_error(std::string{"cannot remove owned socket: "} ++ std::strerror(errno));+ } else {+ set_error("socket path identity changed; refusing to unlink it");+ }+ } else if (errno != ENOENT) {+ set_error(std::string{"cannot inspect owned socket during cleanup: "} ++ std::strerror(errno));+ }++ m_owns_socket = false;+ m_socket_device = 0;+ m_socket_inode = 0;+}++void InjectionServer::set_error(std::string error) {+ std::lock_guard lock{m_error_mutex};+ m_last_error = std::move(error);+}++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/src/inject_server.hpp b/libs/cua-driver/hyprland-plugin/src/inject_server.hppnew file mode 100644index 0000000000..7767a5e090--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/inject_server.hpp@@ -0,0 +1,72 @@+#pragma once++#include "cua_hyprland/session.hpp"++#include <atomic>+#include <chrono>+#include <cstdint>+#include <mutex>+#include <string>+#include <sys/types.h>+#include <thread>++namespace cua::hyprland {++struct ServerSnapshot {+ bool running = false;+ std::uint64_t accepted_connections = 0;+ std::uint64_t rejected_peers = 0;+ std::uint64_t rejected_busy = 0;+ std::uint64_t timed_out_handshakes = 0;+ std::uint64_t timed_out_idle = 0;+ std::uint64_t malformed_frames = 0;+ std::string last_error;+};++struct ServerOptions {+ std::chrono::milliseconds handshake_timeout{5000};+ std::chrono::milliseconds idle_timeout{60000};+};++class InjectionServer {+ public:+ InjectionServer(std::string socket_path, ServerInfo info,+ ServerOptions options = {});+ ~InjectionServer();++ InjectionServer(const InjectionServer&) = delete;+ InjectionServer& operator=(const InjectionServer&) = delete;++ bool start();+ void stop();+ ServerSnapshot snapshot() const;+ const std::string& socket_path() const;++ private:+ void run();+ void remove_owned_socket();+ void set_error(std::string error);++ std::string m_socket_path;+ ServerInfo m_info;+ ServerOptions m_options;+ int m_listen_fd = -1;+ int m_wake_read_fd = -1;+ int m_wake_write_fd = -1;+ bool m_owns_socket = false;+ dev_t m_socket_device = 0;+ ino_t m_socket_inode = 0;+ std::atomic<bool> m_stop_requested = false;+ std::atomic<bool> m_running = false;+ std::atomic<std::uint64_t> m_accepted_connections = 0;+ std::atomic<std::uint64_t> m_rejected_peers = 0;+ std::atomic<std::uint64_t> m_rejected_busy = 0;+ std::atomic<std::uint64_t> m_timed_out_handshakes = 0;+ std::atomic<std::uint64_t> m_timed_out_idle = 0;+ std::atomic<std::uint64_t> m_malformed_frames = 0;+ mutable std::mutex m_error_mutex;+ std::string m_last_error;+ std::thread m_thread;+};++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/src/plugin.cpp b/libs/cua-driver/hyprland-plugin/src/plugin.cppnew file mode 100644index 0000000000..6a676f6acf--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/plugin.cpp@@ -0,0 +1,295 @@+#include "inject_server.hpp"++#include "cua_hyprland/protocol.hpp"+#include "cua_hyprland/status.hpp"++#include <src/config/values/types/BoolValue.hpp>+#include <src/plugins/PluginAPI.hpp>++#include <cerrno>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <format>+#include <memory>+#include <random>+#include <stdexcept>+#include <string>+#include <string_view>+#include <sys/stat.h>+#include <unistd.h>++#ifdef __linux__+#include <sys/random.h>+#endif++#ifndef CUA_HYPRLAND_SOCKET1_API+#error CMake must select a supported Hyprland command API+#endif++namespace {++constexpr auto kPluginVersion = CUA_HYPRLAND_PLUGIN_VERSION;+constexpr auto kSocketName = "cua-inject-v2.sock";++SP<Config::Values::CBoolValue> g_enabled;+#if CUA_HYPRLAND_SOCKET1_API+SP<IPC::Socket1::SCommand> g_status_command;+#else+SP<SHyprCtlCommand> g_status_command;+#endif+CHyprSignalListener g_config_listener;+std::unique_ptr<cua::hyprland::InjectionServer> g_server;+std::string g_compiled_abi_hash;+std::string g_runtime_abi_hash;+std::uint64_t g_epoch = 0;+std::string g_socket_path;+std::string g_reconcile_error;++bool safe_instance_signature(const std::string& signature) {+ if (signature.empty())+ return false;+ for (const auto character : signature) {+ const auto value = static_cast<unsigned char>(character);+ const auto ascii_alphanumeric =+ (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z') ||+ (value >= '0' && value <= '9');+ if (!ascii_alphanumeric && character != '-' && character != '_' &&+ character != '.')+ return false;+ }+ return signature != "." && signature != "..";+}++std::string abi_version_without_patch(std::string_view version) {+ if (!version.contains('.'))+ return std::string{version};+ return std::string{version.substr(0, version.find_last_of('.'))};+}++std::string compiled_abi_fingerprint() {+ return std::format(+ "{}_aq_{}_hu_{}_hg_{}_hc_{}_hlg_{}", GIT_COMMIT_HASH,+ abi_version_without_patch(AQUAMARINE_VERSION),+ abi_version_without_patch(HYPRUTILS_VERSION),+ abi_version_without_patch(HYPRGRAPHICS_VERSION),+ abi_version_without_patch(HYPRCURSOR_VERSION),+ abi_version_without_patch(HYPRLANG_VERSION));+}++bool safe_runtime_path(const std::string& runtime) {+ if (runtime.empty() || runtime.front() != '/' ||+ !cua::hyprland::is_valid_utf8(runtime))+ return false;+ for (const auto character : runtime) {+ const auto value = static_cast<unsigned char>(character);+ if (value < 0x20 || value == 0x7f)+ return false;+ }+ return true;+}++std::string resolve_socket_path() {+ const auto* runtime = std::getenv("XDG_RUNTIME_DIR");+ const auto* signature = std::getenv("HYPRLAND_INSTANCE_SIGNATURE");+ if (!runtime || !signature || !safe_runtime_path(runtime) ||+ !safe_instance_signature(signature))+ throw std::runtime_error("invalid Hyprland runtime environment");++ const auto runtime_path = std::filesystem::path{runtime};+ const auto hypr_root = runtime_path / "hypr";+ const auto instance = hypr_root / signature;+ for (const auto& directory : {runtime_path, hypr_root, instance}) {+ struct stat metadata{};+ if (lstat(directory.c_str(), &metadata) != 0 || !S_ISDIR(metadata.st_mode) ||+ metadata.st_uid != getuid() || (metadata.st_mode & 0077) != 0)+ throw std::runtime_error(+ "Hyprland runtime path is not a private, same-user directory");+ }++ return (instance / kSocketName).string();+}++std::uint64_t make_epoch() {+#ifdef __linux__+ std::uint64_t epoch = 0;+ auto* destination = reinterpret_cast<std::byte*>(&epoch);+ std::size_t offset = 0;+ while (offset < sizeof(epoch)) {+ const auto received = getrandom(destination + offset,+ sizeof(epoch) - offset, 0);+ if (received < 0) {+ if (errno == EINTR)+ continue;+ throw std::runtime_error(std::string{"getrandom failed: "} ++ std::strerror(errno));+ }+ if (received == 0)+ throw std::runtime_error("getrandom returned no entropy");+ offset += static_cast<std::size_t>(received);+ }+#else+ // The non-Linux path exists only for the mock API compile and unit tests.+ std::random_device random;+ const auto high = static_cast<std::uint64_t>(random()) << 32;+ const auto low = static_cast<std::uint64_t>(random());+ const auto epoch = high | low;+#endif+ return epoch == 0 ? 1 : epoch;+}++std::string stop_server() {+ if (!g_server)+ return {};+ g_server->stop();+ auto error = g_server->snapshot().last_error;+ g_server.reset();+ return error;+}++void reconcile_server() {+ if (!g_enabled || !g_enabled->value()) {+ g_reconcile_error = stop_server();+ g_socket_path.clear();+ g_epoch = 0;+ return;+ }+ if (g_server && g_server->snapshot().running)+ return;++ static_cast<void>(stop_server());+ g_epoch = 0;+ g_reconcile_error.clear();+ g_socket_path = resolve_socket_path();+ const auto epoch = make_epoch();+ auto server = std::make_unique<cua::hyprland::InjectionServer>(+ g_socket_path,+ cua::hyprland::ServerInfo{+ .compositor_epoch = epoch,+ .supported_capabilities =+ cua::hyprland::capability(cua::hyprland::Capability::discovery),+ .enabled_capabilities =+ cua::hyprland::capability(cua::hyprland::Capability::discovery),+ });+ if (server->start())+ g_epoch = epoch;+ g_server = std::move(server);+}++std::string status_output(bool json) {+ const auto configured = g_enabled && g_enabled->value();+ const auto snapshot = g_server ? g_server->snapshot() : cua::hyprland::ServerSnapshot{};+ const auto last_error = snapshot.last_error.empty() ? g_reconcile_error : snapshot.last_error;+ const cua::hyprland::StatusReport report{+ .plugin_version = kPluginVersion,+ .compositor_epoch = snapshot.running ? g_epoch : 0,+ .compiled_hash = g_compiled_abi_hash,+ .runtime_hash = g_runtime_abi_hash,+ .configured = configured,+ .transport_ready = snapshot.running,+ .socket_path = g_socket_path,+ .last_error = last_error,+ .discovery_enabled = snapshot.running,+ .accepted_connections = snapshot.accepted_connections,+ .rejected_peers = snapshot.rejected_peers,+ .rejected_busy = snapshot.rejected_busy,+ .timed_out_handshakes = snapshot.timed_out_handshakes,+ .timed_out_idle = snapshot.timed_out_idle,+ .malformed_frames = snapshot.malformed_frames,+ };++ if (json)+ return cua::hyprland::render_status_json(report);++ return cua::hyprland::render_status_text(report);+}++#if CUA_HYPRLAND_SOCKET1_API+IPC::Socket1::SResponse status(const IPC::Socket1::SRequest& request) {+ return IPC::Socket1::SResponse{+ status_output(request.format == IPC::Socket1::FORMAT_JSON)};+}++SP<IPC::Socket1::SCommand> register_status_command(HANDLE handle) {+ return HyprlandAPI::registerHyprCtlCommand(+ handle,+ IPC::Socket1::SCommand{+ .name = "cua:status",+ .match = IPC::Socket1::COMMAND_MATCH_EXACT,+ .handler = status,+ });+}+#else+std::string status(eHyprCtlOutputFormat format, std::string) {+ return status_output(format == eHyprCtlOutputFormat::FORMAT_JSON);+}++SP<SHyprCtlCommand> register_status_command(HANDLE handle) {+ return HyprlandAPI::registerHyprCtlCommand(+ handle,+ SHyprCtlCommand{+ .name = "cua:status",+ .exact = true,+ .fn = status,+ });+}+#endif++} // namespace++APICALL EXPORT std::string PLUGIN_API_VERSION() {+ return HYPRLAND_API_VERSION;+}++APICALL EXPORT PLUGIN_DESCRIPTION_INFO PLUGIN_INIT(HANDLE handle) {+ // Hyprland skips PLUGIN_EXIT when initialization throws. Do not start any+ // worker thread until all potentially throwing registration is complete.+ const auto* runtime_abi_hash = __hyprland_api_get_hash();+ g_compiled_abi_hash = compiled_abi_fingerprint();+ if (!runtime_abi_hash || g_compiled_abi_hash != runtime_abi_hash) {+ throw std::runtime_error(std::format(+ "cua-hyprland-plugin ABI fingerprint mismatch: built for {}, running {}",+ g_compiled_abi_hash,+ runtime_abi_hash ? runtime_abi_hash : "<missing>"));+ }+ g_runtime_abi_hash = runtime_abi_hash;++ g_enabled = makeShared<Config::Values::CBoolValue>(+ "plugin:cua:enabled",+ "Enable Cua's same-user local capability transport. Background mutation remains disabled in this build.",+ false);+ if (!HyprlandAPI::addConfigValueV2(handle, g_enabled))+ throw std::runtime_error("failed to register plugin:cua:enabled");++ g_status_command = register_status_command(handle);+ if (!g_status_command)+ throw std::runtime_error("failed to register cua:status");++ g_config_listener = Event::bus()->m_events.config.reloaded.listen([] {+ try {+ reconcile_server();+ } catch (const std::exception& error) {+ static_cast<void>(stop_server());+ g_reconcile_error = error.what();+ }+ });++ return {+ "cua-hyprland-plugin",+ "Discovery foundation for isolated background computer use",+ "Cua",+ kPluginVersion,+ };+}++APICALL EXPORT void PLUGIN_EXIT() {+ g_config_listener.reset();+ static_cast<void>(stop_server());+ g_status_command.reset();+ g_enabled.reset();+ g_socket_path.clear();+ g_reconcile_error.clear();+ g_compiled_abi_hash.clear();+ g_runtime_abi_hash.clear();+ g_epoch = 0;+}diff --git a/libs/cua-driver/hyprland-plugin/src/protocol.cpp b/libs/cua-driver/hyprland-plugin/src/protocol.cppnew file mode 100644index 0000000000..f068931ac1--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/protocol.cpp@@ -0,0 +1,172 @@+#include "cua_hyprland/protocol.hpp"++#include <algorithm>+#include <limits>++namespace cua::hyprland {+namespace {++void append_u16(std::vector<std::byte>& out, std::uint16_t value) {+ out.push_back(static_cast<std::byte>((value >> 8) & 0xff));+ out.push_back(static_cast<std::byte>(value & 0xff));+}++void append_u32(std::vector<std::byte>& out, std::uint32_t value) {+ for (int shift = 24; shift >= 0; shift -= 8)+ out.push_back(static_cast<std::byte>((value >> shift) & 0xff));+}++void append_u64(std::vector<std::byte>& out, std::uint64_t value) {+ for (int shift = 56; shift >= 0; shift -= 8)+ out.push_back(static_cast<std::byte>((value >> shift) & 0xff));+}++std::uint16_t read_u16(std::span<const std::byte> bytes, std::size_t offset) {+ return (std::to_integer<std::uint16_t>(bytes[offset]) << 8) |+ std::to_integer<std::uint16_t>(bytes[offset + 1]);+}++std::uint32_t read_u32(std::span<const std::byte> bytes, std::size_t offset) {+ std::uint32_t value = 0;+ for (std::size_t index = 0; index < 4; ++index)+ value = (value << 8) | std::to_integer<std::uint32_t>(bytes[offset + index]);+ return value;+}++std::uint64_t read_u64(std::span<const std::byte> bytes, std::size_t offset) {+ std::uint64_t value = 0;+ for (std::size_t index = 0; index < 8; ++index)+ value = (value << 8) | std::to_integer<std::uint64_t>(bytes[offset + index]);+ return value;+}++} // namespace++std::vector<std::byte> encode_frame(const Frame& frame) {+ if (frame.payload.size() > kMaxPayloadSize)+ return {};++ std::vector<std::byte> out;+ out.reserve(kHeaderSize + frame.payload.size());+ out.insert(out.end(), kMagic.begin(), kMagic.end());+ append_u16(out, frame.header.major);+ append_u16(out, frame.header.minor);+ append_u16(out, static_cast<std::uint16_t>(frame.header.type));+ append_u16(out, frame.header.flags);+ append_u64(out, frame.header.request_id);+ append_u32(out, static_cast<std::uint32_t>(frame.payload.size()));+ out.insert(out.end(), frame.payload.begin(), frame.payload.end());+ return out;+}++std::variant<Frame, DecodeError> decode_frame(std::span<const std::byte> bytes) {+ if (bytes.size() < kHeaderSize)+ return DecodeError::frame_too_small;+ if (!std::equal(kMagic.begin(), kMagic.end(), bytes.begin()))+ return DecodeError::bad_magic;++ Header header{+ .major = read_u16(bytes, 4),+ .minor = read_u16(bytes, 6),+ .type = static_cast<MessageType>(read_u16(bytes, 8)),+ .flags = read_u16(bytes, 10),+ .request_id = read_u64(bytes, 12),+ .payload_size = read_u32(bytes, 20),+ };++ if (header.major != kProtocolMajor || header.minor > kProtocolMinor)+ return DecodeError::unsupported_version;+ if (header.flags != 0)+ return DecodeError::nonzero_flags;+ if (header.payload_size > kMaxPayloadSize)+ return DecodeError::payload_too_large;+ if (bytes.size() != kHeaderSize + header.payload_size)+ return DecodeError::size_mismatch;++ return Frame{+ .header = header,+ .payload = std::vector<std::byte>(bytes.begin() + kHeaderSize, bytes.end()),+ };+}++std::vector<std::byte> encode_hello(const Hello& hello) {+ std::vector<std::byte> out;+ out.reserve(16);+ append_u64(out, hello.requested_capabilities);+ append_u64(out, hello.required_capabilities);+ return out;+}++std::variant<Hello, DecodeError> decode_hello(std::span<const std::byte> payload) {+ if (payload.size() != 16)+ return DecodeError::malformed_payload;+ return Hello{+ .requested_capabilities = read_u64(payload, 0),+ .required_capabilities = read_u64(payload, 8),+ };+}++std::vector<std::byte> encode_welcome(const Welcome& welcome) {+ std::vector<std::byte> out;+ out.reserve(32);+ append_u64(out, welcome.compositor_epoch);+ append_u64(out, welcome.supported_capabilities);+ append_u64(out, welcome.enabled_capabilities);+ append_u32(out, welcome.max_frame_size);+ append_u32(out, 0);+ return out;+}++std::variant<Welcome, DecodeError> decode_welcome(std::span<const std::byte> payload) {+ if (payload.size() != 32 || read_u32(payload, 28) != 0)+ return DecodeError::malformed_payload;+ return Welcome{+ .compositor_epoch = read_u64(payload, 0),+ .supported_capabilities = read_u64(payload, 8),+ .enabled_capabilities = read_u64(payload, 16),+ .max_frame_size = read_u32(payload, 24),+ };+}++std::vector<std::byte> encode_error(const ProtocolError& error) {+ constexpr std::size_t kErrorPrefixSize = 4;+ const auto detail_size = std::min(error.detail.size(), kMaxPayloadSize - kErrorPrefixSize);+ std::vector<std::byte> out;+ out.reserve(kErrorPrefixSize + detail_size);+ append_u32(out, static_cast<std::uint32_t>(error.code));+ for (std::size_t index = 0; index < detail_size; ++index)+ out.push_back(static_cast<std::byte>(error.detail[index]));+ return out;+}++std::variant<ProtocolError, DecodeError> decode_error(std::span<const std::byte> payload) {+ if (payload.size() < 4)+ return DecodeError::malformed_payload;+ std::string detail;+ detail.reserve(payload.size() - 4);+ for (const auto byte : payload.subspan(4))+ detail.push_back(static_cast<char>(byte));+ return ProtocolError{+ .code = static_cast<ErrorCode>(read_u32(payload, 0)),+ .detail = std::move(detail),+ };+}++Frame make_frame(MessageType type, std::uint64_t request_id,+ std::vector<std::byte> payload) {+ return Frame{+ .header = Header{+ .type = type,+ .request_id = request_id,+ .payload_size = static_cast<std::uint32_t>(payload.size()),+ },+ .payload = std::move(payload),+ };+}++Frame make_error(std::uint64_t request_id, ErrorCode code, std::string detail) {+ return make_frame(MessageType::error, request_id,+ encode_error(ProtocolError{code, std::move(detail)}));+}++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/src/session.cpp b/libs/cua-driver/hyprland-plugin/src/session.cppnew file mode 100644index 0000000000..249940ca2e--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/session.cpp@@ -0,0 +1,79 @@+#include "cua_hyprland/session.hpp"++namespace cua::hyprland {++Frame Session::handle(const Frame& request, const ServerInfo& server) {+ if (!m_handshaken) {+ if (request.header.type != MessageType::hello) {+ return make_error(request.header.request_id, ErrorCode::handshake_required,+ "HELLO must be the first request");+ }++ const auto decoded = decode_hello(request.payload);+ if (!std::holds_alternative<Hello>(decoded)) {+ return make_error(request.header.request_id, ErrorCode::malformed_frame,+ "invalid HELLO payload");+ }++ const auto hello = std::get<Hello>(decoded);+ const auto unavailable = hello.required_capabilities & ~server.enabled_capabilities;+ if (unavailable != 0) {+ return make_error(request.header.request_id,+ ErrorCode::capability_unavailable,+ "required capabilities are unavailable");+ }++ m_negotiated_capabilities =+ server.enabled_capabilities &+ (hello.requested_capabilities | hello.required_capabilities);+ m_handshaken = true;+ return make_frame(+ MessageType::welcome, request.header.request_id,+ encode_welcome(Welcome{+ .compositor_epoch = server.compositor_epoch,+ .supported_capabilities = server.supported_capabilities,+ .enabled_capabilities = m_negotiated_capabilities,+ }));+ }++ switch (request.header.type) {+ case MessageType::ping:+ if (!request.payload.empty())+ return make_error(request.header.request_id, ErrorCode::malformed_frame,+ "PING payload must be empty");+ return make_frame(MessageType::pong, request.header.request_id);+ case MessageType::status_request:+ if (!request.payload.empty())+ return make_error(request.header.request_id, ErrorCode::malformed_frame,+ "STATUS payload must be empty");+ return make_frame(+ MessageType::status_response, request.header.request_id,+ encode_welcome(Welcome{+ .compositor_epoch = server.compositor_epoch,+ .supported_capabilities = server.supported_capabilities,+ .enabled_capabilities = m_negotiated_capabilities &+ server.enabled_capabilities,+ }));+ case MessageType::hello:+ return make_error(request.header.request_id, ErrorCode::malformed_frame,+ "HELLO may only be sent once");+ case MessageType::pointer_motion:+ case MessageType::pointer_button:+ case MessageType::pointer_axis:+ case MessageType::pointer_drag:+ case MessageType::keyboard_key:+ case MessageType::keyboard_text:+ return make_error(request.header.request_id,+ ErrorCode::background_unavailable,+ "background mutation is not enabled in this build");+ default:+ return make_error(request.header.request_id, ErrorCode::malformed_frame,+ "message type is invalid for a client request");+ }+}++bool Session::handshaken() const {+ return m_handshaken;+}++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/src/status.cpp b/libs/cua-driver/hyprland-plugin/src/status.cppnew file mode 100644index 0000000000..3c41f00c70--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/src/status.cpp@@ -0,0 +1,166 @@+#include "cua_hyprland/status.hpp"++#include "cua_hyprland/protocol.hpp"++#include <format>+#include <string>++namespace cua::hyprland {+namespace {++bool continuation(unsigned char value) {+ return value >= 0x80 && value <= 0xbf;+}++std::size_t valid_sequence_size(std::string_view value, std::size_t offset) {+ const auto first = static_cast<unsigned char>(value[offset]);+ const auto remaining = value.size() - offset;+ if (first < 0x80)+ return 1;+ if (first >= 0xc2 && first <= 0xdf && remaining >= 2 &&+ continuation(static_cast<unsigned char>(value[offset + 1])))+ return 2;+ if (remaining >= 3 && first >= 0xe0 && first <= 0xef) {+ const auto second = static_cast<unsigned char>(value[offset + 1]);+ const auto third = static_cast<unsigned char>(value[offset + 2]);+ const auto valid_second =+ (first == 0xe0 && second >= 0xa0 && second <= 0xbf) ||+ (first == 0xed && second >= 0x80 && second <= 0x9f) ||+ (((first >= 0xe1 && first <= 0xec) ||+ (first >= 0xee && first <= 0xef)) &&+ continuation(second));+ if (valid_second && continuation(third))+ return 3;+ }+ if (remaining >= 4 && first >= 0xf0 && first <= 0xf4) {+ const auto second = static_cast<unsigned char>(value[offset + 1]);+ const auto third = static_cast<unsigned char>(value[offset + 2]);+ const auto fourth = static_cast<unsigned char>(value[offset + 3]);+ const auto valid_second =+ (first == 0xf0 && second >= 0x90 && second <= 0xbf) ||+ (first == 0xf4 && second >= 0x80 && second <= 0x8f) ||+ (first >= 0xf1 && first <= 0xf3 && continuation(second));+ if (valid_second && continuation(third) && continuation(fourth))+ return 4;+ }+ return 0;+}++void append_byte_escape(std::string& escaped, unsigned char value) {+ constexpr char hex[] = "0123456789abcdef";+ escaped += "\\u00";+ escaped += hex[(value >> 4) & 0x0f];+ escaped += hex[value & 0x0f];+}++std::string escape_json(std::string_view value) {+ std::string escaped;+ escaped.reserve(value.size());+ for (std::size_t index = 0; index < value.size();) {+ const auto character = value[index];+ const auto byte = static_cast<unsigned char>(character);+ switch (character) {+ case '\\':+ escaped += "\\\\";+ ++index;+ continue;+ case '"':+ escaped += "\\\"";+ ++index;+ continue;+ case '\n':+ escaped += "\\n";+ ++index;+ continue;+ case '\r':+ escaped += "\\r";+ ++index;+ continue;+ case '\t':+ escaped += "\\t";+ ++index;+ continue;+ default: break;+ }+ if (byte < 0x20 || byte == 0x7f) {+ append_byte_escape(escaped, byte);+ ++index;+ continue;+ }+ const auto sequence_size = valid_sequence_size(value, index);+ if (sequence_size == 0) {+ append_byte_escape(escaped, byte);+ ++index;+ continue;+ }+ escaped.append(value.substr(index, sequence_size));+ index += sequence_size;+ }+ return escaped;+}++constexpr std::string_view json_bool(bool value) {+ return value ? "true" : "false";+}++} // namespace++bool is_valid_utf8(std::string_view value) {+ for (std::size_t offset = 0; offset < value.size();) {+ const auto size = valid_sequence_size(value, offset);+ if (size == 0)+ return false;+ offset += size;+ }+ return true;+}++std::string render_status_json(const StatusReport& report) {+ return std::format(+ R"({{"name":"cua-hyprland-plugin","plugin_version":"{}",)"+ R"("state":"discovery_only","protocol":{{"major":{},"minor":{},)"+ R"("max_frame_bytes":{}}},"compositor_epoch":{},"abi":{{)"+ R"("compiled_hash":"{}","runtime_hash":"{}","match":{}}},)"+ R"("configured":{},"transport":{{"ready":{},"socket":"{}",)"+ R"("mode":"0600","peer_policy":"same_uid","last_error":"{}"}},)"+ R"("capabilities":{{"supported":["discovery"],"enabled":{},)"+ R"("mutation":"disabled_pending_rfc_and_agent_seat"}},)"+ R"("connections":{{"accepted":{},"rejected_peers":{},)"+ R"("rejected_busy":{},"timed_out_handshakes":{},)"+ R"("timed_out_idle":{},"malformed_frames":{}}}}})",+ escape_json(report.plugin_version), kProtocolMajor, kProtocolMinor,+ kMaxFrameSize, report.compositor_epoch, escape_json(report.compiled_hash),+ escape_json(report.runtime_hash),+ json_bool(report.compiled_hash == report.runtime_hash),+ json_bool(report.configured),+ json_bool(report.transport_ready), escape_json(report.socket_path),+ escape_json(report.last_error),+ report.discovery_enabled ? R"(["discovery"])" : "[]",+ report.accepted_connections, report.rejected_peers, report.rejected_busy,+ report.timed_out_handshakes, report.timed_out_idle,+ report.malformed_frames);+}++std::string render_status_text(const StatusReport& report) {+ return std::format(+ "cua-hyprland-plugin {}\nconfigured: {}\ntransport: {}\nsocket: {}\n"+ "last error: {}\nprotocol: {}.{}\ncompositor epoch: {}\n"+ "ABI compiled: {}\nABI runtime: {}\nABI match: {}\n"+ "connections: accepted={}, "+ "rejected_peers={}, rejected_busy={}, timed_out_handshakes={}, "+ "timed_out_idle={}, malformed_frames={}\n"+ "capabilities: discovery only; background mutation disabled\n",+ report.plugin_version, report.configured ? "yes" : "no",+ report.transport_ready ? "ready" : "stopped",+ report.socket_path.empty() ? "<not resolved>" :+ escape_json(report.socket_path),+ report.last_error.empty() ? "<none>" : escape_json(report.last_error),+ kProtocolMajor, kProtocolMinor, report.compositor_epoch,+ escape_json(report.compiled_hash), escape_json(report.runtime_hash),+ report.compiled_hash == report.runtime_hash ? "yes" : "no",+ report.accepted_connections, report.rejected_peers,+ report.rejected_busy, report.timed_out_handshakes,+ report.timed_out_idle, report.malformed_frames);+}++} // namespace cua::hyprlanddiff --git a/libs/cua-driver/hyprland-plugin/tests/README.md b/libs/cua-driver/hyprland-plugin/tests/README.mdnew file mode 100644index 0000000000..7232c9537e--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/README.md@@ -0,0 +1,182 @@+# Hyprland plugin test plan++The plugin is optional, disabled by default, and discovery-only until the+second-seat design is proven and its RFC is accepted. Tests must fail closed;+they must not enable mutation merely to exercise a path.++Neither stable Cua Driver `0.23.2` nor nightly provides isolated background+input through this plugin. Discovery currently covers protocol negotiation,+status, and liveness only; application target discovery and input mutation are+not enabled.++Record stock `0.23.2` desktop capture, window enumeration, foreground actions,+and AT-SPI actions separately. Available Wayland protocols and AT-SPI services+establish prerequisites only. Plugin ABI compatibility and isolated raw+background delivery require their own evidence. Host Hyprland validation+requires the exact versions and rows below.++## Focused pre-merge checks++Run against the exact Hyprland headers used for the build:++The portable protocol tests run on any host with C++26 support. The Unix transport smoke+uses `SOCK_STREAM` only on non-Linux developer hosts that lack AF_UNIX+`SOCK_SEQPACKET`; release evidence must run the same test on Linux, where the+production `SOCK_SEQPACKET` and `SO_PEERCRED` paths are compiled and exercised.+Use `-DCUA_HYPRLAND_BUILD_PLUGIN=OFF` when configuring those tests on a+non-Linux host. Passing the shim is not Linux transport evidence.++1. Build the module with warnings treated as errors where the toolchain allows.+ Compile both the Hyprland `0.56.2` legacy status-command adapter and the+ newer Socket1 adapter in the mock suite. The CMake probe test also verifies+ C++26, pkg-config flag propagation, unsupported-header rejection, and tier+ changes within one build directory. Record the compositor and plugin+ compiler family and version; they must match for live load evidence.+ The ELF dependency check must accept a shared C++ runtime and reject a+ statically linked runtime. Preserve both outputs if an incomplete compiler+ staging directory causes that negative case.+2. Exercise binary packet parsing at zero, boundary, and over-limit sizes,+ including bad magic, unsupported versions, nonzero flags, truncation, queue+ saturation, and disconnect during nonblocking reads and writes.+3. Verify socket placement in the current Hyprland per-instance runtime+ directory, inode mode `0600`, safe stale-socket handling, and cleanup that+ cannot remove another process's file.+4. Verify `SO_PEERCRED` accepts the compositor UID and refuses another UID or+ unavailable credentials before processing requests.+5. Force an I/O-thread poll failure and verify the listener closes, the socket+ path disappears, future connects fail, and status retains the failure.+6. Exercise `EMFILE`/`ENFILE` accept failures under a bounded file-descriptor+ limit and verify retries are time-bounded rather than a readable-listener+ busy loop.+7. Verify protocol, epoch, and capability negotiation, including stale epochs,+ unsupported versions, absent capabilities, handshake and post-handshake idle+ timeouts, keepalive traffic, reconnects, and compositor restarts.+8. Verify opaque target tokens cannot be correlated with pointers, object IDs,+ or PIDs; are pruned on destruction; and never survive an epoch change.+9. Verify every mutation shape returns exact `background_unavailable` without+ focus, z-order, cursor, target state, primary-seat activity, or+ unrelated-window changes. Error detail is diagnostic and is not a stable+ machine-readable reason field in protocol v2.+10. Verify a transport `ack` cannot satisfy an application-delivery assertion;+ the harness must require a typed result and an independent state oracle.++An ABI-negative test builds against one Hyprland version and attempts to load+under a different version in a disposable environment. The acceptable outcome+is an explicit refusal or unavailable status with no socket. A crash, partial+registration, or capability advertisement is a failure.++With the exact module already loaded and discovery enabled in a disposable+Hyprland session, run the live transport check:++```bash+python3 tests/live_discovery.py --reload-module /absolute/path/to/cua-hyprland-plugin.so+```++The script checks real packet negotiation, liveness, all six mutation refusals,+socket mode, unchanged compositor window/workspace/cursor state, connection+closure on unload, and a fresh epoch on reload. It does not validate application+state, a live foreground grab, hardware input isolation, or a different-UID+peer. Those remain separate acceptance rows. The reload option unloads and+reloads the named module; omit it for a transport-only check.++To test two-instance isolation and clean restart inside a disposable Hyprland+Wayland desktop, run the owned-process lifecycle runner:++```bash+python3 tests/nested_lifecycle.py --module /absolute/path/to/cua-hyprland-plugin.so+```++The runner starts two nested Hyprland processes with temporary configs, finds+each by its exact child PID, and loads the matching module only into those+processes. It runs the live refusal check in both, restarts one, and checks old+connection closure, socket removal, fresh socket/epoch, and sibling liveness.+It stops both owned processes on success or failure and preserves temporary+logs. Forced termination is a failure, not a clean-restart pass. The parent+must still answer version queries afterward; its config is never edited and+the module is never loaded into it. Use a disposable parent because nested+windows can affect its focus and compositor startup can update session state.++Record the source SHA, module digest, environment, stdout, stderr, and retained+logs. The JSON result distinguishes this check from application delivery and+physical input isolation. It does not certify package installation, direct DRM+startup, arbitrary ABI combinations, or the complete driver desktop matrix.+Hosted CI tests the runner's cleanup/error paths with mocks; native results+require running it in the Fleet guest or another declared Wayland environment.++## Fleet packaging lane++Build an Omarchy/Arch Fleet image from the monorepo source using+`packaging/arch/PKGBUILD`. Record the source SHA, exact Hyprland package version,+plugin package version, module digest, and image identity. The lane must prove:++- installation only under `/usr/lib/cua/hyprland/`, with no configuration edit,+ service enablement, autoload, or replacement of Hyprland-owned files;+- explicit load, JSON discovery/status inspection, one-shot client negotiation,+ long-lived client reconnect, explicit unload, and clean Hyprland restart;+- exact ABI dependency failure after a simulated Hyprland package change;+- socket isolation between two Hyprland instances for the same user and refusal+ of a different-UID peer; and+- all discovery-only mutation refusals under fixture-state, focus, z-order,+ cursor, and input-leak oracles.++The Fleet lane must also identify whether each client is a one-shot process or+a long-lived process created inside the graphical session. A process launched+outside that session and given copied display variables is not equivalent+evidence. Chromium and Electron rows must record their effective Ozone backend+and confirm they render and expose the intended fixture before testing a+refusal.++Run the repository's ordinary Linux source/unit checks and relevant Cua Driver+catalogs on the exact candidate SHA. Fleet validates reproducible packaging and+lifecycle behavior; it is not the final hardware claim.++## Physical Omarchy final gate++After the Fleet packaging lane passes, and before any capability or release+claim, repeat the candidate package on a bare-metal Omarchy machine using the+exact Hyprland/plugin pair. Record status before load, after load, after+discovery, after refused mutations, after unload, and after a compositor+restart. Independently verify application state, focus, z-order, cursor+position, and absence of primary-seat or unrelated-window input.++The physical run is the final acceptance gate. VM, nested compositor, or Fleet+success cannot replace it. If the candidate SHA, Hyprland package, protocol,+packaging, mutation behavior, or harness changes afterward, rerun the evidence+affected by that change before promotion.++The exact initial baseline is Omarchy `4.0.2-1`, Hyprland `0.56.2`,+xdg-desktop-portal-hyprland `1.4.1`, Cua Driver `0.23.2`, and UWSM/SDDM. Record+all five values with the candidate SHA and plugin module digest.++Run each row separately and retain the typed protocol result plus the listed+independent oracle. All application rows require DPMS on. Because the plugin is+discovery-only, mutation attempts must return `background_unavailable` and+must leave the application, focus, z-order, cursor, primary seat, and unrelated+windows unchanged.++| Validation row | Required evidence |+| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Stock `0.23.2` capture | A non-black frame with fixture-owned visual markers; classify this as stock capture evidence, not plugin evidence. |+| Stock `0.23.2` foreground action | Before/after active-window identity proving whether the driver explicitly activated the target, plus fixture state; activation is foreground-route behavior, not isolated background input. |+| Stock `0.23.2` AT-SPI action | Accessibility and fixture-state evidence identifying the semantic route; no raw-input claim. |+| GTK3 native Wayland | Typed refusal and unchanged GTK3 fixture state. |+| GTK4 native Wayland | Typed refusal and unchanged GTK4 fixture state. |+| Qt6 native Wayland | Typed refusal and unchanged Qt6 fixture state. |+| LibreOffice native Wayland | Typed refusal and unchanged document state. |+| Chromium with Ozone/Wayland | Record Chromium version, launch flags, and effective Wayland Ozone backend; prove the fixture renders, then require typed refusal and unchanged page state. |+| Electron with Ozone/Wayland | Record Electron/Chromium versions, launch flags, and effective Wayland Ozone backend; prove the fixture renders, then require typed refusal and unchanged application state. |+| DPMS off | Require typed refusal before dispatch with no action claimed; do not turn DPMS on implicitly, and never treat a black capture as success. |+| One-shot graphical-session client | Launch one fresh process from the real graphical-session environment, complete discovery negotiation, receive typed mutation refusal, and exit cleanly without relying on state from another invocation. |+| Long-lived graphical-session client | Launch inside the real graphical session, negotiate discovery, survive repeated calls, detect compositor/plugin restart and the stale connection, reconnect and negotiate the new epoch, then receive typed mutation refusal. |++The bare-metal result is the final certification after Fleet. A missing row,+an untyped failure, a black frame treated as capture success, focus or cursor+movement, input leakage, or a client that cannot reconnect fails certification.++`hyprctl` evidence is limited to compositor administration and the plugin's+`cua:status` surface. Record every focus, workspace, DPMS, load, status, and+unload command separately; none is application mutation proof. Likewise,+`list_apps` filtering and the choice and authorization of `cua-driver serve` or+individual `cua-driver call` requests are driver-side tests, not plugin+capabilities. They may be exercised to diagnose an agent integration, but+must not appear in the plugin capability result.diff --git a/libs/cua-driver/hyprland-plugin/tests/cmake-api/CMakeLists.txt b/libs/cua-driver/hyprland-plugin/tests/cmake-api/CMakeLists.txtnew file mode 100644index 0000000000..3d71084011--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/cmake-api/CMakeLists.txt@@ -0,0 +1,28 @@+cmake_minimum_required(VERSION 3.30)+project(cua_hyprland_api_detection_test LANGUAGES CXX)+include(../../cmake/DetectHyprlandAPI.cmake)++set(CMAKE_CXX_STANDARD 17)+set(CMAKE_REQUIRED_FLAGS "-DCUA_CALLER_SETTING=1")+unset(CMAKE_TRY_COMPILE_TARGET_TYPE)++foreach(tier IN ITEMS socket1 legacy unsupported socket1)+ cua_detect_hyprland_api(actual "${CMAKE_CURRENT_SOURCE_DIR}/include"+ "-DCUA_PROBE_${tier}=1;-DCUA_PROBE_FLAG=1")+ if(tier STREQUAL "socket1")+ set(expected 1)+ elseif(tier STREQUAL "legacy")+ set(expected 0)+ else()+ set(expected unsupported)+ endif()+ if(NOT actual STREQUAL expected)+ message(FATAL_ERROR "Expected ${tier} (${expected}), found ${actual}")+ endif()+endforeach()++if(NOT CMAKE_CXX_STANDARD STREQUAL "17" OR+ NOT CMAKE_REQUIRED_FLAGS STREQUAL "-DCUA_CALLER_SETTING=1" OR+ DEFINED CMAKE_TRY_COMPILE_TARGET_TYPE)+ message(FATAL_ERROR "API detection changed caller settings")+endif()diff --git a/libs/cua-driver/hyprland-plugin/tests/cmake-api/include/src/plugins/PluginAPI.hpp b/libs/cua-driver/hyprland-plugin/tests/cmake-api/include/src/plugins/PluginAPI.hppnew file mode 100644index 0000000000..2ca51a3ec2--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/cmake-api/include/src/plugins/PluginAPI.hpp@@ -0,0 +1,16 @@+#pragma once++#if __cplusplus <= 202302L+#error The plugin API probe must compile in C++26 mode+#endif+#ifndef CUA_PROBE_FLAG+#error The plugin API probe must propagate pkg-config flags+#endif++#if defined(CUA_PROBE_socket1)+namespace IPC::Socket1 {+struct SCommand {};+}+#elif defined(CUA_PROBE_legacy)+struct SHyprCtlCommand {};+#endifdiff --git a/libs/cua-driver/hyprland-plugin/tests/live_discovery.py b/libs/cua-driver/hyprland-plugin/tests/live_discovery.pynew file mode 100644index 0000000000..9508b5952d--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/live_discovery.py@@ -0,0 +1,122 @@+"""Verify a loaded discovery-only plugin in a disposable Hyprland session.++This observes compositor state, not application delivery or foreground grabs.+The optional lifecycle test explicitly unloads and reloads the supplied module.+"""++import argparse+import json+import socket+import stat+import struct+import subprocess+from pathlib import Path++if not __debug__:+ raise RuntimeError("Discovery validation requires assertions; do not use -O or PYTHONOPTIMIZE")++HEADER = struct.Struct("!4sHHHHQI")+++def hyprctl(*args):+ return subprocess.check_output(["hyprctl", *args], text=True, timeout=10)+++def status():+ value = json.loads(hyprctl("-j", "cua:status"))+ assert value["state"] == "discovery_only"+ assert value["abi"]["match"] is True+ assert value["capabilities"]["supported"] == ["discovery"]+ assert value["capabilities"]["enabled"] == ["discovery"]+ assert value["transport"]["ready"] is True+ assert value["compositor_epoch"] != 0+ assert value["protocol"] == {"major": 2, "minor": 0, "max_frame_bytes": 4120}+ return value+++def desktop_state():+ active = json.loads(hyprctl("-j", "activewindow"))+ clients = json.loads(hyprctl("-j", "clients"))+ return {+ "active_window": active.get("address"),+ "active_workspace": json.loads(hyprctl("-j", "activeworkspace")).get("id"),+ "cursor": json.loads(hyprctl("-j", "cursorpos")),+ "windows": sorted(+ (+ c["address"],+ c.get("at"),+ c.get("size"),+ c.get("workspace", {}).get("id"),+ c.get("floating"),+ c.get("mapped"),+ c.get("focusHistoryID"),+ )+ for c in clients+ ),+ }+++def exchange(client, message, request_id, payload=b""):+ packet = HEADER.pack(b"CUA2", 2, 0, message, 0, request_id, len(payload)) + payload+ assert client.send(packet) == len(packet)+ response = client.recv(4121)+ assert HEADER.size <= len(response) <= 4120+ magic, major, minor, kind, flags, correlated, size = HEADER.unpack_from(response)+ assert (magic, major, minor, flags, correlated) == (b"CUA2", 2, 0, 0, request_id)+ assert len(response) == HEADER.size + size+ return kind, response[HEADER.size :]+++def connect(metadata):+ path = Path(metadata["transport"]["socket"])+ assert stat.S_ISSOCK(path.stat().st_mode)+ assert stat.S_IMODE(path.stat().st_mode) == 0o600+ client = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)+ client.settimeout(5)+ client.connect(str(path))+ kind, payload = exchange(client, 1, 1, struct.pack("!QQ", 1, 1))+ assert kind == 2+ assert struct.unpack("!QQQII", payload) == (metadata["compositor_epoch"], 1, 1, 4120, 0)+ return client+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--reload-module", type=Path)+ args = parser.parse_args()+ initial = status()+ before = desktop_state()+ with connect(initial) as client:+ assert exchange(client, 3, 2) == (4, b"")+ kind, payload = exchange(client, 5, 3)+ assert kind == 6+ assert struct.unpack("!QQQII", payload) == (initial["compositor_epoch"], 1, 1, 4120, 0)+ for request_id, kind in enumerate((0x100, 0x101, 0x102, 0x103, 0x110, 0x111), 4):+ response_kind, payload = exchange(client, kind, request_id)+ assert response_kind == 0xFFFF and struct.unpack_from("!I", payload)[0] == 8+ assert desktop_state() == before, "refused packets changed compositor state"+ if args.reload_module:+ module = str(args.reload_module.resolve(strict=True))+ assert hyprctl("plugin", "unload", module).strip() == "ok"+ assert client.recv(1) == b"", "unload left the old connection open"+ assert not Path(initial["transport"]["socket"]).exists()+ assert hyprctl("plugin", "load", module).strip() == "ok"+ assert hyprctl("reload").strip() == "ok"+ reloaded = status()+ assert reloaded["compositor_epoch"] != initial["compositor_epoch"]+ with connect(reloaded) as replacement:+ assert exchange(replacement, 3, 2) == (4, b"")+ print(+ json.dumps(+ {+ "result": "passed",+ "mutation_refusals": 6,+ "compositor_state_unchanged": True,+ "module_reload": bool(args.reload_module),+ }+ )+ )+++if __name__ == "__main__":+ main()diff --git a/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py b/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.pynew file mode 100644index 0000000000..3a2bad56b3--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/live_discovery_test.py@@ -0,0 +1,53 @@+"""Protocol helper checks; native evidence still requires a live compositor."""++import os+import subprocess+import sys+import unittest+from pathlib import Path+from unittest.mock import Mock++import live_discovery as discovery+++class DiscoveryTest(unittest.TestCase):+ def test_exchange_sends_and_correlates_request(self):+ packet = discovery.HEADER.pack(b"CUA2", 2, 0, 3, 0, 17, 0)+ client = Mock()+ client.send.return_value = len(packet)+ client.recv.return_value = discovery.HEADER.pack(b"CUA2", 2, 0, 4, 0, 17, 0)+ self.assertEqual(discovery.exchange(client, 3, 17), (4, b""))+ client.send.assert_called_once_with(packet)++ def test_exchange_rejects_short_send_before_receive(self):+ client = Mock()+ client.send.return_value = 0+ with self.assertRaises(AssertionError):+ discovery.exchange(client, 3, 17)+ client.recv.assert_not_called()++ def test_exchange_rejects_wrong_request_id(self):+ client = Mock()+ client.send.return_value = discovery.HEADER.size+ client.recv.return_value = discovery.HEADER.pack(b"CUA2", 2, 0, 4, 0, 18, 0)+ with self.assertRaises(AssertionError):+ discovery.exchange(client, 3, 17)++ def test_optimized_python_refuses_before_cli_or_compositor_access(self):+ script = str(Path(discovery.__file__).resolve())+ for options, optimize in ((["-O"], ""), ([], "1"), (["-OO"], "")):+ with self.subTest(options=options, optimize=optimize):+ result = subprocess.run(+ [sys.executable, *options, script, "--help"],+ env={**os.environ, "PYTHONOPTIMIZE": optimize},+ capture_output=True,+ text=True,+ timeout=10,+ )+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("Discovery validation requires assertions", result.stderr)+ self.assertNotIn("usage:", result.stdout)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hppnew file mode 100644index 0000000000..1ac297cf63--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/mock.hpp@@ -0,0 +1,263 @@+#pragma once++#include <cstdint>+#include <functional>+#include <memory>+#include <optional>+#include <string>+#include <typeinfo>+#include <unordered_map>+#include <utility>+#include <variant>+#include <vector>++#define GIT_COMMIT_HASH "mock-hyprland-hash"+#define AQUAMARINE_VERSION "1.2.3"+#define HYPRUTILS_VERSION "2.3.4"+#define HYPRGRAPHICS_VERSION "3.4.5"+#define HYPRCURSOR_VERSION "4.5.6"+#define HYPRLANG_VERSION "5.6.7"+#define HYPRLAND_API_VERSION "0.1"+#define APICALL extern "C"+#define EXPORT __attribute__((visibility("default")))+#define HANDLE void*+#define PLUGIN_API_VERSION pluginAPIVersion+#define PLUGIN_INIT pluginInit+#define PLUGIN_EXIT pluginExit++APICALL inline EXPORT const char* __hyprland_api_get_client_hash() {+ return "mock-hyprland-hash_aq_1.2_hu_2.3_hg_3.4_hc_4.5_hlg_5.6";+}++APICALL EXPORT const char* __hyprland_api_get_hash();++template <typename T>+using SP = std::shared_ptr<T>;++template <typename T, typename... Args>+SP<T> makeShared(Args&&... args) {+ return std::make_shared<T>(std::forward<Args>(args)...);+}++struct PLUGIN_DESCRIPTION_INFO {+ std::string name;+ std::string description;+ std::string author;+ std::string version;+};++struct SVersionInfo {+ std::string hash = GIT_COMMIT_HASH;+ std::string tag;+ bool dirty = false;+ std::string branch;+ std::string message;+ std::string commits;+};++enum eHyprCtlOutputFormat : std::uint8_t {+ FORMAT_NORMAL = 0,+ FORMAT_JSON,+};++struct SHyprCtlCommand {+ std::string name;+ bool exact = true;+ std::function<std::string(eHyprCtlOutputFormat, std::string)> fn;+};++struct CHyprSignalListener {+ CHyprSignalListener() = default;+ explicit CHyprSignalListener(std::function<void()> reset_callback)+ : m_reset_callback(std::move(reset_callback)) {}+ ~CHyprSignalListener() { reset(); }++ CHyprSignalListener(const CHyprSignalListener&) = delete;+ CHyprSignalListener& operator=(const CHyprSignalListener&) = delete;++ CHyprSignalListener(CHyprSignalListener&& other) noexcept+ : m_reset_callback(std::exchange(other.m_reset_callback, {})) {}++ CHyprSignalListener& operator=(CHyprSignalListener&& other) noexcept {+ if (this == &other)+ return *this;+ reset();+ m_reset_callback = std::exchange(other.m_reset_callback, {});+ return *this;+ }++ void reset() {+ if (!m_reset_callback)+ return;+ auto reset_callback = std::move(m_reset_callback);+ reset_callback();+ }++ private:+ std::function<void()> m_reset_callback;+};++namespace Supplementary {++using PropRefreshBits = std::uint64_t;++} // namespace Supplementary++namespace Config {++using BOOL = bool;++namespace Values {++inline std::optional<Config::BOOL> configured_bool_override;++struct SBoolValueOptions {+ Supplementary::PropRefreshBits refresh = 0;+ const char* deprecationNotice = nullptr;+};++class IValue {+ protected:+ IValue(Supplementary::PropRefreshBits, const char* = nullptr) {}++ public:+ virtual ~IValue() = default;+ virtual const std::type_info* underlying() const = 0;+ virtual void commence() = 0;+};++class CBoolValue : public IValue {+ public:+ CBoolValue(const char*, const char*, Config::BOOL value,+ SBoolValueOptions&& options = {})+ : IValue(options.refresh, options.deprecationNotice),+ m_value(configured_bool_override.value_or(value)) {}+ const std::type_info* underlying() const override { return &typeid(Config::BOOL); }+ void commence() override {}+ Config::BOOL value() const { return m_value; }++ private:+ Config::BOOL m_value;+};++} // namespace Values+} // namespace Config++namespace IPC::Socket1 {++enum eOutputFormat : std::uint8_t {+ FORMAT_NORMAL = 0,+ FORMAT_JSON,+};++enum eCommandMatch : std::uint8_t {+ COMMAND_MATCH_EXACT = 0,+ COMMAND_MATCH_PREFIX,+};++struct SRequest {+ eOutputFormat format = FORMAT_NORMAL;+};++struct SResponse {+ using TResult = std::variant<std::string>;++ explicit SResponse(std::string value) : result(std::move(value)) {}+ TResult result;+};++struct SCommand {+ std::string name;+ eCommandMatch match = COMMAND_MATCH_EXACT;+ std::function<SResponse(const SRequest&)> handler;+};++} // namespace IPC::Socket1++namespace Event {++struct ReloadedEvent {+ struct State {+ std::size_t next_id = 1;+ std::size_t deliveries = 0;+ std::unordered_map<std::size_t, std::function<void()>> callbacks;+ };++ template <typename Callback>+ CHyprSignalListener listen(Callback&& listener) {+ const auto id = state->next_id++;+ state->callbacks.emplace(id, std::forward<Callback>(listener));+ const std::weak_ptr<State> weak_state = state;+ return CHyprSignalListener{[weak_state, id] {+ if (const auto locked = weak_state.lock())+ locked->callbacks.erase(id);+ }};+ }++ void emit() {+ std::vector<std::function<void()>> callbacks;+ callbacks.reserve(state->callbacks.size());+ for (const auto& [id, callback] : state->callbacks) {+ static_cast<void>(id);+ callbacks.push_back(callback);+ }+ for (const auto& callback : callbacks) {+ ++state->deliveries;+ callback();+ }+ }++ std::size_t active_count() const { return state->callbacks.size(); }+ std::size_t delivery_count() const { return state->deliveries; }++ std::shared_ptr<State> state = std::make_shared<State>();+};++struct EventBus {+ struct {+ struct {+ ReloadedEvent reloaded;+ } config;+ } m_events;+};++inline EventBus* bus() {+ static EventBus event_bus;+ return &event_bus;+}++} // namespace Event++namespace HyprlandAPI {++inline SVersionInfo runtime_version{};+inline std::string runtime_abi_hash = __hyprland_api_get_client_hash();+inline SP<IPC::Socket1::SCommand> registered_command;+inline SP<SHyprCtlCommand> registered_legacy_command;+inline bool config_registration_succeeds = true;++inline SVersionInfo getHyprlandVersion(HANDLE) {+ return runtime_version;+}++inline bool addConfigValueV2(HANDLE, SP<Config::Values::IValue>) {+ return config_registration_succeeds;+}++inline SP<IPC::Socket1::SCommand> registerHyprCtlCommand(+ HANDLE, IPC::Socket1::SCommand command) {+ registered_command = makeShared<IPC::Socket1::SCommand>(std::move(command));+ return registered_command;+}++inline SP<SHyprCtlCommand> registerHyprCtlCommand(+ HANDLE, SHyprCtlCommand command) {+ registered_legacy_command = makeShared<SHyprCtlCommand>(std::move(command));+ return registered_legacy_command;+}++} // namespace HyprlandAPI++APICALL inline EXPORT const char* __hyprland_api_get_hash() {+ return HyprlandAPI::runtime_abi_hash.c_str();+}diff --git a/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/config/values/types/BoolValue.hpp b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/config/values/types/BoolValue.hppnew file mode 100644index 0000000000..fad3bd9d83--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/config/values/types/BoolValue.hpp@@ -0,0 +1,3 @@+#pragma once++#include "../../../../mock.hpp"diff --git a/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/plugins/PluginAPI.hpp b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/plugins/PluginAPI.hppnew file mode 100644index 0000000000..8cc8b9cd6c--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/mock-hyprland/src/plugins/PluginAPI.hpp@@ -0,0 +1,3 @@+#pragma once++#include "../../mock.hpp"diff --git a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.pynew file mode 100644index 0000000000..ae104b5e1b--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle.py@@ -0,0 +1,182 @@+"""Test discovery lifecycle in two owned, disposable nested Hyprland processes.++Requires a matching prebuilt module and an active Wayland parent. Never loads+the module into the parent or edits its configuration. This is not a direct-DRM,+application-delivery, package-installation, or physical-input test.+"""++import argparse+import hashlib+import json+import os+import subprocess+import sys+import tempfile+import time+from pathlib import Path++import live_discovery as live+++def command(*args, env=None):+ return subprocess.check_output(args, env=env, text=True, timeout=10).strip()+++def wait_for(check, description):+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ value = check()+ if value:+ return value+ time.sleep(0.1)+ raise TimeoutError(description)+++class NestedCompositor:+ def __init__(self, directory, binary, module):+ self.directory = directory+ self.binary = binary+ self.module = module+ self.process = None+ self.log = None+ self.instance = None+ self.metadata = None+ directory.mkdir()+ self.config = directory / "hyprland.lua"+ self.config.write_text("hl.config({plugin = {cua = {enabled = true}}})\n")++ def ctl(self, *args):+ if not self.instance:+ raise RuntimeError("owned compositor has no instance")+ return command("hyprctl", "-i", self.instance, *args)++ def start(self):+ if self.process is not None:+ raise RuntimeError("compositor already started")+ env = dict(os.environ, AQ_BACKEND="wayland")+ env.pop("HYPRLAND_INSTANCE_SIGNATURE", None)+ self.log = (self.directory / "compositor.log").open("a")+ try:+ self.process = subprocess.Popen(+ [self.binary, "--config", str(self.config)],+ env=env,+ stdout=self.log,+ stderr=subprocess.STDOUT,+ )+ except OSError:+ self.log.close()+ raise++ def ready():+ if self.process.poll() is not None:+ raise RuntimeError(f"nested compositor exited; see {self.directory}")+ instances = json.loads(command("hyprctl", "-j", "instances"))+ matches = [i for i in instances if i["pid"] == self.process.pid]+ if len(matches) == 1:+ self.instance = matches[0]["instance"]+ try:+ json.loads(self.ctl("-j", "version"))+ return True+ except (subprocess.CalledProcessError, json.JSONDecodeError):+ return False+ return False++ wait_for(ready, "owned nested compositor did not become ready")+ assert self.ctl("plugin", "load", str(self.module)) == "ok"+ assert self.ctl("reload") == "ok"+ env = dict(os.environ, HYPRLAND_INSTANCE_SIGNATURE=self.instance)+ result = json.loads(command(sys.executable, str(Path(live.__file__)), env=env))+ assert result["mutation_refusals"] == 6+ assert result["compositor_state_unchanged"] is True+ self.metadata = json.loads(self.ctl("-j", "cua:status"))+ assert self.metadata["transport"]["ready"] and self.metadata["abi"]["match"]+ return self.metadata++ def stop(self):+ if self.process is None:+ return+ process = self.process+ try:+ process.terminate()+ try:+ process.wait(timeout=15)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=5)+ raise RuntimeError("nested compositor required forced termination")+ if self.metadata:+ path = Path(self.metadata["transport"]["socket"])+ assert not path.exists(), "clean shutdown left a discovery socket"+ finally:+ self.log.close()+ self.process = None+ self.instance = None+ self.metadata = None+++def run(module, directory, binary):+ if not __debug__:+ raise RuntimeError("assertions must be enabled; do not run Python with -O")+ parent = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")+ if not parent or not os.environ.get("WAYLAND_DISPLAY"):+ raise RuntimeError("run inside a disposable Hyprland Wayland parent session")+ parent_version = json.loads(command("hyprctl", "-i", parent, "-j", "version"))+ first = NestedCompositor(directory / "first", binary, module)+ second = NestedCompositor(directory / "second", binary, module)+ try:+ a_info = first.start()+ b_info = second.start()+ assert a_info["transport"]["socket"] != b_info["transport"]["socket"]+ assert a_info["compositor_epoch"] != b_info["compositor_epoch"]+ with live.connect(a_info) as a, live.connect(b_info) as b:+ assert live.exchange(a, 3, 2) == (4, b"")+ second.stop()+ assert b.recv(1) == b"", "shutdown left old connection open"+ assert live.exchange(a, 3, 3) == (4, b"")+ c_info = second.start()+ assert c_info["transport"]["socket"] != b_info["transport"]["socket"]+ assert c_info["compositor_epoch"] not in (+ a_info["compositor_epoch"],+ b_info["compositor_epoch"],+ )+ with live.connect(c_info) as c:+ assert live.exchange(c, 3, 2) == (4, b"")+ second.stop()+ assert live.exchange(a, 3, 4) == (4, b"")+ finally:+ try:+ second.stop()+ finally:+ first.stop()+ assert json.loads(command("hyprctl", "-i", parent, "-j", "version")) == parent_version+ return {+ "result": "passed",+ "module_sha256": hashlib.sha256(module.read_bytes()).hexdigest(),+ "hyprland_version": parent_version["version"],+ "two_owned_compositors": True,+ "mutation_refusals_per_start": 6,+ "clean_restart": True,+ "old_connection_closed": True,+ "old_socket_removed": True,+ "fresh_socket_and_epoch": True,+ "sibling_connection_survived": True,+ "parent_responsive": True,+ "owned_compositors_stopped": True,+ "application_delivery_tested": False,+ "physical_input_isolation_tested": False,+ }+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--module", required=True, type=Path)+ parser.add_argument("--hyprland", default="Hyprland")+ args = parser.parse_args()+ module = args.module.resolve(strict=True)+ directory = Path(tempfile.mkdtemp(prefix="cua-plugin-lifecycle-"))+ print(f"Lifecycle logs: {directory}", file=sys.stderr)+ print(json.dumps(run(module, directory, args.hyprland)))+++if __name__ == "__main__":+ main()diff --git a/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.pynew file mode 100644index 0000000000..bc2ca52710--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/nested_lifecycle_test.py@@ -0,0 +1,90 @@+"""Control-flow tests; native lifecycle evidence comes from nested_lifecycle.py."""++import os+import subprocess+import tempfile+import unittest+from pathlib import Path+from unittest.mock import Mock, patch++import nested_lifecycle as lifecycle+++class LifecycleTest(unittest.TestCase):+ def test_failed_launch_closes_log(self):+ with tempfile.TemporaryDirectory() as root:+ compositor = lifecycle.NestedCompositor(+ Path(root) / "child", "Hyprland", Path("plugin.so")+ )+ with patch.object(subprocess, "Popen", side_effect=FileNotFoundError):+ with self.assertRaises(FileNotFoundError):+ compositor.start()+ self.assertTrue(compositor.log.closed)+ self.assertIsNone(compositor.process)++ def test_ctl_requires_owned_instance(self):+ with tempfile.TemporaryDirectory() as root:+ compositor = lifecycle.NestedCompositor(+ Path(root) / "child", "Hyprland", Path("plugin.so")+ )+ with self.assertRaisesRegex(RuntimeError, "no instance"):+ compositor.ctl("reload")++ def test_stop_without_process_is_safe(self):+ with tempfile.TemporaryDirectory() as root:+ compositor = lifecycle.NestedCompositor(+ Path(root) / "child", "Hyprland", Path("plugin.so")+ )+ compositor.stop()++ def test_forced_shutdown_is_failure_and_reaps_owned_process(self):+ with tempfile.TemporaryDirectory() as root:+ compositor = lifecycle.NestedCompositor(+ Path(root) / "child", "Hyprland", Path("plugin.so")+ )+ process = Mock()+ process.wait.side_effect = [subprocess.TimeoutExpired("Hyprland", 15), 0]+ log = Mock()+ compositor.process, compositor.log = process, log+ with self.assertRaisesRegex(RuntimeError, "forced termination"):+ compositor.stop()+ process.terminate.assert_called_once()+ process.kill.assert_called_once()+ self.assertEqual(process.wait.call_count, 2)+ log.close.assert_called_once()+ self.assertIsNone(compositor.process)++ @patch.dict(os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "parent", "WAYLAND_DISPLAY": "parent"})+ @patch.object(lifecycle, "command", return_value='{"version":"test"}')+ @patch.object(lifecycle, "NestedCompositor")+ def test_start_failure_stops_both_owned_children(self, factory, _command):+ first, second = Mock(), Mock()+ factory.side_effect = [first, second]+ second.start.side_effect = RuntimeError("start failed")+ with self.assertRaisesRegex(RuntimeError, "start failed"):+ lifecycle.run(Path("plugin.so"), Path("logs"), "Hyprland")+ first.stop.assert_called_once()+ second.stop.assert_called_once()++ @patch.dict(os.environ, {"HYPRLAND_INSTANCE_SIGNATURE": "parent", "WAYLAND_DISPLAY": "parent"})+ @patch.object(lifecycle, "command", return_value='{"version":"test"}')+ @patch.object(lifecycle, "NestedCompositor")+ def test_cleanup_failure_still_stops_other_child(self, factory, _command):+ first, second = Mock(), Mock()+ factory.side_effect = [first, second]+ first.start.side_effect = RuntimeError("start failed")+ second.stop.side_effect = RuntimeError("cleanup failed")+ with self.assertRaisesRegex(RuntimeError, "cleanup failed"):+ lifecycle.run(Path("plugin.so"), Path("logs"), "Hyprland")+ first.stop.assert_called_once()++ @patch.dict(os.environ, {}, clear=True)+ def test_no_parent_fails_before_launch(self):+ with patch.object(lifecycle, "NestedCompositor") as factory:+ with self.assertRaisesRegex(RuntimeError, "parent session"):+ lifecycle.run(Path("plugin.so"), Path("logs"), "Hyprland")+ factory.assert_not_called()+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp b/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cppnew file mode 100644index 0000000000..d0edfa54e2--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/plugin_api_test.cpp@@ -0,0 +1,193 @@+#include "mock-hyprland/mock.hpp"++#include <algorithm>+#include <array>+#include <cerrno>+#include <cstdlib>+#include <iostream>+#include <stdexcept>+#include <string>+#include <sys/stat.h>+#include <unistd.h>++extern "C" std::string pluginAPIVersion();+extern "C" PLUGIN_DESCRIPTION_INFO pluginInit(HANDLE handle);+extern "C" void pluginExit();++namespace {++void check(bool condition, const std::string& message) {+ if (condition)+ return;+ std::cerr << "FAIL: " << message << '\n';+ std::exit(1);+}++void reset_registered_command() {+#if CUA_HYPRLAND_SOCKET1_API+ HyprlandAPI::registered_command.reset();+#else+ HyprlandAPI::registered_legacy_command.reset();+#endif+}++bool status_command_registered() {+#if CUA_HYPRLAND_SOCKET1_API+ return HyprlandAPI::registered_command &&+ HyprlandAPI::registered_command->name == "cua:status" &&+ HyprlandAPI::registered_command->match ==+ IPC::Socket1::COMMAND_MATCH_EXACT;+#else+ return HyprlandAPI::registered_legacy_command &&+ HyprlandAPI::registered_legacy_command->name == "cua:status" &&+ HyprlandAPI::registered_legacy_command->exact;+#endif+}++std::string json_status() {+#if CUA_HYPRLAND_SOCKET1_API+ const auto response = HyprlandAPI::registered_command->handler(+ IPC::Socket1::SRequest{.format = IPC::Socket1::FORMAT_JSON});+ return std::get<std::string>(response.result);+#else+ return HyprlandAPI::registered_legacy_command->fn(FORMAT_JSON, {});+#endif+}++struct RuntimeTree {+ std::string root;+ std::string hypr;+ std::string instance;+ std::string socket;+};++RuntimeTree make_runtime_tree() {+ std::array<char, 64> pattern{};+ const auto seed = std::string{"/tmp/cua-hyprland-plugin-api-XXXXXX"};+ std::copy(seed.begin(), seed.end(), pattern.begin());+ const auto* root = mkdtemp(pattern.data());+ check(root != nullptr, "plugin API test runtime directory created");++ RuntimeTree tree{+ .root = root,+ .hypr = std::string{root} + "/hypr",+ .instance = std::string{root} + "/hypr/mock-instance",+ .socket = std::string{root} ++ "/hypr/mock-instance/cua-inject-v2.sock",+ };+ check(mkdir(tree.hypr.c_str(), 0700) == 0,+ "plugin API test Hyprland directory created");+ check(mkdir(tree.instance.c_str(), 0700) == 0,+ "plugin API test instance directory created");+ return tree;+}++void remove_runtime_tree(const RuntimeTree& tree) {+ check(rmdir(tree.instance.c_str()) == 0,+ "plugin API test instance directory removed");+ check(rmdir(tree.hypr.c_str()) == 0,+ "plugin API test Hyprland directory removed");+ check(rmdir(tree.root.c_str()) == 0,+ "plugin API test runtime directory removed");+}++} // namespace++int main() {+ check(pluginAPIVersion() == HYPRLAND_API_VERSION,+ "plugin exports the expected Hyprland API version");++ HyprlandAPI::runtime_abi_hash = __hyprland_api_get_client_hash();+ const auto description = pluginInit(nullptr);+ check(description.name == "cua-hyprland-plugin" &&+ description.version == "0.1.0",+ "matching ABI initializes plugin metadata");+ check(status_command_registered(),+ "plugin registers the exact status command");++ const auto json_text = json_status();+ check(json_text.find(R"("state":"discovery_only")") !=+ std::string::npos &&+ json_text.find(R"("configured":false)") !=+ std::string::npos &&+ json_text.find(R"("compositor_epoch":0)") !=+ std::string::npos &&+ json_text.find(R"("enabled":[])") != std::string::npos,+ "disabled plugin status cannot advertise mutation or transport readiness");+ check(Event::bus()->m_events.config.reloaded.active_count() == 1,+ "plugin owns one config-reload listener while loaded");+ pluginExit();+ const auto deliveries_after_exit =+ Event::bus()->m_events.config.reloaded.delivery_count();+ check(Event::bus()->m_events.config.reloaded.active_count() == 0,+ "plugin unload unregisters its config-reload listener");+ Event::bus()->m_events.config.reloaded.emit();+ check(Event::bus()->m_events.config.reloaded.delivery_count() ==+ deliveries_after_exit,+ "config reload after unload cannot call plugin code");++ reset_registered_command();+ HyprlandAPI::runtime_abi_hash = "different-hyprland-abi";+ bool fingerprint_mismatch_rejected = false;+ try {+ static_cast<void>(pluginInit(nullptr));+ } catch (const std::runtime_error& error) {+ fingerprint_mismatch_rejected =+ std::string{error.what()}.find("ABI fingerprint mismatch") !=+ std::string::npos;+ }+ check(fingerprint_mismatch_rejected,+ "runtime Hyprland ABI fingerprint mismatch fails initialization");+ check(!status_command_registered(),+ "ABI fingerprint mismatch registers no status command");++ HyprlandAPI::runtime_abi_hash = __hyprland_api_get_client_hash();+ Config::Values::configured_bool_override = true;+ const auto runtime = make_runtime_tree();+ check(setenv("XDG_RUNTIME_DIR", runtime.root.c_str(), 1) == 0 &&+ setenv("HYPRLAND_INSTANCE_SIGNATURE", "mock-instance", 1) == 0,+ "plugin API test runtime environment configured");+ static_cast<void>(pluginInit(nullptr));+ Event::bus()->m_events.config.reloaded.emit();+ const auto ready_text = json_status();+ struct stat socket_metadata{};+ check(ready_text.find(R"("configured":true)") != std::string::npos &&+ ready_text.find(R"("ready":true)") != std::string::npos &&+ ready_text.find(R"("compositor_epoch":0)") == std::string::npos &&+ lstat(runtime.socket.c_str(), &socket_metadata) == 0 &&+ S_ISSOCK(socket_metadata.st_mode),+ "post-init config reload starts the enabled discovery transport");+ pluginExit();+ check(lstat(runtime.socket.c_str(), &socket_metadata) != 0 && errno == ENOENT,+ "plugin unload removes its transport socket");+ remove_runtime_tree(runtime);++ reset_registered_command();+ const auto insecure_runtime = make_runtime_tree();+ check(chmod(insecure_runtime.hypr.c_str(), 0755) == 0,+ "plugin API test made an insecure runtime component");+ check(setenv("XDG_RUNTIME_DIR", insecure_runtime.root.c_str(), 1) == 0,+ "plugin API test selected the insecure runtime");+ static_cast<void>(pluginInit(nullptr));+ Event::bus()->m_events.config.reloaded.emit();+ const auto refused_text = json_status();+ check(refused_text.find(R"("ready":false)") != std::string::npos &&+ refused_text.find(R"("compositor_epoch":0)") !=+ std::string::npos &&+ refused_text.find("not a private, same-user directory") !=+ std::string::npos &&+ lstat(insecure_runtime.socket.c_str(), &socket_metadata) != 0 &&+ errno == ENOENT,+ "insecure runtime path fails closed without creating a socket");+ pluginExit();+ check(chmod(insecure_runtime.hypr.c_str(), 0700) == 0,+ "plugin API test restored runtime permissions for cleanup");+ remove_runtime_tree(insecure_runtime);++ Config::Values::configured_bool_override.reset();+ unsetenv("XDG_RUNTIME_DIR");+ unsetenv("HYPRLAND_INSTANCE_SIGNATURE");++ std::cout << "cua-hyprland-plugin API tests passed\n";+ return 0;+}diff --git a/libs/cua-driver/hyprland-plugin/tests/protocol_test.cpp b/libs/cua-driver/hyprland-plugin/tests/protocol_test.cppnew file mode 100644index 0000000000..bcf6c19bc7--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/protocol_test.cpp@@ -0,0 +1,212 @@+#include "cua_hyprland/protocol.hpp"+#include "cua_hyprland/session.hpp"++#include <cstdlib>+#include <iostream>+#include <limits>+#include <span>+#include <string>+#include <variant>++namespace {++void check(bool condition, const std::string& message) {+ if (condition)+ return;+ std::cerr << "FAIL: " << message << '\n';+ std::exit(1);+}++template <typename T>+const T& expect(const auto& value, const char* message) {+ check(std::holds_alternative<T>(value), message);+ return std::get<T>(value);+}++} // namespace++int main() {+ using namespace cua::hyprland;++ const auto hello = make_frame(+ MessageType::hello, 42,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ }));+ const auto bytes = encode_frame(hello);+ const auto decoded_result = decode_frame(bytes);+ const auto& decoded = expect<Frame>(decoded_result, "frame round trip");+ check(decoded.header.request_id == 42, "request ID round trip");+ const auto decoded_hello_result = decode_hello(decoded.payload);+ const auto& decoded_hello =+ expect<Hello>(decoded_hello_result, "HELLO round trip");+ check(decoded_hello.required_capabilities == capability(Capability::discovery),+ "HELLO capabilities round trip");++ check(std::get<DecodeError>(decode_frame({})) == DecodeError::frame_too_small,+ "empty frame rejected");++ const auto boundary_frame = make_frame(+ MessageType::error, std::numeric_limits<std::uint64_t>::max(),+ std::vector<std::byte>(kMaxPayloadSize, std::byte{0x5a}));+ const auto boundary_bytes = encode_frame(boundary_frame);+ check(boundary_bytes.size() == kMaxFrameSize,+ "maximum-sized frame encoded");+ const auto decoded_boundary_result = decode_frame(boundary_bytes);+ const auto& decoded_boundary =+ expect<Frame>(decoded_boundary_result, "maximum-sized frame decoded");+ check(decoded_boundary.header.request_id ==+ std::numeric_limits<std::uint64_t>::max() &&+ decoded_boundary.payload.size() == kMaxPayloadSize,+ "maximum-sized frame fields round trip");+ check(encode_frame(make_frame(+ MessageType::error, 1,+ std::vector<std::byte>(kMaxPayloadSize + 1, std::byte{0})))+ .empty(),+ "oversized payload cannot be encoded");++ auto bad_magic = bytes;+ bad_magic[0] = std::byte{'X'};+ check(std::get<DecodeError>(decode_frame(bad_magic)) == DecodeError::bad_magic,+ "bad magic rejected");++ auto future_version = bytes;+ future_version[5] = std::byte{3};+ check(std::get<DecodeError>(decode_frame(future_version)) ==+ DecodeError::unsupported_version,+ "future major version rejected");++ auto oversized_declared_payload = bytes;+ oversized_declared_payload[20] = std::byte{0};+ oversized_declared_payload[21] = std::byte{0};+ oversized_declared_payload[22] = std::byte{0x10};+ oversized_declared_payload[23] = std::byte{0x01};+ check(std::get<DecodeError>(decode_frame(oversized_declared_payload)) ==+ DecodeError::payload_too_large,+ "oversized declared payload rejected before size matching");++ auto nonzero_flags = bytes;+ nonzero_flags[11] = std::byte{1};+ check(std::get<DecodeError>(decode_frame(nonzero_flags)) ==+ DecodeError::nonzero_flags,+ "nonzero flags rejected");++ auto truncated = bytes;+ truncated.pop_back();+ check(std::get<DecodeError>(decode_frame(truncated)) == DecodeError::size_mismatch,+ "truncated frame rejected");++ const ServerInfo server{+ .compositor_epoch = 99,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ };++ Session before_hello;+ const auto handshake_error = before_hello.handle(+ make_frame(MessageType::ping, 1), server);+ check(handshake_error.header.type == MessageType::error,+ "pre-handshake request rejected");+ const auto decoded_handshake_error_result = decode_error(handshake_error.payload);+ const auto& decoded_handshake_error =+ expect<ProtocolError>(decoded_handshake_error_result,+ "handshake error decodes");+ check(decoded_handshake_error.code == ErrorCode::handshake_required,+ "handshake error is typed");++ Session unavailable;+ const auto unavailable_response = unavailable.handle(+ make_frame(+ MessageType::hello, 2,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::pointer_button),+ .required_capabilities = capability(Capability::pointer_button),+ })),+ server);+ const auto unavailable_error_result = decode_error(unavailable_response.payload);+ const auto& unavailable_error =+ expect<ProtocolError>(unavailable_error_result,+ "capability error decodes");+ check(unavailable_error.code == ErrorCode::capability_unavailable,+ "required mutation capability refused");+ check(!unavailable.handshaken(), "failed negotiation does not establish session");++ Session session;+ const auto welcome_response = session.handle(hello, server);+ check(welcome_response.header.type == MessageType::welcome,+ "HELLO receives WELCOME");+ const auto welcome_result = decode_welcome(welcome_response.payload);+ const auto& welcome = expect<Welcome>(welcome_result, "WELCOME decodes");+ check(welcome.compositor_epoch == 99, "WELCOME carries compositor epoch");+ check(welcome.enabled_capabilities == capability(Capability::discovery),+ "WELCOME carries negotiated capabilities");+ check(session.handshaken(), "session records successful handshake");++ const auto status_response =+ session.handle(make_frame(MessageType::status_request, 45), server);+ const auto status_result = decode_welcome(status_response.payload);+ const auto& status =+ expect<Welcome>(status_result, "STATUS_RESPONSE payload decodes");+ check(status_response.header.type == MessageType::status_response &&+ status.enabled_capabilities == capability(Capability::discovery),+ "STATUS_RESPONSE reports only session-negotiated capabilities");++ const ServerInfo revoked_server{+ .compositor_epoch = 99,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = 0,+ };+ const auto revoked_status_response = session.handle(+ make_frame(MessageType::status_request, 46), revoked_server);+ const auto revoked_status_result =+ decode_welcome(revoked_status_response.payload);+ const auto& revoked_status =+ expect<Welcome>(revoked_status_result, "revoked STATUS_RESPONSE decodes");+ check(revoked_status.enabled_capabilities == 0,+ "STATUS_RESPONSE reflects capability revocation without granting new bits");++ Session no_capabilities;+ const auto no_capabilities_welcome = no_capabilities.handle(+ make_frame(MessageType::hello, 47, encode_hello(Hello{})), server);+ const auto no_capabilities_result =+ decode_welcome(no_capabilities_welcome.payload);+ check(expect<Welcome>(no_capabilities_result,+ "zero-capability WELCOME decodes")+ .enabled_capabilities == 0,+ "session cannot gain a capability it did not request");+ const auto no_capabilities_status = no_capabilities.handle(+ make_frame(MessageType::status_request, 48), server);+ check(expect<Welcome>(decode_welcome(no_capabilities_status.payload),+ "zero-capability STATUS_RESPONSE decodes")+ .enabled_capabilities == 0,+ "status does not elevate a zero-capability session");++ const auto pong = session.handle(make_frame(MessageType::ping, 43), server);+ check(pong.header.type == MessageType::pong && pong.header.request_id == 43,+ "PING receives correlated PONG");++ const auto mutation = session.handle(+ make_frame(MessageType::pointer_button, 44), server);+ const auto mutation_error_result = decode_error(mutation.payload);+ const auto& mutation_error =+ expect<ProtocolError>(mutation_error_result, "mutation error decodes");+ check(mutation_error.code == ErrorCode::background_unavailable,+ "mutation remains fail-closed");++ const auto invalid_direction = session.handle(+ make_frame(MessageType::welcome, 49), server);+ const auto invalid_direction_error_result =+ decode_error(invalid_direction.payload);+ check(expect<ProtocolError>(invalid_direction_error_result,+ "invalid-direction error decodes")+ .code == ErrorCode::malformed_frame,+ "server-only message types are reported as malformed client requests");++ const auto long_error = encode_error(+ ProtocolError{ErrorCode::server_busy, std::string(kMaxPayloadSize * 2, 'x')});+ check(long_error.size() == kMaxPayloadSize, "error detail is bounded");++ std::cout << "cua-inject-v2 protocol tests passed\n";+ return 0;+}diff --git a/libs/cua-driver/hyprland-plugin/tests/status_test.cpp b/libs/cua-driver/hyprland-plugin/tests/status_test.cppnew file mode 100644index 0000000000..64181d66c8--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/status_test.cpp@@ -0,0 +1,93 @@+#include "cua_hyprland/status.hpp"++#include <cstdlib>+#include <iostream>+#include <string>++namespace {++void check(bool condition, const std::string& message) {+ if (condition)+ return;+ std::cerr << "FAIL: " << message << '\n';+ std::exit(1);+}++} // namespace++int main(int argc, char** argv) {+ const cua::hyprland::StatusReport report{+ .plugin_version = "0.1.0",+ .compositor_epoch = 42,+ .compiled_hash = "compiled\"hash",+ .runtime_hash = "runtime\\hash",+ .configured = true,+ .transport_ready = false,+ .socket_path = "/run/user/1000/hypr/test/cua.sock",+ .last_error = "line one\nline two",+ .discovery_enabled = false,+ .accepted_connections = 7,+ .rejected_peers = 2,+ .rejected_busy = 3,+ .timed_out_handshakes = 4,+ .timed_out_idle = 5,+ .malformed_frames = 1,+ };++ const auto json = cua::hyprland::render_status_json(report);+ if (argc == 2 && std::string{argv[1]} == "--json") {+ std::cout << json << '\n';+ return 0;+ }+ check(+ json ==+ R"({"name":"cua-hyprland-plugin","plugin_version":"0.1.0",)"+ R"("state":"discovery_only","protocol":{"major":2,"minor":0,)"+ R"("max_frame_bytes":4120},"compositor_epoch":42,"abi":{)"+ R"("compiled_hash":"compiled\"hash","runtime_hash":"runtime\\hash",)"+ R"("match":false},"configured":true,"transport":{"ready":false,)"+ R"("socket":"/run/user/1000/hypr/test/cua.sock","mode":"0600",)"+ R"("peer_policy":"same_uid","last_error":"line one\nline two"},)"+ R"("capabilities":{"supported":["discovery"],"enabled":[],)"+ R"("mutation":"disabled_pending_rfc_and_agent_seat"},)"+ R"("connections":{"accepted":7,"rejected_peers":2,)"+ R"("rejected_busy":3,"timed_out_handshakes":4,)"+ R"("timed_out_idle":5,"malformed_frames":1}})",+ "status JSON is stable, escaped, and structurally complete");++ check(cua::hyprland::render_status_text(report) ==+ "cua-hyprland-plugin 0.1.0\nconfigured: yes\ntransport: stopped\n"+ "socket: /run/user/1000/hypr/test/cua.sock\n"+ "last error: line one\\nline two\nprotocol: 2.0\n"+ "compositor epoch: 42\n"+ "ABI compiled: compiled\\\"hash\n"+ "ABI runtime: runtime\\\\hash\n"+ "ABI match: no\n"+ "connections: accepted=7, rejected_peers=2, rejected_busy=3, "+ "timed_out_handshakes=4, timed_out_idle=5, malformed_frames=1\n"+ "capabilities: discovery only; background mutation disabled\n",+ "plain status is stable");++ std::string unusual_error = "valid:";+ unusual_error += "\xc3\xa9";+ unusual_error += ":invalid:";+ unusual_error.push_back(static_cast<char>(0x80));+ unusual_error.push_back(static_cast<char>(0x7f));+ const auto unusual_json = cua::hyprland::render_status_json(+ cua::hyprland::StatusReport{+ .plugin_version = "0.1.0",+ .compiled_hash = "same",+ .runtime_hash = "same",+ .last_error = unusual_error,+ });+ check(unusual_json.find("valid:\xc3\xa9:invalid:\\u0080\\u007f") !=+ std::string::npos &&+ unusual_json.find(R"("match":true)") != std::string::npos,+ "status preserves valid UTF-8 and escapes invalid bytes");+ check(cua::hyprland::is_valid_utf8("\xc3\xa9") &&+ !cua::hyprland::is_valid_utf8(std::string_view{"\x80", 1}),+ "UTF-8 validation distinguishes valid and invalid runtime paths");++ std::cout << "cua-hyprland-plugin status tests passed\n";+ return 0;+}diff --git a/libs/cua-driver/hyprland-plugin/tests/transport_test.cpp b/libs/cua-driver/hyprland-plugin/tests/transport_test.cppnew file mode 100644index 0000000000..f15d14256c--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/transport_test.cpp@@ -0,0 +1,401 @@+#include "cua_hyprland/protocol.hpp"+#include "cua_hyprland/session.hpp"+#include "inject_server.hpp"++#include <array>+#include <algorithm>+#include <cstdlib>+#include <chrono>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <span>+#include <string>+#include <thread>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/un.h>+#include <unistd.h>+#include <variant>++namespace {++void check(bool condition, const std::string& message) {+ if (condition)+ return;+ std::cerr << "FAIL: " << message << '\n';+ std::exit(1);+}++class TempDirectory {+ public:+ TempDirectory() {+ std::array<char, 64> pattern{};+ const auto seed = std::string{"/tmp/cua-hyprland-transport-XXXXXX"};+ std::copy(seed.begin(), seed.end(), pattern.begin());+ const auto* path = mkdtemp(pattern.data());+ check(path != nullptr, "temporary directory created");+ m_path = path;+ }++ ~TempDirectory() {+ static_cast<void>(rmdir(m_path.c_str()));+ }++ std::filesystem::path path() const { return m_path; }++ private:+ std::filesystem::path m_path;+};++int connect_client(const std::string& socket_path) {+#ifdef __linux__+ constexpr int socket_type = SOCK_SEQPACKET;+#else+ constexpr int socket_type = SOCK_STREAM;+#endif+ const auto fd = socket(AF_UNIX, socket_type, 0);+ check(fd >= 0, "client socket created");++ sockaddr_un address{};+ address.sun_family = AF_UNIX;+ check(socket_path.size() < sizeof(address.sun_path), "test socket path fits");+ std::copy(socket_path.begin(), socket_path.end(), address.sun_path);+ check(connect(fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == 0,+ "client connected");+ return fd;+}++void send_request(int fd, const cua::hyprland::Frame& frame) {+ const auto bytes = cua::hyprland::encode_frame(frame);+#ifdef MSG_NOSIGNAL+ constexpr int no_signal = MSG_NOSIGNAL;+#else+ constexpr int no_signal = 0;+#endif+ check(send(fd, bytes.data(), bytes.size(), no_signal) ==+ static_cast<ssize_t>(bytes.size()),+ "request sent");+}++void send_bytes(int fd, std::span<const std::byte> bytes) {+#ifdef MSG_NOSIGNAL+ constexpr int no_signal = MSG_NOSIGNAL;+#else+ constexpr int no_signal = 0;+#endif+ check(send(fd, bytes.data(), bytes.size(), no_signal) ==+ static_cast<ssize_t>(bytes.size()),+ "raw packet sent");+}++cua::hyprland::Frame receive_response(int fd) {+ std::array<std::byte, cua::hyprland::kMaxFrameSize> bytes{};+ const auto received = recv(fd, bytes.data(), bytes.size(), 0);+ check(received > 0, "response received");+ const auto decoded = cua::hyprland::decode_frame(+ std::span<const std::byte>{bytes.data(), static_cast<std::size_t>(received)});+ check(std::holds_alternative<cua::hyprland::Frame>(decoded),+ "response frame decoded");+ return std::get<cua::hyprland::Frame>(decoded);+}++} // namespace++int main() {+ using namespace cua::hyprland;++ TempDirectory temporary;+ const auto socket_path = (temporary.path() / "cua-inject-v2.sock").string();+ InjectionServer server{+ socket_path,+ ServerInfo{+ .compositor_epoch = 77,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ }};+ const auto started = server.start();+ check(started, "server started: " + server.snapshot().last_error);++ struct stat metadata{};+ check(lstat(socket_path.c_str(), &metadata) == 0 && S_ISSOCK(metadata.st_mode),+ "server created a Unix socket");+ check((metadata.st_mode & 0777) == 0600, "socket mode is 0600");++ const auto bad_magic_client = connect_client(socket_path);+ auto bad_magic_bytes = encode_frame(make_frame(+ MessageType::hello, 8, encode_hello(Hello{})));+ bad_magic_bytes[0] = std::byte{'X'};+ send_bytes(bad_magic_client, bad_magic_bytes);+ const auto bad_magic_response = receive_response(bad_magic_client);+ const auto bad_magic_error = decode_error(bad_magic_response.payload);+ check(bad_magic_response.header.request_id == 0 &&+ std::holds_alternative<ProtocolError>(bad_magic_error) &&+ std::get<ProtocolError>(bad_magic_error).code ==+ ErrorCode::malformed_frame,+ "wire-level bad magic returns an uncorrelated malformed-frame error");+ close(bad_magic_client);++ const auto future_client = connect_client(socket_path);+ auto future_bytes = encode_frame(make_frame(+ MessageType::hello, 9, encode_hello(Hello{})));+ future_bytes[4] = std::byte{0};+ future_bytes[5] = std::byte{3};+ send_bytes(future_client, future_bytes);+ const auto future_response = receive_response(future_client);+ const auto future_error = decode_error(future_response.payload);+ check(future_response.header.request_id == 9 &&+ std::holds_alternative<ProtocolError>(future_error) &&+ std::get<ProtocolError>(future_error).code ==+ ErrorCode::unsupported_version,+ "wire-level future major returns a correlated version error");+ close(future_client);++#ifdef __linux__+ const auto oversized_client = connect_client(socket_path);+ const std::vector<std::byte> oversized_packet(kMaxFrameSize + 1,+ std::byte{0x5a});+ send_bytes(oversized_client, oversized_packet);+ close(oversized_client);++ const auto zero_length_client = connect_client(socket_path);+ send_bytes(zero_length_client, {});+ close(zero_length_client);+#endif++ const auto client = connect_client(socket_path);+ send_request(+ client,+ make_frame(+ MessageType::hello, 10,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ })));+ const auto welcome_frame = receive_response(client);+ check(welcome_frame.header.type == MessageType::welcome,+ "same-UID client negotiated a session");+ const auto welcome = decode_welcome(welcome_frame.payload);+ check(std::holds_alternative<Welcome>(welcome) &&+ std::get<Welcome>(welcome).compositor_epoch == 77,+ "server returned the current compositor epoch");++ send_request(client, make_frame(MessageType::pointer_button, 11));+ const auto refusal_frame = receive_response(client);+ const auto refusal = decode_error(refusal_frame.payload);+ check(std::holds_alternative<ProtocolError>(refusal) &&+ std::get<ProtocolError>(refusal).code ==+ ErrorCode::background_unavailable,+ "mutation returned typed background_unavailable");+ close(client);++#ifdef __linux__+ for (int attempt = 0;+ attempt < 100 && server.snapshot().malformed_frames < 3;+ ++attempt)+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ check(server.snapshot().malformed_frames == 3,+ "wire-level malformed, unsupported, and oversized packets counted");+#else+ check(server.snapshot().malformed_frames == 2,+ "wire-level malformed and unsupported packets counted");+#endif++ const auto long_lived_client = connect_client(socket_path);+ send_request(+ long_lived_client,+ make_frame(+ MessageType::hello, 13,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ })));+ check(receive_response(long_lived_client).header.type == MessageType::welcome,+ "long-lived client negotiated before transport restart");+ server.stop();+ check(!std::filesystem::exists(socket_path), "owned socket removed on stop");+ std::array<std::byte, 1> closed_probe{};+ check(recv(long_lived_client, closed_probe.data(), closed_probe.size(), 0) == 0,+ "long-lived client observed transport shutdown");+ close(long_lived_client);++ InjectionServer restarted_server{+ socket_path,+ ServerInfo{+ .compositor_epoch = 78,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ }};+ check(restarted_server.start(),+ "restarted server started: " + restarted_server.snapshot().last_error);+ const auto reconnected_client = connect_client(socket_path);+ send_request(+ reconnected_client,+ make_frame(+ MessageType::hello, 14,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ })));+ const auto reconnected_welcome = receive_response(reconnected_client);+ const auto reconnected_welcome_payload =+ decode_welcome(reconnected_welcome.payload);+ check(std::holds_alternative<Welcome>(reconnected_welcome_payload) &&+ std::get<Welcome>(reconnected_welcome_payload).compositor_epoch == 78,+ "reconnected client negotiated the replacement transport epoch");+ close(reconnected_client);+ restarted_server.stop();++ const auto busy_socket_path =+ (temporary.path() / "cua-inject-v2-busy.sock").string();+ InjectionServer busy_server{+ busy_socket_path,+ ServerInfo{+ .compositor_epoch = 79,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ }};+ check(busy_server.start(),+ "busy-test server started: " + busy_server.snapshot().last_error);++ std::array<int, 8> held_clients{};+ for (auto& held_client : held_clients)+ held_client = connect_client(busy_socket_path);+ for (int attempt = 0;+ attempt < 100 && busy_server.snapshot().accepted_connections < 8;+ ++attempt)+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ check(busy_server.snapshot().accepted_connections == 8,+ "server accepted eight concurrent held clients");++ const auto excess_client = connect_client(busy_socket_path);+ const auto busy_frame = receive_response(excess_client);+ const auto busy = decode_error(busy_frame.payload);+ check(busy_frame.header.type == MessageType::error &&+ std::holds_alternative<ProtocolError>(busy) &&+ std::get<ProtocolError>(busy).code == ErrorCode::server_busy,+ "excess client received typed server_busy refusal");+ close(excess_client);+ for (const auto held_client : held_clients)+ close(held_client);++ busy_server.stop();+ check(!std::filesystem::exists(busy_socket_path),+ "busy-test socket removed on stop");+ check(busy_server.snapshot().rejected_busy == 1,+ "busy connection rejection was recorded");++ const auto timeout_socket_path =+ (temporary.path() / "cua-inject-v2-timeout.sock").string();+ InjectionServer timeout_server{+ timeout_socket_path,+ ServerInfo{+ .compositor_epoch = 80,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ },+ ServerOptions{.handshake_timeout = std::chrono::milliseconds{30}}};+ check(timeout_server.start(),+ "timeout-test server started: " + timeout_server.snapshot().last_error);+ std::array<int, 8> silent_clients{};+ for (auto& silent_client : silent_clients)+ silent_client = connect_client(timeout_socket_path);+ for (int attempt = 0;+ attempt < 100 && timeout_server.snapshot().timed_out_handshakes < 8;+ ++attempt)+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ check(timeout_server.snapshot().timed_out_handshakes == 8,+ "silent pre-handshake clients were reaped");+ const auto admitted_after_timeout = connect_client(timeout_socket_path);+ send_request(+ admitted_after_timeout,+ make_frame(+ MessageType::hello, 12,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ })));+ check(receive_response(admitted_after_timeout).header.type ==+ MessageType::welcome,+ "new client was admitted after handshake timeout cleanup");+ close(admitted_after_timeout);+ for (const auto silent_client : silent_clients)+ close(silent_client);+ timeout_server.stop();++ const auto idle_socket_path =+ (temporary.path() / "cua-inject-v2-idle.sock").string();+ InjectionServer idle_server{+ idle_socket_path,+ ServerInfo{+ .compositor_epoch = 82,+ .supported_capabilities = capability(Capability::discovery),+ .enabled_capabilities = capability(Capability::discovery),+ },+ ServerOptions{+ .handshake_timeout = std::chrono::milliseconds{1000},+ .idle_timeout = std::chrono::milliseconds{30},+ }};+ check(idle_server.start(),+ "idle-test server started: " + idle_server.snapshot().last_error);+ const auto idle_client = connect_client(idle_socket_path);+ send_request(+ idle_client,+ make_frame(+ MessageType::hello, 15,+ encode_hello(Hello{+ .requested_capabilities = capability(Capability::discovery),+ .required_capabilities = capability(Capability::discovery),+ })));+ check(receive_response(idle_client).header.type == MessageType::welcome,+ "idle-test client negotiated a session");+ for (int attempt = 0;+ attempt < 100 && idle_server.snapshot().timed_out_idle < 1;+ ++attempt)+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ check(idle_server.snapshot().timed_out_idle == 1,+ "idle handshaken client was reaped");+ std::array<std::byte, 1> idle_probe{};+ check(recv(idle_client, idle_probe.data(), idle_probe.size(), 0) == 0,+ "idle client observed timeout shutdown");+ close(idle_client);+ idle_server.stop();++ const auto replaced_socket_path =+ (temporary.path() / "cua-inject-v2-replaced.sock").string();+ InjectionServer replaced_server{+ replaced_socket_path, ServerInfo{.compositor_epoch = 81}};+ check(replaced_server.start(),+ "replacement-test server started: " ++ replaced_server.snapshot().last_error);+ check(std::filesystem::remove(replaced_socket_path),+ "test removed the original socket directory entry");+ {+ std::ofstream replacement{replaced_socket_path};+ replacement << "replacement must survive server shutdown";+ }+ replaced_server.stop();+ check(std::filesystem::is_regular_file(replaced_socket_path),+ "server did not remove a replacement path");+ check(replaced_server.snapshot().last_error ==+ "socket path identity changed; refusing to unlink it",+ "replacement refusal is observable in status");+ check(std::filesystem::remove(replaced_socket_path),+ "test removed the preserved replacement path");++ const auto occupied_path = (temporary.path() / "occupied").string();+ {+ std::ofstream occupied{occupied_path};+ occupied << "not a socket";+ }+ InjectionServer collision{occupied_path, ServerInfo{.compositor_epoch = 88}};+ check(!collision.start(), "pre-existing path refused");+ collision.stop();+ check(std::filesystem::is_regular_file(occupied_path),+ "failed start did not remove an unowned path");+ check(std::filesystem::remove(occupied_path),+ "test removed the preserved occupied path");++ std::cout << "cua-inject-v2 transport tests passed\n";+ return 0;+}diff --git a/libs/cua-driver/hyprland-plugin/tests/validation.md b/libs/cua-driver/hyprland-plugin/tests/validation.mdnew file mode 100644index 0000000000..0b6f164631--- /dev/null+++ b/libs/cua-driver/hyprland-plugin/tests/validation.md@@ -0,0 +1,247 @@+# Discovery foundation validation++The discovery-only plugin passed a native build and lifecycle checks on Cua+Cloud Fleet on September 4, 2026. These results support review of the foundation;+the full promotion gates in [the test plan](README.md) remain open.++The [September 5 merge-readiness pass](#merge-readiness-revalidation-september-5-2026)+records a fresh candidate build and the remaining system-installation gate.++## Candidate and environment++The tested source was based on Cua commit+`4da67bb61c262c663fa88559d1d3f1a138b3a463`. The 27-file plugin tree had SHA-256+`32c4c2224bcf260921083797a4c5bfd72dbca0ced70cbd0d24738de2caf83007`.+This digest hashes sorted relative file paths and raw file contents, each+followed by a NUL byte. It excludes this subsequently added validation report.++| Component | Tested value |+| ------------------------------ | --------------------- |+| Plugin | `0.1.0` |+| Omarchy | `4.0.1-1` |+| Hyprland | `0.56.2-1` |+| xdg-desktop-portal-hyprland | `1.4.1-1` |+| Installed Cua Driver | `0.22.2` |+| Compositor and plugin compiler | GCC `16.1.1 20260728` |+| CMake / Ninja | `4.4.3` / `1.13.2` |+| Shared C++ runtime | `libstdc++.so.6.0.36` |++This Fleet image matches the Hyprland baseline but has older Omarchy and+Cua Driver versions than the complete acceptance target. Driver integration+was not exercised by this plugin run.++The exact compiler package was selected from Hyprland's package build metadata+and its Arch signature verified. The plugin used the shared C++ runtime already+loaded by the compositor. The actual Arch recipe ran with `makepkg --nodeps`+because CMake and Ninja were task-local Python wheels. Its independent checks+for installed Hyprland and header versions still ran.++| Artifact | SHA-256 |+| --------------- | ------------------------------------------------------------------ |+| Arch package | `a9e401ca9ac1c1f0532519f74a650e84ff679ce2e29ab8751b85903e1e0a7e99` |+| Packaged module | `842a4aa768e95434bba7c9ac2c56c4846a518f0cff883f8c9fee7b2480736f43` |++## Results++- Native package build and `check()`: six of six CTests passed, including the+ production Linux `SOCK_SEQPACKET` transport.+- Package inventory: shared module and license, plus package metadata; exact+ `hyprland=0.56.2-1` dependency; no configuration edits or autoload.+- Real Hyprland load: matching ABI fingerprints, disabled initial transport,+ and enabled discovery socket with mode `0600` after config reload.+- Ten consecutive live unload/reload cycles: all six mutation types returned+ `background_unavailable`, measured compositor state stayed unchanged, old+ connections closed, and replacement transports published fresh epochs.+- Disable/re-enable: socket and client closed, disabled epoch became zero,+ and re-enabling created a fresh epoch.+- Synthetic ABI mismatch: altering the compiled fingerprint caused explicit+ load refusal before command/socket registration. The matching module loaded+ afterward. This was not a second real Hyprland version.+- Supplemental native transport fixture: same-UID acceptance, different-UID+ rejection through `SO_PEERCRED`, and independent sockets/epochs. Only that+ fixture's permissions were relaxed to test peer rejection independently of+ filesystem access. This was not two simultaneous compositor instances.+- macOS review-host suites: six of six tests passed in normal, ASan/UBSan, and+ TSan configurations. macOS uses a transport shim and mocked compositor APIs.++The reusable live check is [live_discovery.py](live_discovery.py). It measures+active-window identity, workspace, cursor coordinates, window geometry/mapping,+and focus history. It does not prove application delivery, complete stacking+order, physical input isolation, or behavior during an active foreground grab.+The peer and synthetic ABI checks were supplemental fixtures; they are not+claimed as automated by that script.++## Runtime-linkage failure investigated++An earlier compiler staging directory omitted its separately packaged shared+runtime. GCC selected `libstdc++.a`; a later reload of that module hung+Hyprland. Debugger attachment was unavailable, so static linkage remains the+leading suspected cause rather than a backtrace-confirmed diagnosis.++Correcting the runtime search path produced a module linked to the compositor's+shared C++ runtime. A fresh Fleet passed the repeated lifecycle checks above.+The build now rejects modules without a shared C++ runtime dependency.++## Follow-up at `3789f0e6e`++A second Fleet run on September 4, 2026 (September 5 UTC), tested commit+`3789f0e6eeb350587fe48c4da35b327975a5bd9c` through the Cua Sandbox SDK.+The image had the same component versions listed above. The source archive+contained the committed plugin directory and repository license, with SHA-256+`27835f9192a35d9b721396642e91a81eb18088075d15c5b4ed2f1f912e159aa4`.++The matching signed compiler package and shared runtime were used again.+The Arch recipe built successfully with `makepkg --nodeps`; all six native+CTests passed. The downloaded artifacts matched the guest hashes:++| Artifact | SHA-256 |+| --------------- | ------------------------------------------------------------------ |+| Arch package | `2c4881b4a17aef554edcaa1181f73ae2453e39b05c7bb5169db8ae9be34adebf` |+| Packaged module | `693d6470a011956e58320de67fae8ed8d4628476e605f74cea018eb2eb5d5705` |++Additional native checks passed:++- Two simultaneous Hyprland `0.56.2` processes, nested under the Fleet desktop,+ exposed distinct discovery sockets and epochs. The live discovery harness+ passed all six mutation refusals and its compositor-state comparison in each.+- Restarting one nested compositor closed its old connection and removed its+ socket. Its replacement used a fresh instance socket and epoch. The other+ compositor's existing discovery connection remained responsive through both+ restart and shutdown of its sibling.+- A genuine Hyprland `0.56.1-3` Arch package, verified against its signature,+ ran as another nested compositor. Loading the unmodified `0.56.2` plugin+ explicitly failed with an ABI fingerprint mismatch. No plugin, status+ command, or discovery socket remained registered, and the compositor still+ answered version queries. This closes the earlier synthetic-only ABI gap+ for this specific version pair, not arbitrary upgrades.++The lifecycle orchestration was task-local; these additional checks are not+automated by `live_discovery.py` alone. Initial headless startup failed before+loading the plugin; nested Wayland startup succeeded. The nested tests do not+certify direct DRM startup, physical input, application delivery, or isolation+during a foreground grab. All input mutations remained disabled.++The SDK shell ran as an unprivileged desktop user. `sudo -n -l` required a+password, and the SDK shell interface provided no user-selection parameter.+System installation and upgrade-transaction checks therefore remain open;+package construction is not evidence of `pacman -U` installation.++The [hosted Linux CI run](https://github.com/trycua/cua/actions/runs/33937061198)+also passed all six tests at this SHA, using Ubuntu 24.04, Clang 18.1.3, and+CMake 3.31.6. It covers the native Unix transport and mocked compositor APIs,+not a loaded compositor module. A fresh macOS Debug build passed six tests.++All test compositor units were stopped, the plugin was unloaded, and the+original desktop remained responsive with its configuration hash unchanged.+No system package was installed and no autoload setting was added.+The SDK accepted deletion of the follow-up pool. Immediate lookup still+returned it; later pool and namespace lookups returned `403`, so final resource+absence could not be independently confirmed with that credential.+A subsequent successful account-level SDK namespace listing returned no matching+namespace. Direct lookup still returned `403`; that response alone is not+treated as proof of deletion.++## Reproducible lifecycle follow-up at `0a67bf5c8`++The checked-in [nested lifecycle runner](nested_lifecycle.py) passed on Cua+Cloud Fleet at `0a67bf5c844f5b358651737fb3545aaed5522007` on September 5, 2026+(UTC), through the Cua Sandbox SDK. The committed plugin, workflow, and license+archive had SHA-256+`960beaebeba6b4b10e9b08cdeb56e3843313b5e41a4154ca95693615e2a06ce0`.++The guest had Omarchy `4.0.1-1`, Hyprland `0.56.2-1`, portal `1.4.1-1`, and+installed driver `0.22.2`. This run reused the matching-toolchain module from+the `3789f0e6e` build, SHA-256+`693d6470a011956e58320de67fae8ed8d4628476e605f74cea018eb2eb5d5705`.+Plugin C++, headers, CMake, and packaging were unchanged between that build and+this candidate; this run tests the new orchestration, not a new package build.++Both exact-PID-owned nested compositors passed the live six-mutation refusal+and measured-state check. One restarted with a fresh socket and epoch; its old+connection closed and socket disappeared. The sibling's connection remained+responsive through restart and shutdown. Both owned processes stopped, only+the original parent remained in the instance inventory, and the parent's+plugin list was empty. Seven runner control-flow/cleanup tests also passed on+the guest and on the macOS review host. Hosted CI now runs those tests alongside+the existing six CTests; CI itself does not launch nested Hyprland.++The guest still lacked `renderD128` and passwordless package-install access.+No driver was installed, no system package transaction ran, and no input+capability was enabled. Nested startup can affect the disposable parent's+focus, so parent foreground preservation is not claimed by this lifecycle run.+Application delivery, foreground-grab isolation, and direct-DRM behavior remain+outside its evidence. The report-only follow-up does not change the tested+runner or executable sources.++## Outstanding acceptance gates++System installation with `pacman -U`, dependency-upgrade refusal, the complete+Fleet baseline, and physical-host certification remain unverified. Native+two-instance and clean-restart evidence is limited to nested compositors.+Second-seat delivery, target tokens, operator authorization, driver+integration, and the application/foreground-grab matrix remain future work.++The initial source differed from the first Fleet-tested tree only in documentation and+formatting: shutdown wording describes the worker join accurately, this report+records the evidence, and Markdown/Python formatting follows repository tools.+The Python harness's parsed syntax tree is checked against the tested copy.+Plugin C++ source, CMake files, and packaging are unchanged.++The guest configuration was restored, the plugin unloaded, and both initial+disposable Fleet pools deleted with fresh lookups confirming their removal.+The follow-up report changes only this Markdown file after testing+`3789f0e6e`; it does not change the plugin, packaging, CI, or test harness.++## Merge-readiness revalidation (September 5, 2026)++Tested source: `e254619817e75019d025e2714a395378ea533a28`, after merging+`1336a5e419c933eb750bfefe2d9db6aad63235de` from main. The merge resolved one+installation-document conflict without changing the plugin implementation.+The test-helper follow-up refuses optimized Python before validation or+compositor access; four regression tests cover that guard and packet exchange.+The plugin remains version `0.1.0`, discovery-only, and outside the Driver+installation/release path. There are no Rust delivery changes in this PR.++A fresh disposable Cua Cloud Fleet claim used Omarchy `4.0.1-1`, Hyprland+`0.56.2-1`, and portal `1.4.1-1`. The installed Driver remained `0.22.2` and+was not replaced or used as input-delivery evidence. Hyprland's ELF compiler+record and the selected plugin compiler both reported GCC `16.1.1 20260728`;+the guest's default compiler was `16.2.1` and was not used for the plugin.+The module linked the guest's shared `libstdc++.so.6.0.36`.++Validation results:++- The unchanged Arch recipe built with CMake `4.4.3` and Ninja `1.13.2`.+ `makepkg --nodeps` skipped dependency-database checks because CMake/Ninja+ were task-local wheels; the recipe's exact installed Hyprland and header+ checks ran. All six native Release CTests passed.+- All 11 Python helper tests passed on the guest and macOS review host.+ Six portable Release CTests also passed on macOS; those are not Linux proof.+- Package metadata pins `hyprland=0.56.2-1`. Its payload contains only the+ module and license plus their parent directories, with no autoload config.+- `nested_lifecycle.py` passed against the freshly built module: two actual+ owned compositors, six mutation refusals per start, a clean restart, old+ connection/socket closure, fresh socket and epoch, and sibling liveness.+ Both children stopped; the original compositor remained responsive and its+ plugin list was empty. This does not claim unchanged parent focus during+ nested-window startup.+- A real `sudo -n pacman -U` attempt refused because the guest requires a sudo+ password. A subsequent package query confirmed that the plugin was not+ installed. **System installation and dependency-upgrade refusal remain+ unverified**; package creation and metadata inspection do not replace them.++| Artifact | SHA-256 |+| ------------------------------------------ | ------------------------------------------------------------------ |+| Exported plugin source and license archive | `4feaafc406f6557ea21b358a5f883cd77053d70a31623483d2ac06b82b4d90e9` |+| Arch package | `300cb04ba8c001daeb84f37232fedc135920e5c424ea651d3db1b3cbb3b6d23c` |+| Native module | `e179eaa165a20d2f0365e0062c1cca8ac4c4caa9532124417636a603ee4ba73d` |++The remaining merge gates are a recorded discovery-only RFC disposition and+the system package-transaction evidence above. Direct-DRM restart, the exact+physical-host baseline, and input/client certification remain separate+promotion gates. The nonshipping input experiment in #3572 is not included+in this foundation's scope or results.++The claim and pool were deleted after evidence collection. A fresh successful+SDK namespace inventory found zero matching namespaces. The local evidence+archive is retained; no Fleet image or package was published.