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
fix(cua-driver): record KDE Wayland desktops through the portal ScreenCast (#6361)
injaneity776fe70a7a08
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.ymlindex cf2a2cfa3b..967b5c9b73 100644--- a/.github/workflows/cd-rust-cua-driver.yml+++ b/.github/workflows/cd-rust-cua-driver.yml@@ -222,6 +222,9 @@ jobs:# aarch64 variant automatically and the glibc floor holds on both arches.# The C deps below all exist in bullseye, including libwayland-dev for the# native Wayland backend (#1910).+ # libpipewire is not part of that floor. These binaries omit portal-capture,+ # and builds that enable it load libpipewire-0.3 at runtime, so hosts+ # without it (Ubuntu 20.04 ships none) still run every other tool.container:image: debian:11steps:@@ -241,7 +244,7 @@ jobs:# snapshot.debian.org answers 504 under load; retry each fetch.apt-get -o Dir::Etc::sourceparts=- -o Acquire::Retries=5 update# PipeWire ScreenCast capture remains Nix/modern-build only because- # bullseye's 0.3.19 headers are too old for libspa-sys 0.8. Portal+ # bullseye's 0.3.19 headers are too old for libspa-sys 0.10. Portal# RemoteDesktop/libei input is pure Rust plus libxkbcommon and ships# in these portable release binaries.apt-get -o Dir::Etc::sourceparts=- -o Acquire::Retries=5 install -y --no-install-recommends \diff --git a/.github/workflows/ci-cua-driver-installer-compat.yml b/.github/workflows/ci-cua-driver-installer-compat.ymlindex d8b1b0f406..417aee67cb 100644--- a/.github/workflows/ci-cua-driver-installer-compat.yml+++ b/.github/workflows/ci-cua-driver-installer-compat.yml@@ -133,6 +133,9 @@ jobs:if: runner.os == 'Linux'run: |sudo apt-get update+ # libpipewire-0.3-0 is left out on purpose: cua-driver loads it only+ # when a portal ScreenCast recording starts, so the install and+ # --version must work without it.sudo apt-get install -y --no-install-recommends \libx11-6 libxi6 libxtst6 libxext6 libwayland-client0 libxkbcommon0@@ -149,6 +152,10 @@ jobs:VERSION_OUTPUT=$("$INSTALLED" --version)echo "$VERSION_OUTPUT"grep -Fq "${CUA_DRIVER_RS_VERSION}" <<< "$VERSION_OUTPUT"+ if [[ "$RUNNER_OS" == "Linux" ]] && readelf -d "$INSTALLED" | grep -F NEEDED | grep -Fq libpipewire; then+ echo "::error::cua-driver links libpipewire; it must load it at runtime so hosts without PipeWire can install it"+ exit 1+ fiif [[ "$RUNNER_OS" == "macOS" ]]; thentest -x /Applications/CuaDriver.app/Contents/MacOS/cua-driver/usr/libexec/PlistBuddy -c Print:CFBundleIdentifier \diff --git a/.github/workflows/ci-rust-linux.yml b/.github/workflows/ci-rust-linux.ymlindex 62215340ee..222fe953bf 100644--- a/.github/workflows/ci-rust-linux.yml+++ b/.github/workflows/ci-rust-linux.yml@@ -167,9 +167,9 @@ jobs:env:CUA_TEST_REQUIRE_DRIVER_BIN: "1"run: cargo test -p cua-driver -p cua-driver-e2e -p cua-driver-contract -p cua-driver-core -p cua-driver-testkit -p cursor-overlay -p cursor-theme-cli -p platform-linux --all-targets --locked- - name: Run Wayland libei tests (portal-input)+ - name: Run Wayland portal tests (portal-input + portal-capture)working-directory: libs/cua-driver/rust- run: cargo test --locked -p platform-linux --features portal-input --lib+ run: cargo test --locked -p platform-linux --features portal-input,portal-capture --lib- name: Run cua-cursor-motion tests (lab parity, golden trajectories)working-directory: libs/cua-driver/rustrun: cargo test -p cua-cursor-motion --all-features --all-targets --lockeddiff --git a/.github/workflows/monitor-branded-installers.yml b/.github/workflows/monitor-branded-installers.ymlindex 0302b3d85b..d510a58c11 100644--- a/.github/workflows/monitor-branded-installers.yml+++ b/.github/workflows/monitor-branded-installers.yml@@ -158,6 +158,9 @@ jobs:if: runner.os == 'Linux'run: |sudo apt-get update+ # libpipewire-0.3-0 is left out on purpose: cua-driver loads it only+ # when a portal ScreenCast recording starts, so the install and+ # --version must work without it.sudo apt-get install -y --no-install-recommends \libx11-6 libxi6 libxtst6 libxext6 libwayland-client0 libxkbcommon0@@ -190,6 +193,10 @@ jobs:test -x "$INSTALLED"VERSION_OUTPUT=$("$INSTALLED" --version)echo "Installed: $VERSION_OUTPUT"+ if [[ "$RUNNER_OS" == "Linux" ]] && readelf -d "$INSTALLED" | grep -F NEEDED | grep -Fq libpipewire; then+ echo "::error::cua-driver links libpipewire; it must load it at runtime so hosts without PipeWire can install it"+ exit 1+ fiPUBLISHED=$(tr -d '[:space:]' < .github/release-state/cua-driver-rs-published-version)PUBLISHED="${CANARY_PIN:-$PUBLISHED}"if ! grep -Fq "$PUBLISHED" <<< "$VERSION_OUTPUT"; thendiff --git a/docs/content/docs/cua-driver/concepts/platform-support.mdx b/docs/content/docs/cua-driver/concepts/platform-support.mdxindex b6075efab7..9296688f7c 100644--- a/docs/content/docs/cua-driver/concepts/platform-support.mdx+++ b/docs/content/docs/cua-driver/concepts/platform-support.mdx@@ -38,7 +38,7 @@ routes where the app has a real X11 window.| Sway (wlroots) | Supported with limits | The full Electron, Tauri, GTK, and capture catalog | Focus-bound raw background input refuses. Other wlroots compositors unproven. || niri | Supported with limits | The full Electron, Tauri, GTK, and capture catalog on floating windows in a nested niri session | Needs niri 25.08 or later. No background input. niri has no per-toplevel capture protocol, so floating windows are cropped from the output. Tiled windows get no window capture or window-coordinate input; use `get_desktop_state` and desktop-scope actions. Overlapping floating windows refuse. Keep animations under 1 s. Client-side-decorated apps need `prefer-no-csd` for element frames. || GNOME/Mutter | Supported with limits | AT-SPI, GTK controls, compositor geometry and capture, foreground activation, portal/libei input | Needs the bundled [WinRects Shell helper](/cua-driver/quickstart) and one Shell restart. Portal video recording incomplete. |-| KDE/KWin | Experimental | Plasma 6 startup, GTK AT-SPI discovery, portal availability | The KWin helper is read-only; raw target-addressed input refuses. |+| KDE/KWin | Experimental | Plasma 6 startup, GTK AT-SPI discovery, portal availability | The KWin helper is read-only; raw target-addressed input refuses. Desktop video through the portal ScreenCast needs a `portal-capture` build and a one-time portal monitor grant. || Hyprland / Omarchy | Experimental | [Qualified isolated input](#hyprland-and-omarchy) since 0.24.0 | Does not inherit Sway coverage. || `cua-compositor` (nested) | Experimental | Native GTK behavior, capture, per-surface raw input | Owns its own compositor; says nothing about stock Wayland. || XWayland | Supported with limits | X11 routes for real X11 windows; AT-SPI fallback | Depends on whether the app actually uses X11. |diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdxindex 9f82a7dd84..9d9bdd5d18 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/batch-recording-and-settings.mdx@@ -145,7 +145,9 @@ Turn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restar**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.-**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.+**Windows + Linux X11 use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.++**Linux Wayland routes by compositor**: GNOME uses the trusted Shell helper's frames, wlroots compositors use `wf-recorder`, and compositors without wlr-screencopy (KDE/KWin) record the monitor the user grants through the xdg-desktop-portal ScreenCast (one consent dialog per install; requires a build with the `portal-capture` feature and ffmpeg on PATH). Unsupported combinations report the exact limitation in `last_error`.State persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex db1536f0e1..41b6777b88 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -76,12 +76,12 @@ dependencies = [[[package]]name = "annotate-snippets"-version = "0.9.2"+version = "0.11.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ccaf7e9dfbb6ab22c82e473cd1a8a7bd313c19a5b7e40970f3d89ef5a5c9e81e"+checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"dependencies = [+ "anstyle","unicode-width",- "yansi-term",][[package]]@@ -225,7 +225,7 @@ dependencies = ["memchr","proc-macro2","quote",- "rustc-hash 2.1.3",+ "rustc-hash","serde","serde_derive","syn",@@ -486,21 +486,19 @@ dependencies = [[[package]]name = "bindgen"-version = "0.69.5"+version = "0.72.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"dependencies = ["annotate-snippets","bitflags 2.11.1","cexpr","clang-sys","itertools",- "lazy_static",- "lazycell","proc-macro2","quote","regex",- "rustc-hash 1.1.0",+ "rustc-hash","shlex","syn",]@@ -792,9 +790,9 @@ dependencies = [[[package]]name = "cfg-expr"-version = "0.15.8"+version = "0.20.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"+checksum = "fe4ece8474b5f766c63426647e7b4b316b67431ade1036a8313cee24a03ae917"dependencies = ["smallvec 1.15.1","target-lexicon",@@ -1012,15 +1010,6 @@ dependencies = ["crossbeam-utils",]-[[package]]-name = "convert_case"-version = "0.6.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"-dependencies = [- "unicode-segmentation",-]-[[package]]name = "cookie"version = "0.18.1"@@ -1037,9 +1026,6 @@ name = "cookie-factory"version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"-dependencies = [- "futures",-][[package]]name = "cookie_store"@@ -1667,7 +1653,7 @@ dependencies = ["bitvec","cfg-if","libc",- "nix 0.23.2",+ "nix","thiserror 1.0.69",]@@ -1892,48 +1878,12 @@ version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"-[[package]]-name = "futures"-version = "0.3.32"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"-dependencies = [- "futures-channel",- "futures-core",- "futures-executor",- "futures-io",- "futures-sink",- "futures-task",- "futures-util",-]--[[package]]-name = "futures-channel"-version = "0.3.32"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"-dependencies = [- "futures-core",- "futures-sink",-]-[[package]]name = "futures-core"version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"-[[package]]-name = "futures-executor"-version = "0.3.32"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"-dependencies = [- "futures-core",- "futures-task",- "futures-util",-]-[[package]]name = "futures-io"version = "0.3.32"@@ -1982,7 +1932,6 @@ version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"dependencies = [- "futures-channel","futures-core","futures-io","futures-macro",@@ -2521,12 +2470,6 @@ version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"-[[package]]-name = "lazycell"-version = "1.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"-[[package]]name = "leb128fmt"version = "0.1.0"@@ -2566,26 +2509,25 @@ dependencies = [[[package]]name = "libspa"-version = "0.8.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65f3a4b81b2a2d8c7f300643676202debd1b7c929dbf5c9bb89402ea11d19810"+checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40"dependencies = ["bitflags 2.11.1","cc",- "convert_case","cookie-factory","libc","libspa-sys",- "nix 0.27.1",- "nom 7.1.3",+ "nom 8.0.0",+ "rustix","system-deps",][[package]]name = "libspa-sys"-version = "0.8.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bf0d9716420364790e85cbb9d3ac2c950bde16a7dd36f3209b7dfdfc4a24d01f"+checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"dependencies = ["bindgen","cc",@@ -2806,17 +2748,6 @@ dependencies = ["memoffset 0.6.5",]-[[package]]-name = "nix"-version = "0.27.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053"-dependencies = [- "bitflags 2.11.1",- "cfg-if",- "libc",-]-[[package]]name = "nom"version = "1.2.4"@@ -3481,28 +3412,11 @@ dependencies = ["futures-io",]-[[package]]-name = "pipewire"-version = "0.8.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "08e645ba5c45109106d56610b3ee60eb13a6f2beb8b74f8dc8186cf261788dda"-dependencies = [- "anyhow",- "bitflags 2.11.1",- "libc",- "libspa",- "libspa-sys",- "nix 0.27.1",- "once_cell",- "pipewire-sys",- "thiserror 1.0.69",-]-[[package]]name = "pipewire-sys"-version = "0.8.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "849e188f90b1dda88fe2bfe1ad31fe5f158af2c98f80fb5d13726c44f3f01112"+checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"dependencies = ["bindgen","libspa-sys",@@ -3544,11 +3458,12 @@ dependencies = ["futures-util","image","libc",+ "libloading","libspa","memmap2","meval","pip-preview",- "pipewire",+ "pipewire-sys","reis","serde","serde_json",@@ -4070,12 +3985,6 @@ dependencies = ["cc",]-[[package]]-name = "rustc-hash"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"-[[package]]name = "rustc-hash"version = "2.1.3"@@ -4564,14 +4473,14 @@ dependencies = [[[package]]name = "system-deps"-version = "6.2.2"+version = "7.0.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"+checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"dependencies = ["cfg-expr","heck","pkg-config",- "toml 0.8.23",+ "toml 1.1.3+spec-1.1.0","version-compare",]@@ -4593,9 +4502,9 @@ dependencies = [[[package]]name = "target-lexicon"-version = "0.12.16"+version = "0.13.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"[[package]]name = "tempfile"@@ -4828,6 +4737,21 @@ dependencies = ["winnow 0.7.15",]+[[package]]+name = "toml"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned 1.1.1",+ "toml_datetime 1.1.1+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.3",+]+[[package]]name = "toml_datetime"version = "0.6.11"@@ -5036,17 +4960,11 @@ version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"-[[package]]-name = "unicode-segmentation"-version = "1.13.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"-[[package]]name = "unicode-width"-version = "0.1.14"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"[[package]]name = "unicode-xid"@@ -6226,15 +6144,6 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"-[[package]]-name = "yansi-term"-version = "0.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1"-dependencies = [- "winapi",-]-[[package]]name = "yoke"version = "0.8.2"diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.mdindex b053e9c89f..c64e0f6e79 100644--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md@@ -268,9 +268,19 @@ driver selects a backend from compositor capabilities:explicitly for controlled automation. GNOME and KDE never switch into it.Sway recording works through the wlroots recorder path and is exercised by the-canonical harness runner. Portal-backed GNOME recording is still an evidence-gap. Capture and recording availability therefore depend on the compositor,-installed helpers, and portal grant.+canonical harness runner. Compositors that expose no wlr-screencopy protocol,+including KDE/KWin, record through the xdg-desktop-portal ScreenCast: the+first `start_recording` with `record_video:true` opens the desktop's screen+share dialog, the granted monitor is remembered through a restore token, and+frames are encoded with ffmpeg. That route exists only in builds with the+`portal-capture` feature (the Nix package); other builds report the missing+feature in `last_error` instead of failing silently. It also needs the+PipeWire client library (`libpipewire-0.3-0` on Debian and Ubuntu), which the+driver loads only when that recording starts; without it, that recording+reports the missing library and every other tool works. Portal-backed GNOME+recording is still an evidence gap. Capture and recording availability+therefore depend on the compositor, installed helpers, build features, and+portal grant.Standard Wayland has no general client protocol for raw input to an arbitraryoccluded surface. Background AX actions can still deliver through AT-SPI, and@@ -463,7 +473,7 @@ ask the user.| Sway/wlroots | AT-SPI, native discovery, full-display and cropped-window screencopy, foreground input, semantic background actions, and video | Raw background pointer and keyboard input remains focus-bound || Hyprland/Omarchy | Experimental source candidate with separate discovery-foundation and bounded two-seat app evidence | Default plugin is discovery-only; raw background v3 qualification is limited to the exact native Calc/Inkscape packages and a private agent US keymap; user Caps-to-Ctrl/Super remaps do not alter agent semantics; complete native harness and release acceptance are separate gates || GNOME/Mutter | AT-SPI, WinRects geometry and activation, capture, and portal/libei foreground input | Requires the helper and portal grant; portal video parity remains open |-| KDE/KWin | AT-SPI and generic discovery where exposed | Target-specific activation and behavioral coverage remain experimental |+| KDE/KWin | AT-SPI and generic discovery where exposed | Target-specific activation and behavioral coverage remain experimental; video needs a `portal-capture` build and a portal monitor grant || Nested `cua-compositor` | Versioned direct per-surface input, native GTK 31/31, capture/scope 5/5, and partial Electron coverage | The complete shared matrix remains experimental; do not infer standard-Wayland support |See [WORKFLOW.md](WORKFLOW.md) for exact targeting and verification and `RECORDING.md` for sessiondiff --git a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.mdindex 1090ef5929..b590982dae 100644--- a/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md+++ b/libs/cua-driver/rust/Skills/cua-driver/RECORDING.md@@ -52,8 +52,12 @@ assuming the convenience command supports every raw-tool argument.responsible runtime's grant. Permission status is not proof of live capture.- Windows video uses ffmpeg `gdigrab`; the runtime must be in the interactivedesktop session.-- Linux X11 video uses ffmpeg `x11grab`. Native Wayland needs a supported- compositor-specific recorder and any portal grant; see [LINUX.md](LINUX.md).+- Linux X11 video uses ffmpeg `x11grab`. Native Wayland routes by compositor:+ GNOME uses the trusted Shell helper frames, wlroots compositors use+ `wf-recorder`, and compositors without wlr-screencopy (KDE/KWin) use the+ xdg-desktop-portal ScreenCast, which needs a `portal-capture` build, the+ PipeWire client library (`libpipewire-0.3-0`), and a one-time monitor grant+ in the portal dialog; see [LINUX.md](LINUX.md).A successful desktop PNG does not establish video availability.## What each turn folder containsdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rsindex 1c3d8a4a7b..0424994aad 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recording_tools.rs@@ -93,12 +93,20 @@ impl Tool for StartRecordingTool {choose Allow, or run `cua-driver permissions grant` beforehand \to answer it up front. The recorder captures screen video only \and does not enable system-audio capture.\n\n\- **Windows + Linux use an ffmpeg subprocess** (`gdigrab` / \+ **Windows + Linux X11 use an ffmpeg subprocess** (`gdigrab` / \`x11grab` + libx264). Requires ffmpeg on PATH (winget install \Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or \fails on startup the per-turn capture (screenshots + \action.json) still runs and the session's `last_error` field \carries the diagnostic.\n\n\+ **Linux Wayland routes by compositor**: GNOME uses the trusted \+ Shell helper's frames, wlroots compositors use `wf-recorder`, \+ and compositors without wlr-screencopy (KDE/KWin) record the \+ monitor the user grants through the xdg-desktop-portal \+ ScreenCast (one consent dialog per install; requires a build \+ with the `portal-capture` feature and ffmpeg on PATH). \+ Unsupported combinations report the exact limitation in \+ `last_error`.\n\n\State persists for the life of the daemon; a restart \resets to disabled with no on-disk state. Call `stop_recording` to \disable + finalize the mp4."diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/video.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/video.rsindex f7eddc53d9..9c0d1eb41b 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/video.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/video.rs@@ -7,8 +7,11 @@//! - **macOS:** native ScreenCaptureKit via `platform_macos::video_sckit`//! (no extra TCC grant — inherits cua-driver's own Screen Recording//! permission, no subprocess).-//! - **Windows + Linux:** ffmpeg subprocess via `video_ffmpeg`+//! - **Windows + Linux X11:** ffmpeg subprocess via `video_ffmpeg`//! (`gdigrab` / `x11grab` input + libx264 encode).+//! - **Linux Wayland:** compositor-routed capture via+//! `platform_linux::video_wayland` (GNOME Shell helper frames, wlroots+//! `wf-recorder`, or xdg-desktop-portal ScreenCast over PipeWire).//!//! The factory is registered with `set_video_backend_factory` from each//! platform's `main.rs` startup block, mirroring how `SCREENSHOT_FN` /diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rsindex 36d108c8c0..9f568e950f 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/video_ffmpeg.rs@@ -208,7 +208,9 @@ pub fn find_ffprobe() -> Option<PathBuf> {}}-pub(crate) fn find_ffmpeg() -> Option<PathBuf> {+/// Locate `ffmpeg`, preferring PATH and falling back to the winget install+/// location on Windows. Shared by every subprocess-encoding video backend.+pub fn find_ffmpeg() -> Option<PathBuf> {if Command::new("ffmpeg").arg("-version").stdout(Stdio::null())diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rsindex 23476c2c95..415dfaa708 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs@@ -703,7 +703,7 @@ fn configure_linux_runtime(prepare_desktop_environment: bool) {});if platform_linux::wayland::is_wayland() {cua_driver_core::video::set_video_backend_factory(Box::new(- platform_linux::video_wayland::WfRecorderVideoBackendFactory,+ platform_linux::video_wayland::WaylandVideoBackendFactory,));} else {cua_driver_core::video::set_video_backend_factory(Box::new(diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.tomlindex 4c124c8f83..11cda83c67 100644--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml@@ -87,16 +87,16 @@ zbus = { version = "5", default-features = false, features = ["tokio"] }# ashpd re-exports `url` transitively; declared explicitly so ashpd# version bumps cannot silently break the resolver.url = "2"-# PipeWire client for the ScreenCast per-window capture path — dequeues-# frames from the node id returned by `open_pipe_wire_remote`. Pinned to-# 0.8 (last well-documented release; 0.10 had docs.rs build failures in-# mid-2026). Needs libpipewire-0.3 headers at build time — gated behind-# the `portal-capture` feature.-pipewire = { version = "0.8", optional = true }-# Companion to pipewire 0.8 — needed to construct the SPA_PARAM_EnumFormat-# pod (SPA_VIDEO_FORMAT_BGRx at announced width/height) we hand to-# `Stream::connect`. Same `portal-capture` gating as `pipewire`.-libspa = { version = "0.8", optional = true }+# PipeWire types and constants for the ScreenCast video route, which dequeues+# frames from the node id returned by `open_pipe_wire_remote`. libpipewire+# itself is loaded at runtime (`wayland::libpipewire`), so builds need its+# headers but the binary does not link it. Gated behind `portal-capture`.+pipewire-sys = { version = "0.10", optional = true }+libloading = { version = "0.8", optional = true }+# SPA pods, format parsing and buffer types (header-only, compiled in): builds+# the SPA_PARAM_EnumFormat pod (raw BGRx/BGRA/RGBx/RGBA at announced+# width/height) handed to `pw_stream_connect`. Same `portal-capture` gating.+libspa = { version = "0.10", optional = true }# Pure-Rust libei/libeis bindings for the GNOME/KDE input path (handshake# → seat → device → pointer_absolute/button/scroll/keyboard/text). API is# documented as "incomplete and subject to change" — budget for churn on@@ -141,11 +141,13 @@ portal-input = ["dep:calloop","dep:enumflags2",]-# PipeWire-backed per-window ScreenCast capture keeps its newer system-header-# requirement and remains enabled by Nix/modern desktop builds.+# PipeWire-backed ScreenCast capture (the full-desktop video route for+# KDE/KWin and other compositors without wlr-screencopy) keeps its newer+# system-header requirement and remains enabled by Nix/modern desktop builds.portal-capture = ["ashpd/screencast",- "dep:pipewire",+ "dep:pipewire-sys",+ "dep:libloading","dep:libspa",]# Backward-compatible full desktop feature used by the Nix package.diff --git a/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs b/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rsindex 0a525d8865..04e2546d17 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/video_wayland.rs@@ -1,8 +1,16 @@//! Native Wayland full-desktop video capture.//!-//! wlroots compositors use `wf-recorder`. GNOME does not expose the wlroots-//! screencopy protocol, so its attested Shell helper supplies compositor-owned-//! PNG frames which are encoded into the same MP4 artifact through FFmpeg.+//! One factory, three compositor routes (see [`WaylandVideoRoute`]):+//!+//! - GNOME's attested Shell helper supplies compositor-owned PNG frames that+//! are encoded into MP4 through FFmpeg; no consent dialog is involved.+//! - wlroots compositors advertise `zwlr_screencopy_manager_v1`, which+//! `wf-recorder` consumes directly.+//! - Everything else (KDE/KWin, portal-only desktops) records through the+//! xdg-desktop-portal ScreenCast: the user grants a monitor once, the+//! PipeWire stream is paced to a constant frame rate, and FFmpeg encodes+//! raw frames into the same MP4 artifact. This route needs the+//! `portal-capture` feature; builds without it report the limitation.use std::io::Read;use std::io::Write;@@ -12,20 +20,90 @@ use std::sync::mpsc::{self, RecvTimeoutError};use std::time::{Duration, Instant};use cua_driver_core::video::{VideoBackend, VideoBackendFactory, VideoMetadata};+use cua_driver_core::video_ffmpeg::find_ffmpeg;-pub struct WfRecorderVideoBackendFactory;+pub struct WaylandVideoBackendFactory;-impl VideoBackendFactory for WfRecorderVideoBackendFactory {+impl VideoBackendFactory for WaylandVideoBackendFactory {fn start(&self, output_path: &Path) -> anyhow::Result<Box<dyn VideoBackend>> {- if let Some(first_frame) = crate::wayland::shell_helper::trusted_screenshot_display() {- return GnomeShellVideoBackend::start(output_path, first_frame)- .map(|backend| Box::new(backend) as Box<dyn VideoBackend>);+ let first_frame = crate::wayland::shell_helper::trusted_screenshot_display();+ let wlr_screencopy = crate::wayland::probe_managers()+ .ok()+ .map(|managers| managers.screencopy);+ match select_route(first_frame.is_some(), wlr_screencopy) {+ WaylandVideoRoute::GnomeShell => GnomeShellVideoBackend::start(+ output_path,+ first_frame.expect("GnomeShell route requires a trusted first frame"),+ )+ .map(|backend| Box::new(backend) as Box<dyn VideoBackend>),+ WaylandVideoRoute::WfRecorder => WfRecorderVideoBackend::start(output_path)+ .map(|backend| Box::new(backend) as Box<dyn VideoBackend>),+ WaylandVideoRoute::PortalScreencast => start_portal_video(output_path),}- WfRecorderVideoBackend::start(output_path)- .map(|backend| Box::new(backend) as Box<dyn VideoBackend>)}}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WaylandVideoRoute {+ GnomeShell,+ WfRecorder,+ PortalScreencast,+}++/// `wlr_screencopy` is `None` when the registry could not be probed; the+/// wf-recorder route then keeps its own startup diagnostics as the report.+fn select_route(trusted_gnome_frames: bool, wlr_screencopy: Option<bool>) -> WaylandVideoRoute {+ if trusted_gnome_frames {+ WaylandVideoRoute::GnomeShell+ } else if wlr_screencopy == Some(false) {+ WaylandVideoRoute::PortalScreencast+ } else {+ WaylandVideoRoute::WfRecorder+ }+}++#[cfg(not(feature = "portal-capture"))]+fn start_portal_video(_output_path: &Path) -> anyhow::Result<Box<dyn VideoBackend>> {+ anyhow::bail!(+ "this compositor does not expose wlr-screencopy, and this cua-driver build was compiled \+ without the `portal-capture` feature, so xdg-desktop-portal ScreenCast video is \+ unavailable. Use a build with `--features portal-capture` (the Nix package enables it) \+ to record on KDE/KWin and other portal-only compositors."+ )+}++#[cfg(feature = "portal-capture")]+fn start_portal_video(output_path: &Path) -> anyhow::Result<Box<dyn VideoBackend>> {+ portal_video::PortalVideoBackend::start(output_path)+ .map(|backend| Box::new(backend) as Box<dyn VideoBackend>)+}++fn require_ffmpeg(route: &str) -> anyhow::Result<PathBuf> {+ find_ffmpeg().ok_or_else(|| anyhow::anyhow!("ffmpeg is required for {route} video capture"))+}++fn prepare_output_dir(output_path: &Path) -> anyhow::Result<()> {+ if let Some(parent) = output_path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ Ok(())+}++/// Collect the tail of a child's stderr without letting the pipe fill up.+fn drain_stderr_tail(child: &mut Child) -> Option<std::thread::JoinHandle<Vec<u8>>> {+ child.stderr.take().map(|mut stderr| {+ std::thread::spawn(move || {+ let mut output = Vec::new();+ let _ = stderr.read_to_end(&mut output);+ if output.len() > 4096 {+ let excess = output.len() - 4096;+ output.drain(..excess);+ }+ output+ })+ })+}+struct GnomeShellVideoBackend {stop_tx: mpsc::Sender<()>,worker: std::thread::JoinHandle<anyhow::Result<()>>,@@ -35,26 +113,16 @@ struct GnomeShellVideoBackend {impl GnomeShellVideoBackend {fn start(output_path: &Path, first_frame: Vec<u8>) -> anyhow::Result<Self> {- let available = Command::new("ffmpeg")- .arg("-version")- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .map(|status| status.success())- .unwrap_or(false);- if !available {- anyhow::bail!("ffmpeg is required for GNOME Wayland video capture");- }- if let Some(parent) = output_path.parent() {- std::fs::create_dir_all(parent)?;- }+ let ffmpeg = require_ffmpeg("GNOME Wayland")?;+ prepare_output_dir(output_path)?;let output_path = output_path.to_path_buf();let worker_output = output_path.clone();let (stop_tx, stop_rx) = mpsc::channel();let (ready_tx, ready_rx) = mpsc::sync_channel(1);let worker = std::thread::spawn(move || {- let result = run_gnome_shell_encoder(&worker_output, first_frame, stop_rx, &ready_tx);+ let result =+ run_gnome_shell_encoder(&ffmpeg, &worker_output, first_frame, stop_rx, &ready_tx);if result.is_err() {let _ = ready_tx.send(result.as_ref().map(|_| ()).map_err(ToString::to_string));}@@ -81,12 +149,13 @@ impl GnomeShellVideoBackend {}fn run_gnome_shell_encoder(+ ffmpeg: &Path,output_path: &Path,first_frame: Vec<u8>,stop_rx: mpsc::Receiver<()>,ready_tx: &mpsc::SyncSender<Result<(), String>>,) -> anyhow::Result<()> {- let mut child = Command::new("ffmpeg")+ let mut child = Command::new(ffmpeg).args(["-hide_banner","-loglevel",@@ -190,9 +259,7 @@ impl WfRecorderVideoBackend {"wf-recorder not found on PATH. Install wf-recorder for native Wayland video.");}- if let Some(parent) = output_path.parent() {- std::fs::create_dir_all(parent)?;- }+ prepare_output_dir(output_path)?;let started_at = Instant::now();let mut command = Command::new("wf-recorder");@@ -209,17 +276,7 @@ impl WfRecorderVideoBackend {let mut child = command.spawn().map_err(|error| anyhow::anyhow!("failed to start wf-recorder: {error}"))?;- let stderr_thread = child.stderr.take().map(|mut stderr| {- std::thread::spawn(move || {- let mut output = Vec::new();- let _ = stderr.read_to_end(&mut output);- if output.len() > 4096 {- let excess = output.len() - 4096;- output.drain(..excess);- }- output- })- });+ let stderr_thread = drain_stderr_tail(&mut child);let probe_deadline = Instant::now() + Duration::from_millis(1500);while Instant::now() < probe_deadline {@@ -285,3 +342,844 @@ impl VideoBackend for WfRecorderVideoBackend {})}}++/// Constant-frame-rate pacing for a producer that only delivers frames on+/// damage. Each tick reports how many copies of the latest frame bring the+/// encoded timeline up to wall-clock time, so a static desktop still yields a+/// video whose duration matches the recording.+#[derive(Debug)]+#[cfg_attr(not(feature = "portal-capture"), allow(dead_code))]+struct FramePacer {+ fps: u32,+ started_at: Instant,+ emitted: u64,+}++#[cfg_attr(not(feature = "portal-capture"), allow(dead_code))]+impl FramePacer {+ fn new(fps: u32, started_at: Instant) -> Self {+ Self {+ fps,+ started_at,+ emitted: 0,+ }+ }++ fn due(&mut self, now: Instant) -> u64 {+ let elapsed = now.saturating_duration_since(self.started_at);+ let target = elapsed.as_micros() * u128::from(self.fps) / 1_000_000;+ let due = u64::try_from(target)+ .unwrap_or(u64::MAX)+ .saturating_sub(self.emitted);+ self.emitted += due;+ due+ }+}++#[cfg(feature = "portal-capture")]+mod portal_video {+ use super::*;+ use crate::wayland::libpipewire::libpipewire;+ use crate::wayland::portal::RestoreToken;+ use crate::wayland::portal_screencast::{+ run_frame_stream, Frame, FrameFlow, FrameSink, RawFormat, ScreencastSession, StreamOptions,+ CONSENT_TIMEOUT, PORTAL_CALL_TIMEOUT,+ };+ use ashpd::desktop::screencast::SourceType;+ use ashpd::enumflags2::BitFlags;+ use std::io::ErrorKind;+ use std::os::fd::AsRawFd;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;++ pub(super) const FPS: u32 = 10;+ pub(super) const TICK: Duration = Duration::from_millis(1000 / FPS as u64);+ const FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(10);+ /// Encoder must survive this long after its first frame before the+ /// backend reports a successful start; ffmpeg rejects bad arguments or+ /// missing codecs within milliseconds.+ const ENCODER_PROBE: Duration = Duration::from_millis(1500);+ const ENCODER_SHUTDOWN: Duration = Duration::from_secs(10);+ /// Every frame a tick owes must be accepted by the encoder within this+ /// window. A consumer that cannot keep up fails the recording explicitly+ /// instead of quietly shortening the timeline, and a wedged one cannot+ /// park the PipeWire loop for longer than this.+ pub(super) const FEED_DEADLINE: Duration = Duration::from_secs(5);++ pub(super) struct PortalVideoBackend {+ stop: Arc<AtomicBool>,+ /// Resolves to the number of frames the encoder accepted.+ worker: std::thread::JoinHandle<anyhow::Result<u64>>,+ output_path: PathBuf,+ }++ impl PortalVideoBackend {+ pub(super) fn start(output_path: &Path) -> anyhow::Result<Self> {+ let ffmpeg = require_ffmpeg("portal ScreenCast")?;+ // Before the consent dialog, so a host without PipeWire never asks.+ libpipewire()?;+ prepare_output_dir(output_path)?;++ let output_path = output_path.to_path_buf();+ let stop = Arc::new(AtomicBool::new(false));+ let (ready_tx, ready_rx) = mpsc::sync_channel::<Result<(), String>>(1);+ let worker = std::thread::spawn({+ let output_path = output_path.clone();+ let stop = stop.clone();+ move || {+ let session = ScreencastSession::open(+ BitFlags::from(SourceType::Monitor),+ Some(RestoreToken::ScreencastVideo),+ CONSENT_TIMEOUT,+ );+ let session = match session {+ Ok(session) => session,+ Err(error) => {+ let _ = ready_tx.send(Err(error.to_string()));+ return Err(error);+ }+ };+ let result = (|| {+ let fd = session.pipewire_fd()?;+ let node_id = session.node_id()?;+ let sink =+ RawVideoEncoder::new(ffmpeg, output_path, stop, ready_tx.clone());+ let options = StreamOptions {+ first_frame_timeout: FIRST_FRAME_TIMEOUT,+ tick_interval: TICK,+ };+ run_frame_stream(fd, node_id, options, sink)?.finish()+ })();+ session.close();+ if let Err(error) = &result {+ let _ = ready_tx.try_send(Err(error.to_string()));+ }+ result+ }+ });+ // Session setup and the PipeWire remote are each bounded by+ // PORTAL_CALL_TIMEOUT on either side of the consent wait.+ let start_deadline =+ PORTAL_CALL_TIMEOUT * 2 + CONSENT_TIMEOUT + FIRST_FRAME_TIMEOUT + ENCODER_PROBE * 2;+ match ready_rx.recv_timeout(start_deadline) {+ Ok(Ok(())) => Ok(Self {+ stop,+ worker,+ output_path,+ }),+ Ok(Err(error)) => {+ let _ = worker.join();+ anyhow::bail!("portal ScreenCast video failed to start: {error}")+ }+ Err(_) => {+ stop.store(true, Ordering::SeqCst);+ let _ = worker.join();+ anyhow::bail!(+ "portal ScreenCast video did not start within {}s",+ start_deadline.as_secs()+ )+ }+ }+ }+ }++ impl VideoBackend for PortalVideoBackend {+ fn stop(self: Box<Self>) -> anyhow::Result<VideoMetadata> {+ self.stop.store(true, Ordering::SeqCst);+ let delivered = match self.worker.join() {+ Ok(result) => result?,+ Err(_) => anyhow::bail!("portal ScreenCast video worker panicked"),+ };+ // The artifact is a constant-rate stream of exactly `delivered`+ // frames, so its duration is derived from them rather than from+ // the wall clock the pacer was chasing.+ Ok(VideoMetadata {+ path: self.output_path,+ duration_ms: delivered * 1000 / u64::from(FPS),+ finalized: true,+ })+ }+ }++ /// ffmpeg `rawvideo` pixel format matching a negotiated PipeWire layout.+ pub(super) fn ffmpeg_pix_fmt(format: RawFormat) -> &'static str {+ match format {+ RawFormat::Bgrx => "bgr0",+ RawFormat::Bgra => "bgra",+ RawFormat::Rgbx => "rgb0",+ RawFormat::Rgba => "rgba",+ }+ }++ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ struct Geometry {+ width: u32,+ height: u32,+ pix_fmt: &'static str,+ }++ pub(super) fn set_nonblocking(fd: &impl AsRawFd) -> std::io::Result<()> {+ let fd = fd.as_raw_fd();+ let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };+ if flags < 0 {+ return Err(std::io::Error::last_os_error());+ }+ if unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ }++ /// Write one whole frame to a non-blocking pipe, sleeping in `poll` for+ /// writable readiness between partial writes. A consumer that stops+ /// reading surfaces as `TimedOut` at `deadline` instead of parking the+ /// calling thread.+ pub(super) fn write_frame(+ dst: &mut (impl Write + AsRawFd),+ frame: &[u8],+ deadline: Instant,+ ) -> std::io::Result<()> {+ let mut written = 0;+ while written < frame.len() {+ match dst.write(&frame[written..]) {+ Ok(0) => return Err(ErrorKind::WriteZero.into()),+ Ok(n) => written += n,+ Err(error) if error.kind() == ErrorKind::WouldBlock => {+ await_writable(dst, deadline)?+ }+ Err(error) if error.kind() == ErrorKind::Interrupted => {}+ Err(error) => return Err(error),+ }+ }+ Ok(())+ }++ fn await_writable(fd: &impl AsRawFd, deadline: Instant) -> std::io::Result<()> {+ loop {+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ return Err(ErrorKind::TimedOut.into());+ }+ let mut pollfd = libc::pollfd {+ fd: fd.as_raw_fd(),+ events: libc::POLLOUT,+ revents: 0,+ };+ let timeout_ms = i32::try_from(remaining.as_millis())+ .unwrap_or(i32::MAX)+ .max(1);+ match unsafe { libc::poll(&mut pollfd, 1, timeout_ms) } {+ // The kernel may wake slightly before the millisecond it was+ // given; the deadline check above decides whether time is up.+ 0 => {}+ // POLLERR/POLLHUP also count: the next write reports them.+ n if n > 0 => return Ok(()),+ _ => {+ let error = std::io::Error::last_os_error();+ if error.kind() != ErrorKind::Interrupted {+ return Err(error);+ }+ }+ }+ }+ }++ struct Encoder {+ child: Child,+ stdin: Option<std::process::ChildStdin>,+ stderr_thread: Option<std::thread::JoinHandle<Vec<u8>>>,+ geometry: Geometry,+ spawned_at: Instant,+ pacer: FramePacer,+ /// Frames ffmpeg has accepted in full; the artifact's length.+ delivered: u64,+ }++ impl Encoder {+ fn spawn(ffmpeg: &Path, output_path: &Path, geometry: Geometry) -> anyhow::Result<Self> {+ let mut child = Command::new(ffmpeg)+ .args(["-hide_banner", "-loglevel", "error", "-f", "rawvideo"])+ .args(["-pix_fmt", geometry.pix_fmt])+ .args([+ "-video_size",+ &format!("{}x{}", geometry.width, geometry.height),+ ])+ .args(["-framerate", &FPS.to_string()])+ .args(["-i", "-", "-an"])+ .args(["-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2"])+ .args(["-c:v", "libx264", "-preset", "ultrafast"])+ .args(["-pix_fmt", "yuv420p", "-movflags", "+faststart", "-y"])+ .arg(output_path)+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|error| anyhow::anyhow!("failed to start FFmpeg encoder: {error}"))?;+ let stdin = child.stdin.take();+ if let Some(stdin) = &stdin {+ if let Err(error) = set_nonblocking(stdin) {+ let _ = child.kill();+ let _ = child.wait();+ anyhow::bail!("could not make the FFmpeg encoder pipe non-blocking: {error}");+ }+ }+ let stderr_thread = drain_stderr_tail(&mut child);+ let now = Instant::now();+ Ok(Self {+ child,+ stdin,+ stderr_thread,+ geometry,+ spawned_at: now,+ pacer: FramePacer::new(FPS, now),+ delivered: 0,+ })+ }++ fn stderr_tail(&mut self) -> String {+ let tail = self+ .stderr_thread+ .take()+ .and_then(|worker| worker.join().ok())+ .unwrap_or_default();+ String::from_utf8_lossy(&tail).into_owned()+ }++ fn ensure_alive(&mut self) -> anyhow::Result<()> {+ if let Some(status) = self.child.try_wait()? {+ let tail = self.stderr_tail();+ anyhow::bail!("FFmpeg encoder exited during recording ({status}): {tail}");+ }+ Ok(())+ }++ /// Hand one frame to ffmpeg in full, or explain why that was not+ /// possible within `deadline`.+ fn feed(&mut self, frame: &[u8], deadline: Instant) -> anyhow::Result<()> {+ let stdin = self+ .stdin+ .as_mut()+ .ok_or_else(|| anyhow::anyhow!("FFmpeg encoder exposed no stdin"))?;+ match write_frame(stdin, frame, deadline) {+ Ok(()) => {+ self.delivered += 1;+ Ok(())+ }+ Err(error) if error.kind() == ErrorKind::TimedOut => anyhow::bail!(+ "FFmpeg encoder stopped accepting {}x{} frames within the {}s feed window; \+ it is not keeping up with {FPS} fps",+ self.geometry.width,+ self.geometry.height,+ FEED_DEADLINE.as_secs()+ ),+ Err(error) if error.kind() == ErrorKind::BrokenPipe => {+ let status = self.reap(Instant::now() + Duration::from_secs(2))?;+ let tail = self.stderr_tail();+ match status {+ Some(status) => anyhow::bail!(+ "FFmpeg encoder exited during recording ({status}): {tail}"+ ),+ None => anyhow::bail!(+ "FFmpeg encoder closed its input during recording: {tail}"+ ),+ }+ }+ Err(error) => anyhow::bail!("failed to feed FFmpeg encoder: {error}"),+ }+ }++ /// Wait for ffmpeg to exit until `deadline`, then kill it. `None`+ /// means it had to be killed.+ fn reap(&mut self, deadline: Instant) -> std::io::Result<Option<std::process::ExitStatus>> {+ loop {+ if let Some(status) = self.child.try_wait()? {+ return Ok(Some(status));+ }+ if Instant::now() >= deadline {+ let _ = self.child.kill();+ let _ = self.child.wait();+ return Ok(None);+ }+ std::thread::sleep(Duration::from_millis(80));+ }+ }++ /// Close stdin so ffmpeg writes the moov atom, then wait for it.+ fn finish(mut self) -> anyhow::Result<u64> {+ drop(self.stdin.take());+ let status = self.reap(Instant::now() + ENCODER_SHUTDOWN)?;+ let tail = self.stderr_tail();+ match status {+ Some(status) if status.success() => Ok(self.delivered),+ Some(status) => anyhow::bail!("FFmpeg encoder exited with {status}: {tail}"),+ None => anyhow::bail!(+ "FFmpeg encoder did not finalize within {}s: {tail}",+ ENCODER_SHUTDOWN.as_secs()+ ),+ }+ }+ }++ impl Drop for Encoder {+ fn drop(&mut self) {+ // Reached only on error paths; the success path consumes the+ // encoder through `finish`. Closing stdin lets ffmpeg finalize a+ // playable partial artifact before we reap it.+ drop(self.stdin.take());+ let _ = self.reap(Instant::now() + ENCODER_SHUTDOWN);+ }+ }++ /// Feeds paced raw frames from the portal stream into an FFmpeg encoder+ /// that is spawned lazily with the first frame's negotiated geometry.+ pub(super) struct RawVideoEncoder {+ ffmpeg: PathBuf,+ output_path: PathBuf,+ stop: Arc<AtomicBool>,+ ready: Option<mpsc::SyncSender<Result<(), String>>>,+ encoder: Option<Encoder>,+ /// Latest frame, tightly packed at `width * 4` bytes per row.+ latest: Vec<u8>,+ }++ impl RawVideoEncoder {+ pub(super) fn new(+ ffmpeg: PathBuf,+ output_path: PathBuf,+ stop: Arc<AtomicBool>,+ ready: mpsc::SyncSender<Result<(), String>>,+ ) -> Self {+ Self {+ ffmpeg,+ output_path,+ stop,+ ready: Some(ready),+ encoder: None,+ latest: Vec::new(),+ }+ }++ /// Finalize the artifact and return the number of frames it holds.+ pub(super) fn finish(mut self) -> anyhow::Result<u64> {+ let Some(encoder) = self.encoder.take() else {+ anyhow::bail!("portal ScreenCast delivered no frame before recording stopped");+ };+ let delivered = encoder.finish()?;+ if self+ .output_path+ .metadata()+ .map(|meta| meta.len())+ .unwrap_or(0)+ == 0+ {+ anyhow::bail!("FFmpeg encoder produced an empty artifact");+ }+ Ok(delivered)+ }++ /// Process id of the live ffmpeg child, for tests that need to wedge+ /// a real consumer.+ #[cfg(test)]+ pub(super) fn encoder_pid(&self) -> Option<u32> {+ self.encoder.as_ref().map(|encoder| encoder.child.id())+ }+ }++ impl FrameSink for RawVideoEncoder {+ fn frame(&mut self, frame: Frame<'_>) -> anyhow::Result<FrameFlow> {+ let geometry = Geometry {+ width: frame.width(),+ height: frame.height(),+ pix_fmt: ffmpeg_pix_fmt(frame.format()),+ };+ match &self.encoder {+ None => {+ self.encoder = Some(Encoder::spawn(&self.ffmpeg, &self.output_path, geometry)?);+ }+ Some(encoder) if encoder.geometry != geometry => {+ anyhow::bail!(+ "display geometry changed from {}x{} {} to {}x{} {} during recording; \+ the artifact was finalized at the point of change",+ encoder.geometry.width,+ encoder.geometry.height,+ encoder.geometry.pix_fmt,+ geometry.width,+ geometry.height,+ geometry.pix_fmt+ );+ }+ Some(_) => {}+ }+ frame.pack_rows(&mut self.latest);+ Ok(FrameFlow::Continue)+ }++ fn tick(&mut self) -> anyhow::Result<FrameFlow> {+ if self.stop.load(Ordering::SeqCst) {+ return Ok(FrameFlow::Stop);+ }+ let Some(encoder) = self.encoder.as_mut() else {+ return Ok(FrameFlow::Continue);+ };+ encoder.ensure_alive()?;+ let now = Instant::now();+ let due = encoder.pacer.due(now);+ let deadline = now + FEED_DEADLINE;+ for written in 0..due {+ // A stop request lands between frames, so the frame in flight+ // is always whole; frames never handed over are not counted.+ if written > 0 && self.stop.load(Ordering::SeqCst) {+ return Ok(FrameFlow::Stop);+ }+ encoder.feed(&self.latest, deadline)?;+ }+ if self.ready.is_some()+ && encoder.delivered > 0+ && encoder.spawned_at.elapsed() >= ENCODER_PROBE+ {+ encoder.ensure_alive()?;+ if let Some(ready) = self.ready.take() {+ let _ = ready.send(Ok(()));+ }+ }+ Ok(FrameFlow::Continue)+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn trusted_gnome_frames_take_precedence_over_every_probe_result() {+ for probe in [Some(true), Some(false), None] {+ assert_eq!(select_route(true, probe), WaylandVideoRoute::GnomeShell);+ }+ }++ #[test]+ fn compositors_without_wlr_screencopy_route_to_the_portal() {+ assert_eq!(+ select_route(false, Some(false)),+ WaylandVideoRoute::PortalScreencast+ );+ }++ #[test]+ fn wlr_screencopy_and_unprobeable_registries_keep_wf_recorder() {+ assert_eq!(+ select_route(false, Some(true)),+ WaylandVideoRoute::WfRecorder+ );+ assert_eq!(select_route(false, None), WaylandVideoRoute::WfRecorder);+ }++ #[cfg(not(feature = "portal-capture"))]+ #[test]+ fn portal_route_without_the_feature_names_the_build_flag() {+ let error = start_portal_video(Path::new("/nonexistent/recording.mp4"))+ .err()+ .expect("portal video must be refused without portal-capture");+ let message = error.to_string();+ assert!(message.contains("portal-capture"), "{message}");+ assert!(message.contains("wlr-screencopy"), "{message}");+ assert!(+ !Path::new("/nonexistent").exists(),+ "refusal must not create output directories"+ );+ }++ #[test]+ fn pacer_repeats_the_latest_frame_to_match_wall_clock_time() {+ let start = Instant::now();+ let mut pacer = FramePacer::new(10, start);+ assert_eq!(pacer.due(start), 0);+ assert_eq!(pacer.due(start + Duration::from_millis(50)), 0);+ assert_eq!(pacer.due(start + Duration::from_millis(100)), 1);+ assert_eq!(pacer.due(start + Duration::from_millis(150)), 0);+ // A stall of one second owes ten frames, not one.+ assert_eq!(pacer.due(start + Duration::from_millis(1150)), 10);+ assert_eq!(pacer.emitted, 11);+ }++ #[test]+ fn pacer_never_owes_frames_for_time_before_it_started() {+ let start = Instant::now();+ let mut pacer = FramePacer::new(30, start + Duration::from_secs(5));+ assert_eq!(pacer.due(start), 0);+ assert_eq!(pacer.due(start + Duration::from_secs(6)), 30);+ }++ #[cfg(feature = "portal-capture")]+ #[test]+ fn negotiated_formats_map_to_rawvideo_pixel_formats() {+ use crate::wayland::portal_screencast::RawFormat;+ assert_eq!(portal_video::ffmpeg_pix_fmt(RawFormat::Bgrx), "bgr0");+ assert_eq!(portal_video::ffmpeg_pix_fmt(RawFormat::Bgra), "bgra");+ assert_eq!(portal_video::ffmpeg_pix_fmt(RawFormat::Rgbx), "rgb0");+ assert_eq!(portal_video::ffmpeg_pix_fmt(RawFormat::Rgba), "rgba");+ }++ /// A non-blocking pipe; the test decides whether and how fast its reader+ /// drains it.+ #[cfg(feature = "portal-capture")]+ fn nonblocking_pipe() -> (std::fs::File, std::fs::File) {+ use std::os::fd::FromRawFd;+ let mut fds = [0i32; 2];+ assert_eq!(+ unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_NONBLOCK | libc::O_CLOEXEC) },+ 0,+ "pipe2: {}",+ std::io::Error::last_os_error()+ );+ unsafe {+ (+ std::fs::File::from_raw_fd(fds[0]),+ std::fs::File::from_raw_fd(fds[1]),+ )+ }+ }++ /// A slow but healthy reader forces many partial writes and `poll` waits;+ /// the frame must still arrive whole and in order.+ #[cfg(feature = "portal-capture")]+ #[test]+ fn write_frame_completes_a_frame_across_partial_writes_to_a_reading_consumer() {+ use portal_video::write_frame;+ // Larger than any Linux pipe capacity the kernel hands out by default.+ let frame: Vec<u8> = (0..(2u32 << 20)).map(|i| (i % 251) as u8).collect();+ let (mut reader, mut writer) = nonblocking_pipe();+ let expected = frame.clone();+ let drain = std::thread::spawn(move || {+ let mut received = Vec::new();+ let mut scratch = vec![0u8; 1 << 16];+ while received.len() < expected.len() {+ match reader.read(&mut scratch) {+ Ok(0) => break,+ Ok(n) => received.extend_from_slice(&scratch[..n]),+ Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {+ std::thread::sleep(Duration::from_millis(1));+ }+ Err(error) => panic!("{error}"),+ }+ }+ received+ });+ write_frame(+ &mut writer,+ &frame,+ Instant::now() + Duration::from_secs(10),+ )+ .expect("a draining consumer accepts the whole frame");+ drop(writer);+ assert_eq!(drain.join().unwrap(), frame);+ }++ /// The encoder is a child process holding the read end of a pipe; one+ /// that never reads must surface as a timeout at the deadline, not park+ /// the PipeWire thread.+ #[cfg(feature = "portal-capture")]+ #[test]+ fn write_frame_times_out_on_a_child_that_never_reads() {+ use portal_video::{set_nonblocking, write_frame};+ let mut child = Command::new("sleep")+ .arg("30")+ .stdin(Stdio::piped())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("sleep is available on every Linux CI image");+ let mut stdin = child.stdin.take().unwrap();+ set_nonblocking(&stdin).unwrap();++ let frame = vec![0xCDu8; 2 << 20];+ let began = Instant::now();+ let result = write_frame(&mut stdin, &frame, began + Duration::from_millis(300));+ let waited = began.elapsed();+ let _ = child.kill();+ let _ = child.wait();+ let error = result.expect_err("a full pipe with no reader cannot take a whole frame");+ assert_eq!(error.kind(), std::io::ErrorKind::TimedOut, "{error}");+ assert!(+ waited >= Duration::from_millis(300) && waited < Duration::from_secs(2),+ "waited {waited:?}: the deadline, not the pipe, must end the wait"+ );+ }++ /// `nb_read_frames` and container duration of a finished artifact.+ #[cfg(feature = "portal-capture")]+ fn probe_video(path: &Path) -> Option<(u64, f64)> {+ let output = Command::new("ffprobe")+ .args(["-v", "error", "-select_streams", "v:0", "-count_frames"])+ .args(["-show_entries", "stream=nb_read_frames:format=duration"])+ .args(["-of", "default=noprint_wrappers=1"])+ .arg(path)+ .output()+ .ok()?;+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let text = String::from_utf8_lossy(&output.stdout);+ let field = |key: &str| {+ text.lines()+ .find_map(|line| {+ line.strip_prefix(key)+ .and_then(|rest| rest.strip_prefix('='))+ })+ .unwrap_or_else(|| panic!("ffprobe output lacks {key}: {text}"))+ .trim()+ .to_owned()+ };+ Some((+ field("nb_read_frames").parse().unwrap(),+ field("duration").parse().unwrap(),+ ))+ }++ /// Drive the production sink exactly as the PipeWire timer does, at the+ /// resolution the parent recorded natively, and hold the finished+ /// artifact to the wall clock it was paced against.+ #[cfg(feature = "portal-capture")]+ #[test]+ fn a_healthy_encoder_receives_every_paced_frame_at_desktop_resolution() {+ use crate::wayland::portal_screencast::{Frame, FrameFlow, FrameSink};+ use libspa::param::video::VideoFormat;+ use portal_video::{RawVideoEncoder, FPS, TICK};+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::sync::Arc;++ let Some(ffmpeg) = find_ffmpeg() else {+ eprintln!("skipping: ffmpeg is not on PATH");+ return;+ };+ let dir = tempfile::tempdir().unwrap();+ let output = dir.path().join("paced.mp4");+ let stop = Arc::new(AtomicBool::new(false));+ let (ready_tx, ready_rx) = mpsc::sync_channel(1);+ let mut sink = RawVideoEncoder::new(ffmpeg, output.clone(), stop.clone(), ready_tx);++ let (width, height) = (1920u32, 1200u32);+ let pixels = vec![0x40u8; (width * height * 4) as usize];+ let frame = Frame::new(width, height, width * 4, VideoFormat::BGRx, &pixels).unwrap();+ assert_eq!(sink.frame(frame).unwrap(), FrameFlow::Continue);+ let spawned = Instant::now();++ let run_for = Duration::from_secs(3);+ let mut next_tick = spawned;+ let paced = loop {+ next_tick += TICK;+ std::thread::sleep(next_tick.saturating_duration_since(Instant::now()));+ if spawned.elapsed() >= run_for {+ stop.store(true, Ordering::SeqCst);+ }+ match sink.tick().unwrap() {+ FrameFlow::Continue => {}+ FrameFlow::Stop => break spawned.elapsed(),+ }+ };+ assert!(+ ready_rx.try_recv().unwrap().is_ok(),+ "a live encoder must report readiness after the probe window"+ );+ let delivered = sink.finish().unwrap();++ let one_frame = 1.0 / f64::from(FPS);+ let paced = paced.as_secs_f64();+ let reported = delivered as f64 * one_frame;+ assert!(+ (reported - paced).abs() <= one_frame + 0.15,+ "{delivered} frames were reported ({reported:.3}s) but the pacer ran for {paced:.3}s"+ );+ let Some((frames, duration)) = probe_video(&output) else {+ eprintln!("skipping artifact probe: ffprobe is not on PATH");+ return;+ };+ eprintln!(+ "paced {paced:.3}s, reported {delivered} frames, ffprobe {frames} frames / {duration:.3}s"+ );+ assert_eq!(+ frames, delivered,+ "the artifact must hold exactly the frames that were reported"+ );+ assert!(+ (duration - paced).abs() <= one_frame + 0.15,+ "artifact covers {duration:.3}s but the pacer ran for {paced:.3}s ({frames} frames)"+ );+ }++ /// Freeze the real encoder mid-recording: the tick must fail within the+ /// feed window with a diagnostic instead of parking, and the partial+ /// artifact must still be finalized on the error path.+ #[cfg(feature = "portal-capture")]+ #[test]+ fn a_wedged_encoder_fails_the_tick_within_the_feed_window() {+ use crate::wayland::portal_screencast::{Frame, FrameFlow, FrameSink};+ use libspa::param::video::VideoFormat;+ use portal_video::{RawVideoEncoder, FEED_DEADLINE, TICK};+ use std::sync::atomic::AtomicBool;+ use std::sync::Arc;++ let Some(ffmpeg) = find_ffmpeg() else {+ eprintln!("skipping: ffmpeg is not on PATH");+ return;+ };+ let dir = tempfile::tempdir().unwrap();+ let output = dir.path().join("wedged.mp4");+ let (ready_tx, _ready_rx) = mpsc::sync_channel(1);+ let mut sink = RawVideoEncoder::new(+ ffmpeg,+ output.clone(),+ Arc::new(AtomicBool::new(false)),+ ready_tx,+ );+ let (width, height) = (1920u32, 1200u32);+ let pixels = vec![0x40u8; (width * height * 4) as usize];+ let frame = Frame::new(width, height, width * 4, VideoFormat::BGRx, &pixels).unwrap();+ assert_eq!(sink.frame(frame).unwrap(), FrameFlow::Continue);+ for _ in 0..5 {+ std::thread::sleep(TICK);+ assert_eq!(sink.tick().unwrap(), FrameFlow::Continue);+ }++ let pid = sink+ .encoder_pid()+ .expect("encoder spawned with the first frame") as i32;+ assert_eq!(unsafe { libc::kill(pid, libc::SIGSTOP) }, 0);+ let frozen = Instant::now();+ let error = loop {+ std::thread::sleep(TICK);+ match sink.tick() {+ Ok(FrameFlow::Continue) => assert!(+ frozen.elapsed() < FEED_DEADLINE + Duration::from_secs(2),+ "ticks kept succeeding against a frozen encoder"+ ),+ Ok(FrameFlow::Stop) => panic!("no stop was requested"),+ Err(error) => break error,+ }+ };+ let failed_after = frozen.elapsed();+ assert_eq!(unsafe { libc::kill(pid, libc::SIGCONT) }, 0);+ assert!(+ error.to_string().contains("not keeping up"),+ "unexpected diagnostic: {error}"+ );+ assert!(+ failed_after >= FEED_DEADLINE && failed_after < FEED_DEADLINE + Duration::from_secs(2),+ "failed after {failed_after:?}; the feed window must bound the wait"+ );+ // Error path: dropping the sink closes ffmpeg's input and reaps it,+ // leaving a finalized partial artifact.+ drop(sink);+ assert!(output+ .metadata()+ .map(|meta| meta.len() > 0)+ .unwrap_or(false));+ assert!(+ unsafe { libc::kill(pid, 0) } != 0,+ "ffmpeg must have been reaped"+ );+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rsindex 5a30b63fee..0f2acaaa4f 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libei.rs@@ -20,9 +20,9 @@//! until EIS acknowledges the preceding input through ei_connection.sync.//!//! Persistence: ashpd `PersistMode::ExplicitlyRevoked` keeps the user's consent-//! until they revoke it in desktop settings. The restore token is stored at-//! `~/.config/cua-driver/libei-persistent.token` and reused across daemon-//! restarts.+//! until they revoke it in desktop settings. The restore token is stored via+//! [`super::portal::RestoreToken::RemoteDesktopInput`] and reused across+//! daemon restarts.//!//! Coordinates: ei_pointer_absolute takes desktop-layout positions that must//! lie inside an announced ei_device.Region — collected between device creation@@ -31,13 +31,14 @@use super::region_route::{route_absolute, RegionRect};use std::collections::HashMap;-use std::path::PathBuf;use std::sync::OnceLock;use std::thread;use crossbeam_channel::{bounded, Receiver, Sender};use xkbcommon::xkb;+use super::portal::RestoreToken;+/// Buttons the public API exposes. Mapped to evdev codes in the worker/// thread so the libei surface only sees evdev integers.#[derive(Debug, Clone, Copy)]@@ -163,53 +164,6 @@ fn wait_for_reply(rx: Receiver<anyhow::Result<()>>) -> anyhow::Result<()> {})?}-fn restore_token_path() -> Option<PathBuf> {- let base = dirs::config_dir()?;- Some(base.join("cua-driver").join("libei-persistent.token"))-}--fn read_restore_token() -> Option<String> {- let path = restore_token_path()?;- std::fs::read_to_string(path)- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())-}--fn write_restore_token(token: &str) -> anyhow::Result<()> {- let path = restore_token_path()- .ok_or_else(|| anyhow::anyhow!("no config dir available for libei restore_token"))?;- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent).map_err(|e| {- anyhow::anyhow!(- "failed to create {} for restore_token: {e}",- parent.display()- )- })?;- }- use std::io::Write;- use std::os::unix::fs::OpenOptionsExt;-- let mut file = std::fs::OpenOptions::new()- .create(true)- .truncate(true)- .write(true)- .mode(0o600)- .open(&path)- .map_err(|e| {- anyhow::anyhow!(- "failed to open libei restore_token at {}: {e}",- path.display()- )- })?;- file.write_all(token.as_bytes()).map_err(|e| {- anyhow::anyhow!(- "failed to write libei restore_token to {}: {e}",- path.display()- )- })-}-/// Spawn the libei worker thread (idempotent — safe to call from every/// MCP tool invocation; subsequent calls are no-ops).pub fn ensure_started() -> anyhow::Result<()> {@@ -494,7 +448,7 @@ fn open_eis_context() -> anyhow::Result<(reis::ei::Context, PortalKeepAlive)> {let mut select_opts = SelectDevicesOptions::default().set_devices(BitFlags::<DeviceType>::from(DeviceType::Keyboard) | DeviceType::Pointer).set_persist_mode(PersistMode::ExplicitlyRevoked);- if let Some(tok) = read_restore_token() {+ if let Some(tok) = RestoreToken::RemoteDesktopInput.read() {select_opts = select_opts.set_restore_token(Some(tok.as_str()));}@@ -518,7 +472,7 @@ fn open_eis_context() -> anyhow::Result<(reis::ei::Context, PortalKeepAlive)> {// skip the dialog for the lifetime of the persistence grant// until the user explicitly revokes the grant in desktop settings.if let Some(tok) = started.restore_token() {- let _ = write_restore_token(tok);+ let _ = RestoreToken::RemoteDesktopInput.write(tok);}let fd = proxydiff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/libpipewire.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libpipewire.rsnew file mode 100644index 0000000000..31ed717eae--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/libpipewire.rs@@ -0,0 +1,143 @@+//! libpipewire, loaded when a portal recording starts instead of linked.+//!+//! Linking it would stop cua-driver and the SDK library from loading at all on+//! hosts without PipeWire, although only portal ScreenCast video uses it. The+//! `spa_*` helpers the capture also calls are header-only and compiled in.++use std::os::raw::{c_char, c_int, c_void};+use std::ptr;+use std::sync::{Mutex, PoisonError};++use libspa::sys::{spa_dict, spa_direction, spa_hook, spa_pod};+use pipewire_sys::{+ pw_buffer, pw_context, pw_core, pw_loop, pw_main_loop, pw_properties, pw_proxy, pw_stream,+ pw_stream_events, pw_stream_flags,+};++const SONAME: &str = "libpipewire-0.3.so.0";++macro_rules! entry_points {+ ($($name:ident: fn($($arg:ty),*) $(-> $ret:ty)?;)*) => {+ /// The libpipewire functions the portal capture calls.+ pub(crate) struct PipeWire {+ $(pub(crate) $name: unsafe extern "C" fn($($arg),*) $(-> $ret)?,)*+ _library: libloading::Library,+ }++ impl PipeWire {+ fn open(soname: &str) -> Result<Self, libloading::Error> {+ // SAFETY: libpipewire has no load-time initialisers with preconditions.+ let library = unsafe { libloading::Library::new(soname) }?;+ $(+ // Fails to compile if the type drifts from pipewire-sys's prototype.+ const _: unsafe extern "C" fn($($arg),*) $(-> $ret)? = pipewire_sys::$name;+ // SAFETY: the symbol has the type checked above.+ let $name = *unsafe {+ library.get::<unsafe extern "C" fn($($arg),*) $(-> $ret)?>(+ concat!(stringify!($name), "\0").as_bytes(),+ )+ }?;+ )*+ Ok(Self { $($name,)* _library: library })+ }+ }+ };+}++entry_points! {+ pw_init: fn(*mut c_int, *mut *mut *mut c_char);+ pw_main_loop_new: fn(*const spa_dict) -> *mut pw_main_loop;+ pw_main_loop_get_loop: fn(*mut pw_main_loop) -> *mut pw_loop;+ pw_main_loop_run: fn(*mut pw_main_loop) -> c_int;+ pw_main_loop_quit: fn(*mut pw_main_loop) -> c_int;+ pw_main_loop_destroy: fn(*mut pw_main_loop);+ pw_context_new: fn(*mut pw_loop, *mut pw_properties, usize) -> *mut pw_context;+ pw_context_connect_fd: fn(*mut pw_context, c_int, *mut pw_properties, usize) -> *mut pw_core;+ pw_context_destroy: fn(*mut pw_context);+ pw_core_disconnect: fn(*mut pw_core) -> c_int;+ pw_properties_new_dict: fn(*const spa_dict) -> *mut pw_properties;+ pw_proxy_destroy: fn(*mut pw_proxy);+ pw_stream_new: fn(*mut pw_core, *const c_char, *mut pw_properties) -> *mut pw_stream;+ pw_stream_add_listener: fn(*mut pw_stream, *mut spa_hook, *const pw_stream_events, *mut c_void);+ pw_stream_connect: fn(*mut pw_stream, spa_direction, u32, pw_stream_flags, *mut *const spa_pod, u32) -> c_int;+ pw_stream_dequeue_buffer: fn(*mut pw_stream) -> *mut pw_buffer;+ pw_stream_queue_buffer: fn(*mut pw_stream, *mut pw_buffer) -> c_int;+ pw_stream_destroy: fn(*mut pw_stream);+}++fn load(soname: &str) -> anyhow::Result<PipeWire> {+ PipeWire::open(soname).map_err(|error| {+ anyhow::anyhow!(+ "portal ScreenCast video needs the PipeWire client library, and {soname} could not \+ be loaded ({error}). Install it (libpipewire-0.3-0 on Debian and Ubuntu, \+ pipewire-libs on Fedora, libpipewire on Arch) and start the recording again."+ )+ })+}++/// Load and initialise libpipewire on first use. A failed load is not cached,+/// so installing PipeWire takes effect without restarting the driver.+pub(crate) fn libpipewire() -> anyhow::Result<&'static PipeWire> {+ static LOADED: Mutex<Option<&'static PipeWire>> = Mutex::new(None);+ let mut loaded = LOADED.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(pw) = *loaded {+ return Ok(pw);+ }+ let pw: &'static PipeWire = Box::leak(Box::new(load(SONAME)?));+ // SAFETY: called once, before any other libpipewire function.+ unsafe { (pw.pw_init)(ptr::null_mut(), ptr::null_mut()) };+ *loaded = Some(pw);+ Ok(pw)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_missing_library_names_the_package_to_install() {+ let error = load("libpipewire-cua-test-absent.so.0")+ .err()+ .expect("no such library")+ .to_string();+ assert!(+ error.contains("libpipewire-cua-test-absent.so.0"),+ "{error}"+ );+ assert!(error.contains("libpipewire-0.3-0"), "{error}");+ }++ struct NoSink;++ impl crate::wayland::portal_screencast::FrameSink for NoSink {+ fn frame(+ &mut self,+ _: crate::wayland::portal_screencast::Frame<'_>,+ ) -> anyhow::Result<crate::wayland::portal_screencast::FrameFlow> {+ unreachable!()+ }+ }++ #[test]+ fn the_crate_does_not_link_libpipewire() {+ // Keep the capture code live in this binary; the linker would not+ // record a library that only dead code references.+ std::hint::black_box(+ crate::wayland::portal_screencast::run_frame_stream::<NoSink> as *const (),+ );+ let exe = std::env::current_exe().unwrap();+ let output = std::process::Command::new("readelf")+ .arg("-d")+ .arg(&exe)+ .output()+ .expect("readelf (binutils) is needed to inspect the test binary");+ assert!(+ output.status.success(),+ "readelf -d {} failed",+ exe.display()+ );+ let dynamic = String::from_utf8_lossy(&output.stdout);+ assert!(dynamic.contains("(NEEDED)"), "{dynamic}");+ assert!(!dynamic.contains("libpipewire"), "{dynamic}");+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rsindex 167440c8ad..87e536c6aa 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/mod.rs@@ -31,9 +31,14 @@ pub mod shell_helper;pub mod sway_ipc;mod virtual_keyboard;// RemoteDesktop/libei input is portable and ships in release binaries.-// PipeWire ScreenCast capture is no longer built here (the portal-capture feature is kept for downstream forwarding).#[cfg(feature = "portal-input")]pub mod libei;+// PipeWire ScreenCast capture backs the portal video route for compositors+// without wlr-screencopy (KDE/KWin).+#[cfg(feature = "portal-capture")]+pub(crate) mod libpipewire;+#[cfg(feature = "portal-capture")]+pub(crate) mod portal_screencast;/// Whether the GNOME/KDE RemoteDesktop + libei input backend is compiled in.pub const PORTAL_INPUT_ENABLED: bool = cfg!(feature = "portal-input");diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal.rsindex 166158bc5b..83bda64c52 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal.rs@@ -7,6 +7,7 @@//! later portal call can wait forever. Always give ashpd an explicit//! connection whose lifetime is owned by the caller's runtime instead.+use std::path::{Path, PathBuf};use std::time::Duration;pub(crate) const PROBE_TIMEOUT: Duration = Duration::from_secs(2);@@ -16,3 +17,126 @@ pub(crate) async fn fresh_session_connection() -> anyhow::Result<zbus::Connectio.await.map_err(|e| anyhow::anyhow!("xdg-desktop-portal session bus unreachable: {e}"))}++/// Per-install portal `restore_token` files. A token lets a portal session+/// with `PersistMode::ExplicitlyRevoked` reuse the user's earlier consent, so+/// the desktop shows the consent dialog once per install rather than once per+/// process. Each portal purpose owns one token because the portal binds the+/// token to the exact sources or devices that were selected.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[cfg_attr(+ not(all(feature = "portal-input", feature = "portal-capture")),+ allow(dead_code)+)]+pub enum RestoreToken {+ /// RemoteDesktop keyboard + pointer for the libei input backend.+ RemoteDesktopInput,+ /// ScreenCast monitor stream for full-desktop video recording.+ ScreencastVideo,+}++#[cfg_attr(+ not(any(feature = "portal-input", feature = "portal-capture")),+ allow(dead_code)+)]+impl RestoreToken {+ fn file_name(self) -> &'static str {+ match self {+ // Historical name; renaming it would re-prompt every existing install.+ Self::RemoteDesktopInput => "libei-persistent.token",+ Self::ScreencastVideo => "screencast-video.token",+ }+ }++ fn path(self) -> Option<PathBuf> {+ Some(restore_token_path_in(&dirs::config_dir()?, self))+ }++ pub fn read(self) -> Option<String> {+ read_restore_token_at(&self.path()?)+ }++ pub fn write(self, token: &str) -> anyhow::Result<()> {+ let path = self+ .path()+ .ok_or_else(|| anyhow::anyhow!("no config dir available for portal restore_token"))?;+ write_restore_token_at(&path, token)+ }+}++fn restore_token_path_in(config_dir: &Path, token: RestoreToken) -> PathBuf {+ config_dir.join("cua-driver").join(token.file_name())+}++fn read_restore_token_at(path: &Path) -> Option<String> {+ std::fs::read_to_string(path)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+}++fn write_restore_token_at(path: &Path, token: &str) -> anyhow::Result<()> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).map_err(|e| {+ anyhow::anyhow!(+ "failed to create {} for restore_token: {e}",+ parent.display()+ )+ })?;+ }+ use std::io::Write;+ use std::os::unix::fs::OpenOptionsExt;++ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .truncate(true)+ .write(true)+ .mode(0o600)+ .open(path)+ .map_err(|e| {+ anyhow::anyhow!(+ "failed to open portal restore_token at {}: {e}",+ path.display()+ )+ })?;+ file.write_all(token.as_bytes()).map_err(|e| {+ anyhow::anyhow!(+ "failed to write portal restore_token to {}: {e}",+ path.display()+ )+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::os::unix::fs::PermissionsExt;++ #[test]+ fn restore_tokens_live_in_distinct_files_under_the_driver_config_dir() {+ let base = Path::new("/cfg");+ let input = restore_token_path_in(base, RestoreToken::RemoteDesktopInput);+ let video = restore_token_path_in(base, RestoreToken::ScreencastVideo);+ assert_eq!(+ input,+ PathBuf::from("/cfg/cua-driver/libei-persistent.token")+ );+ assert_ne!(input, video);+ assert_eq!(video.parent(), input.parent());+ }++ #[test]+ fn restore_token_roundtrips_trimmed_and_private() {+ let dir = tempfile::tempdir().unwrap();+ let path = restore_token_path_in(dir.path(), RestoreToken::ScreencastVideo);++ assert_eq!(read_restore_token_at(&path), None);+ write_restore_token_at(&path, " tok-123 \n").unwrap();+ assert_eq!(read_restore_token_at(&path).as_deref(), Some("tok-123"));+ let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;+ assert_eq!(mode, 0o600);++ write_restore_token_at(&path, "\n").unwrap();+ assert_eq!(read_restore_token_at(&path), None);+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rs b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rsnew file mode 100644index 0000000000..034b127aac--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/wayland/portal_screencast.rs@@ -0,0 +1,1013 @@+//! Compositor-agnostic capture via `xdg-desktop-portal` ScreenCast + PipeWire.+//!+//! Reaches GNOME/Mutter and KDE/KWin, which expose no wlroots capture+//! protocols to ordinary clients. Two primitives share one consent path:+//!+//! - [`ScreencastSession`] owns the portal side: create the session, select+//! sources, wait for the user's consent (or reuse a persisted restore+//! token), start the cast, and hand out the PipeWire remote fd plus node id.+//! - [`run_frame_stream`] owns the PipeWire side: connect to the remote,+//! negotiate a raw BGRx/BGRA/RGBx/RGBA format, and deliver dequeued frames+//! to a [`FrameSink`] on the calling thread until the sink asks to stop.+//!+//! The Wayland video backend composes them for a paced full-desktop recording.++use std::cell::RefCell;+use std::ffi::{c_char, c_int, c_void, CStr};+use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd};+use std::ptr;+use std::time::{Duration, Instant};++use ashpd::desktop::screencast::{+ CursorMode, OpenPipeWireRemoteOptions, Screencast, SelectSourcesOptions, SourceType,+ StartCastOptions, Streams,+};+use ashpd::desktop::{CreateSessionOptions, PersistMode, Session};+use ashpd::enumflags2::BitFlags;+use libspa::buffer::{ChunkFlags, Data};+use libspa::param::format::{FormatProperties, MediaSubtype, MediaType};+use libspa::param::video::{VideoFormat, VideoInfoRaw};+use libspa::param::{format_utils, ParamType};+use libspa::pod::serialize::PodSerializer;+use libspa::pod::Pod;+use libspa::spa_interface_call_method;+use libspa::sys as spa_sys;+use libspa::utils::{Fraction, Rectangle, SpaTypes};+use pipewire_sys as pw_sys;++use super::libpipewire::{libpipewire, PipeWire};+use super::portal::RestoreToken;++/// How long to wait for the user to answer the portal's consent dialog when no+/// valid restore token skips it.+pub const CONSENT_TIMEOUT: Duration = Duration::from_secs(60);++/// Bound on each stretch of portal calls that needs no user answer, so a+/// portal that never replies fails the start instead of parking its caller.+pub const PORTAL_CALL_TIMEOUT: Duration = Duration::from_secs(10);++fn portal_unresponsive(step: &str) -> anyhow::Error {+ anyhow::anyhow!(+ "xdg-desktop-portal did not answer {step} within {}s",+ PORTAL_CALL_TIMEOUT.as_secs()+ )+}++/// A live portal ScreenCast session. The portal tears the cast down when the+/// owning D-Bus connection goes away, so the session keeps its own runtime+/// alive (one worker thread keeps the zbus connection driven, see #2105).+pub struct ScreencastSession {+ runtime: tokio::runtime::Runtime,+ session: Session<Screencast>,+ streams: Streams,+ fd: OwnedFd,+}++impl ScreencastSession {+ /// Open a ScreenCast session for `sources`. When `restore` is given, the+ /// persisted token is offered so the desktop can skip its consent dialog,+ /// and the token the portal returns is persisted for the next session.+ pub fn open(+ sources: BitFlags<SourceType>,+ restore: Option<RestoreToken>,+ consent_timeout: Duration,+ ) -> anyhow::Result<Self> {+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .build()+ .map_err(|e| anyhow::anyhow!("failed to build tokio runtime for ashpd: {e}"))?;+ let (session, streams, fd) = runtime.block_on(async {+ let saved_token = restore.and_then(RestoreToken::read);+ let setup = tokio::time::timeout(PORTAL_CALL_TIMEOUT, async {+ let connection = super::portal::fresh_session_connection().await?;+ let proxy = Screencast::with_connection(connection).await.map_err(|e| {+ anyhow::anyhow!(+ "portal ScreenCast proxy unreachable: {e}. Install \+ xdg-desktop-portal-gnome / xdg-desktop-portal-kde."+ )+ })?;+ let session = proxy+ .create_session(CreateSessionOptions::default())+ .await+ .map_err(|e| anyhow::anyhow!("portal create_session failed: {e}"))?;++ let mut select_opts = SelectSourcesOptions::default()+ .set_sources(sources)+ .set_multiple(false)+ .set_cursor_mode(CursorMode::Embedded)+ .set_persist_mode(PersistMode::ExplicitlyRevoked);+ if let Some(token) = saved_token.as_deref() {+ select_opts = select_opts.set_restore_token(Some(token));+ }+ proxy+ .select_sources(&session, select_opts)+ .await+ .map_err(|e| anyhow::anyhow!("portal select_sources failed: {e}"))?+ .response()+ .map_err(|e| anyhow::anyhow!("portal select_sources response error: {e}"))?;+ anyhow::Ok((proxy, session))+ });+ let (proxy, session) = setup+ .await+ .map_err(|_| portal_unresponsive("the ScreenCast session setup"))??;++ // `start` resolves only once the user answers the consent dialog+ // (or the restore token skips it); bound that wait here.+ let start = proxy.start(&session, None, StartCastOptions::default());+ let streams = match tokio::time::timeout(consent_timeout, start).await {+ Ok(request) => request+ .map_err(|e| anyhow::anyhow!("portal start failed: {e}"))?+ .response()+ .map_err(|e| {+ anyhow::anyhow!(+ "portal ScreenCast start was refused (consent denied or dialog dismissed): {e}"+ )+ })?,+ Err(_) => {+ let _ = session.close().await;+ anyhow::bail!(+ "portal ScreenCast consent was not granted within {}s",+ consent_timeout.as_secs()+ );+ }+ };+ if let (Some(restore), Some(token)) = (restore, streams.restore_token()) {+ if saved_token.as_deref() != Some(token) {+ if let Err(error) = restore.write(token) {+ tracing::warn!("could not persist portal ScreenCast restore token: {error}");+ }+ }+ }++ let remote = proxy.open_pipe_wire_remote(&session, OpenPipeWireRemoteOptions::default());+ let fd = match tokio::time::timeout(PORTAL_CALL_TIMEOUT, remote).await {+ Ok(fd) => fd.map_err(|e| anyhow::anyhow!("portal open_pipe_wire_remote failed: {e}"))?,+ Err(_) => {+ let _ = session.close().await;+ return Err(portal_unresponsive("open_pipe_wire_remote"));+ }+ };+ anyhow::Ok((session, streams, fd))+ })?;+ Ok(Self {+ runtime,+ session,+ streams,+ fd,+ })+ }++ /// PipeWire node id of the first stream the portal published.+ pub fn node_id(&self) -> anyhow::Result<u32> {+ self.streams+ .streams()+ .first()+ .map(|stream| stream.pipe_wire_node_id())+ .ok_or_else(|| anyhow::anyhow!("portal advertised no ScreenCast streams"))+ }++ /// An independently owned duplicate of the PipeWire remote fd, suitable for+ /// `pw_context_connect_fd`, which consumes its fd.+ pub fn pipewire_fd(&self) -> anyhow::Result<OwnedFd> {+ let dup_fd = unsafe { libc::dup(self.fd.as_raw_fd()) };+ if dup_fd < 0 {+ anyhow::bail!(+ "dup of portal PipeWire fd failed: {}",+ std::io::Error::last_os_error()+ );+ }+ Ok(unsafe { OwnedFd::from_raw_fd(dup_fd) })+ }++ /// End the cast. The compositor stops streaming as soon as the portal+ /// session closes, so callers should stop consuming frames first.+ pub fn close(self) {+ let _ = self.runtime.block_on(self.session.close());+ }+}++/// The packed 32-bit layouts [`run_frame_stream`] offers during format+/// negotiation; every [`Frame`] carries one of these.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RawFormat {+ Bgrx,+ Bgra,+ Rgbx,+ Rgba,+}++impl RawFormat {+ pub fn from_video_format(format: VideoFormat) -> Option<Self> {+ match format {+ VideoFormat::BGRx => Some(Self::Bgrx),+ VideoFormat::BGRA => Some(Self::Bgra),+ VideoFormat::RGBx => Some(Self::Rgbx),+ VideoFormat::RGBA => Some(Self::Rgba),+ _ => None,+ }+ }+}++const BYTES_PER_PIXEL: usize = 4;++/// One dequeued video frame whose geometry has been checked against its+/// payload, so consumers can index rows without bounds failures.+pub struct Frame<'a> {+ width: u32,+ height: u32,+ stride: usize,+ format: RawFormat,+ pixels: &'a [u8],+}++impl<'a> Frame<'a> {+ /// Rejects frames a producer described inconsistently: an unsupported+ /// format, empty dimensions, rows narrower than `width` pixels, or a+ /// payload shorter than `stride * height`.+ pub fn new(+ width: u32,+ height: u32,+ stride: u32,+ format: VideoFormat,+ pixels: &'a [u8],+ ) -> anyhow::Result<Self> {+ let format = RawFormat::from_video_format(format).ok_or_else(|| {+ anyhow::anyhow!("portal ScreenCast negotiated unsupported pixel format {format:?}")+ })?;+ if width == 0 || height == 0 {+ anyhow::bail!("portal ScreenCast produced an empty {width}x{height} frame");+ }+ let stride = stride as usize;+ let row = width as usize * BYTES_PER_PIXEL;+ if stride < row {+ anyhow::bail!(+ "portal ScreenCast frame stride {stride} is narrower than its {width}-pixel rows \+ ({row} bytes)"+ );+ }+ let needed = stride * height as usize;+ if pixels.len() < needed {+ anyhow::bail!(+ "portal ScreenCast buffer holds {} bytes but {width}x{height} rows of {stride} \+ bytes need {needed}",+ pixels.len()+ );+ }+ Ok(Self {+ width,+ height,+ stride,+ format,+ pixels,+ })+ }++ pub fn width(&self) -> u32 {+ self.width+ }++ pub fn height(&self) -> u32 {+ self.height+ }++ pub fn format(&self) -> RawFormat {+ self.format+ }++ /// Copy the visible pixels into `out`, dropping any row padding so the+ /// result is `width * 4` bytes per row.+ pub fn pack_rows(&self, out: &mut Vec<u8>) {+ let row = self.width as usize * BYTES_PER_PIXEL;+ out.clear();+ out.reserve(row * self.height as usize);+ for line in self.pixels.chunks(self.stride).take(self.height as usize) {+ out.extend_from_slice(&line[..row]);+ }+ }+}++/// Whether [`run_frame_stream`] keeps pumping after a sink callback.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FrameFlow {+ Continue,+ Stop,+}++/// Consumer of a PipeWire capture stream. Both hooks run on the thread that+/// called [`run_frame_stream`]; an error from either ends the stream and is+/// returned to that caller.+pub trait FrameSink {+ fn frame(&mut self, frame: Frame<'_>) -> anyhow::Result<FrameFlow>;++ /// Periodic hook, called every [`run_frame_stream`] `tick_interval`.+ fn tick(&mut self) -> anyhow::Result<FrameFlow> {+ Ok(FrameFlow::Continue)+ }+}++#[derive(Debug, Clone, Copy)]+pub struct StreamOptions {+ /// Give up when the producer delivers no frame at all within this window+ /// (for example when the user closed the consent dialog mid-cast).+ pub first_frame_timeout: Duration,+ pub tick_interval: Duration,+}++impl Default for StreamOptions {+ fn default() -> Self {+ Self {+ first_frame_timeout: Duration::from_secs(10),+ tick_interval: Duration::from_millis(100),+ }+ }+}++/// A `pw_stream` state, as its `state_changed` event reports it.+#[derive(Debug, Clone, PartialEq, Eq)]+enum StreamState {+ Error(String),+ Unconnected,+ Connecting,+ Paused,+ Streaming,+}++impl StreamState {+ /// # Safety+ /// `error` is null or points to a NUL-terminated string.+ unsafe fn from_raw(state: pw_sys::pw_stream_state, error: *const c_char) -> Self {+ match state {+ pw_sys::pw_stream_state_PW_STREAM_STATE_UNCONNECTED => Self::Unconnected,+ pw_sys::pw_stream_state_PW_STREAM_STATE_CONNECTING => Self::Connecting,+ pw_sys::pw_stream_state_PW_STREAM_STATE_PAUSED => Self::Paused,+ pw_sys::pw_stream_state_PW_STREAM_STATE_STREAMING => Self::Streaming,+ _ => Self::Error(lossy(error)),+ }+ }+}++/// # Safety+/// `text` is null or points to a NUL-terminated string.+unsafe fn lossy(text: *const c_char) -> String {+ if text.is_null() {+ String::new()+ } else {+ CStr::from_ptr(text).to_string_lossy().into_owned()+ }+}++/// Capture state shared by every libpipewire callback of one+/// [`run_frame_stream`]. All of them run on the thread inside+/// `pw_main_loop_run`.+struct Pump<S> {+ pw: &'static PipeWire,+ mainloop: *mut pw_sys::pw_main_loop,+ stream: *mut pw_sys::pw_stream,+ node_id: u32,+ options: StreamOptions,+ sink: S,+ negotiated: VideoInfoRaw,+ started_at: Instant,+ saw_frame: bool,+ /// Most recent error the remote core reported against the connection+ /// itself; libpipewire only turns it into an `Unconnected` transition,+ /// dropping the message.+ core_error: Option<String>,+ outcome: Option<anyhow::Result<()>>,+}++/// Why a `pw_stream` state transition ends the capture, if it does.+///+/// libpipewire moves a stream to `Unconnected` without any `Error` when the+/// server destroys its node (`proxy_removed`) or the core connection drops+/// (`on_core_error` with `-EPIPE`), and a server-sent node error arrives as+/// an `Error` transition. `Paused` is not terminal: the compositor pauses a+/// source it may resume, and a damage-free desktop stays `Streaming`.+fn stream_loss(new: &StreamState, core_error: Option<&str>) -> Option<String> {+ match new {+ StreamState::Error(error) => Some(format!("portal ScreenCast stream failed: {error}")),+ StreamState::Unconnected => Some(match core_error {+ Some(error) => format!("portal ScreenCast stream disconnected: {error}"),+ None => "portal ScreenCast stream disconnected: the compositor removed the source \+ (session closed or sharing revoked)"+ .to_owned(),+ }),+ StreamState::Connecting | StreamState::Paused | StreamState::Streaming => None,+ }+}++/// Why removing registry global `removed` ends a capture of `node_id`, if it+/// does: only the portal's own node going away means the source is gone.+fn source_removed(removed: u32, node_id: u32) -> Option<&'static str> {+ (removed == node_id).then_some(+ "portal ScreenCast stream disconnected: the compositor removed the source \+ (session closed or sharing revoked)",+ )+}++impl<S: FrameSink> Pump<S> {+ /// Records the outcome; the callback quits the loop once its borrow ends+ /// (see [`settle`]).+ fn finish(&mut self, outcome: anyhow::Result<()>) {+ if self.outcome.is_none() {+ self.outcome = Some(outcome);+ }+ }++ fn apply(&mut self, result: anyhow::Result<FrameFlow>) {+ match result {+ Ok(FrameFlow::Continue) => {}+ Ok(FrameFlow::Stop) => self.finish(Ok(())),+ Err(error) => self.finish(Err(error)),+ }+ }++ fn negotiate(&mut self, param: &Pod) {+ let Ok((media_type, media_subtype)) = format_utils::parse_format(param) else {+ return;+ };+ if media_type != MediaType::Video || media_subtype != MediaSubtype::Raw {+ return;+ }+ let mut info = VideoInfoRaw::default();+ if info.parse(param).is_ok() {+ self.negotiated = info;+ }+ }++ /// # Safety+ /// `buffer` belongs to a `pw_buffer` just dequeued from this pump's stream.+ unsafe fn deliver(&mut self, buffer: *mut spa_sys::spa_buffer) {+ if self.outcome.is_some() {+ return;+ }+ let info = self.negotiated;+ let size = info.size();+ let (width, height) = (size.width, size.height);+ if width == 0 || height == 0 {+ return;+ }+ if buffer.is_null() || (*buffer).n_datas == 0 || (*buffer).datas.is_null() {+ return;+ }+ // `Data` is a transparent wrapper around `spa_data`.+ let data = &mut *(*buffer).datas.cast::<Data>();+ let chunk = data.chunk();+ let (offset, chunk_size, chunk_stride, chunk_flags) = (+ chunk.offset() as usize,+ chunk.size(),+ chunk.stride(),+ chunk.flags(),+ );+ // A producer marks buffers it could not fill; they carry no+ // frame and go straight back to it.+ if chunk_flags.contains(ChunkFlags::CORRUPTED) {+ return;+ }+ // Producers may leave stride unset; derive it for the packed+ // 32-bit formats negotiated below.+ let stride = if chunk_stride > 0 {+ chunk_stride as u32+ } else if chunk_size > 0 {+ chunk_size / height+ } else {+ width * 4+ };+ let data_type = data.type_();+ let frame = data+ .data()+ .ok_or_else(|| {+ anyhow::anyhow!(+ "portal ScreenCast delivered a {data_type:?} buffer that is not \+ memory-mapped; only shared-memory frames are supported"+ )+ })+ .and_then(|bytes| {+ let payload = bytes.get(offset..).unwrap_or(&[]);+ Frame::new(width, height, stride, info.format(), payload)+ });+ let result = match frame {+ Ok(frame) => {+ self.saw_frame = true;+ self.sink.frame(frame)+ }+ Err(error) => Err(error),+ };+ self.apply(result);+ }++ fn tick(&mut self) {+ if self.outcome.is_some() {+ return;+ }+ if !self.saw_frame && self.started_at.elapsed() >= self.options.first_frame_timeout {+ let timeout = self.options.first_frame_timeout.as_secs();+ self.finish(Err(anyhow::anyhow!(+ "portal ScreenCast delivered no frame within {timeout}s"+ )));+ return;+ }+ let result = self.sink.tick();+ self.apply(result);+ }+}++/// # Safety+/// `data` is the pump pointer a listener was registered with.+unsafe fn pump<'a, S>(data: *mut c_void) -> &'a RefCell<Pump<S>> {+ &*data.cast::<RefCell<Pump<S>>>()+}++/// Quits the loop once the capture has an outcome. Callers hold no borrow:+/// quitting from the loop thread can dispatch queued events, which re-enter+/// the callbacks.+///+/// # Safety+/// The pump's main loop is still alive.+unsafe fn settle<S>(pump: &RefCell<Pump<S>>) {+ let (pw, mainloop, done) = {+ let pump = pump.borrow();+ (pump.pw, pump.mainloop, pump.outcome.is_some())+ };+ if done {+ (pw.pw_main_loop_quit)(mainloop);+ }+}++unsafe extern "C" fn on_core_error<S>(+ data: *mut c_void,+ id: u32,+ _seq: c_int,+ res: c_int,+ message: *const c_char,+) {+ if id == pw_sys::PW_ID_CORE {+ pump::<S>(data).borrow_mut().core_error = Some(format!("{} ({res})", lossy(message)));+ }+}++unsafe extern "C" fn on_global_remove<S: FrameSink>(data: *mut c_void, id: u32) {+ let pump = pump::<S>(data);+ {+ let mut pump = pump.borrow_mut();+ if let Some(reason) = source_removed(id, pump.node_id) {+ pump.finish(Err(anyhow::anyhow!(reason)));+ }+ }+ settle(pump);+}++unsafe extern "C" fn on_state_changed<S: FrameSink>(+ data: *mut c_void,+ _old: pw_sys::pw_stream_state,+ new: pw_sys::pw_stream_state,+ error: *const c_char,+) {+ let new = StreamState::from_raw(new, error);+ let pump = pump::<S>(data);+ {+ let mut pump = pump.borrow_mut();+ if let Some(reason) = stream_loss(&new, pump.core_error.as_deref()) {+ pump.finish(Err(anyhow::anyhow!(reason)));+ }+ }+ settle(pump);+}++unsafe extern "C" fn on_param_changed<S: FrameSink>(+ data: *mut c_void,+ id: u32,+ param: *const spa_sys::spa_pod,+) {+ if !param.is_null() && id == ParamType::Format.as_raw() {+ pump::<S>(data).borrow_mut().negotiate(Pod::from_raw(param));+ }+}++unsafe extern "C" fn on_process<S: FrameSink>(data: *mut c_void) {+ let pump = pump::<S>(data);+ let (pw, stream) = {+ let pump = pump.borrow();+ (pump.pw, pump.stream)+ };+ // Keep only the newest queued buffer and hand the older ones back.+ let mut buffer = (pw.pw_stream_dequeue_buffer)(stream);+ if buffer.is_null() {+ return;+ }+ loop {+ let newer = (pw.pw_stream_dequeue_buffer)(stream);+ if newer.is_null() {+ break;+ }+ (pw.pw_stream_queue_buffer)(stream, buffer);+ buffer = newer;+ }+ pump.borrow_mut().deliver((*buffer).buffer);+ (pw.pw_stream_queue_buffer)(stream, buffer);+ settle(pump);+}++unsafe extern "C" fn on_tick<S: FrameSink>(data: *mut c_void, _expirations: u64) {+ let pump = pump::<S>(data);+ pump.borrow_mut().tick();+ settle(pump);+}++/// Runs one teardown step on drop, so an early return releases everything+/// created before it in reverse order.+struct Release<F: FnMut()>(F);++impl<F: FnMut()> Drop for Release<F> {+ fn drop(&mut self) {+ (self.0)()+ }+}++/// A listener registered with libpipewire. The hook and the events table it+/// points at stay at a fixed address until the hook is unlinked on drop.+struct Listener<E> {+ hook: Box<spa_sys::spa_hook>,+ events: Box<E>,+}++impl<E> Listener<E> {+ /// # Safety+ /// `add` registers the hook and events table it is given.+ unsafe fn add(events: E, add: impl FnOnce(*mut spa_sys::spa_hook, *const E)) -> Self {+ let mut listener = Self {+ hook: Box::new(std::mem::zeroed()),+ events: Box::new(events),+ };+ add(&mut *listener.hook, &*listener.events);+ listener+ }+}++impl<E> Drop for Listener<E> {+ fn drop(&mut self) {+ libspa::utils::hook::remove(*self.hook);+ }+}++fn timespec(duration: Duration) -> spa_sys::timespec {+ // SAFETY: timespec is plain data; zeroing also clears any padding fields.+ let mut timespec: spa_sys::timespec = unsafe { std::mem::zeroed() };+ timespec.tv_sec = duration.as_secs() as _;+ timespec.tv_nsec = duration.subsec_nanos() as _;+ timespec+}++fn creation_failed(what: &str) -> anyhow::Error {+ anyhow::anyhow!(+ "pipewire {what} failed: {}",+ std::io::Error::last_os_error()+ )+}++/// Connect to the PipeWire remote behind a portal ScreenCast and feed frames+/// from `node_id` to `sink` until the sink stops, the sink errors, the+/// stream errors or disconnects, a producer delivers an inconsistent frame,+/// or no first frame arrives in time. Blocks the calling thread.+///+/// Only raw shared-memory formats are offered (no DMA-BUF modifier+/// negotiation) so the compositor falls back to memfd buffers that+/// `MAP_BUFFERS` can expose as plain byte slices.+pub fn run_frame_stream<S: FrameSink>(+ fd: OwnedFd,+ node_id: u32,+ options: StreamOptions,+ sink: S,+) -> anyhow::Result<S> {+ let pw = libpipewire()?;++ // Compositors typically pick BGRx/BGRA on Linux desktops; the alternates+ // let negotiation succeed on more sources.+ let obj = libspa::pod::object!(+ SpaTypes::ObjectParamFormat,+ ParamType::EnumFormat,+ libspa::pod::property!(FormatProperties::MediaType, Id, MediaType::Video),+ libspa::pod::property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),+ libspa::pod::property!(+ FormatProperties::VideoFormat,+ Choice,+ Enum,+ Id,+ VideoFormat::BGRx,+ VideoFormat::BGRx,+ VideoFormat::BGRA,+ VideoFormat::RGBx,+ VideoFormat::RGBA,+ ),+ libspa::pod::property!(+ FormatProperties::VideoSize,+ Choice,+ Range,+ Rectangle,+ Rectangle {+ width: 1920,+ height: 1080+ },+ Rectangle {+ width: 1,+ height: 1+ },+ Rectangle {+ width: 7680,+ height: 4320+ }+ ),+ libspa::pod::property!(+ FormatProperties::VideoFramerate,+ Choice,+ Range,+ Fraction,+ Fraction { num: 30, denom: 1 },+ Fraction { num: 0, denom: 1 },+ Fraction {+ num: 1000,+ denom: 1+ }+ ),+ );+ let values: Vec<u8> = PodSerializer::serialize(+ std::io::Cursor::new(Vec::new()),+ &libspa::pod::Value::Object(obj),+ )+ .map_err(|e| anyhow::anyhow!("EnumFormat pod serialization failed: {e}"))?+ .0+ .into_inner();+ let enum_format = Pod::from_bytes(&values)+ .ok_or_else(|| anyhow::anyhow!("EnumFormat pod parse-back failed"))?;++ let pump = Box::new(RefCell::new(Pump {+ pw,+ mainloop: ptr::null_mut(),+ stream: ptr::null_mut(),+ node_id,+ options,+ sink,+ negotiated: Default::default(),+ started_at: Instant::now(),+ saw_frame: false,+ core_error: None,+ outcome: None,+ }));+ let data: *mut c_void = ptr::from_ref(&*pump).cast_mut().cast();++ // SAFETY: every object below is created, used and destroyed on this+ // thread; each `Release` and `Listener` drops before what it refers to,+ // and all of them drop before `pump`, which every callback points at.+ unsafe {+ let mainloop = (pw.pw_main_loop_new)(ptr::null());+ if mainloop.is_null() {+ return Err(creation_failed("MainLoop::new"));+ }+ let _mainloop = Release(move || (pw.pw_main_loop_destroy)(mainloop));+ pump.borrow_mut().mainloop = mainloop;+ let loop_ = (pw.pw_main_loop_get_loop)(mainloop);++ let context = (pw.pw_context_new)(loop_, ptr::null_mut(), 0);+ if context.is_null() {+ return Err(creation_failed("Context::new"));+ }+ let _context = Release(move || (pw.pw_context_destroy)(context));++ let core = (pw.pw_context_connect_fd)(context, fd.into_raw_fd(), ptr::null_mut(), 0);+ if core.is_null() {+ return Err(creation_failed("connect_fd"));+ }+ let _core = Release(move || {+ (pw.pw_core_disconnect)(core);+ });++ let mut core_events: pw_sys::pw_core_events = std::mem::zeroed();+ core_events.version = pw_sys::PW_VERSION_CORE_EVENTS;+ core_events.error = Some(on_core_error::<S>);+ let _core_listener = Listener::add(core_events, |hook, events| {+ spa_interface_call_method!(+ core,+ pw_sys::pw_core_methods,+ add_listener,+ hook,+ events,+ data+ );+ });++ // A producer that stops casting removes its node, but libpipewire parks a+ // stream linked to it in `Paused` until the session manager gets round to+ // destroying it, which can take long enough to record a frozen tail.+ // Watching the registry ends the capture as soon as the source is gone.+ let registry: *mut pw_sys::pw_registry = spa_interface_call_method!(+ core,+ pw_sys::pw_core_methods,+ get_registry,+ pw_sys::PW_VERSION_REGISTRY,+ 0+ );+ if registry.is_null() {+ return Err(creation_failed("get_registry"));+ }+ let _registry = Release(move || (pw.pw_proxy_destroy)(registry.cast()));+ let mut registry_events: pw_sys::pw_registry_events = std::mem::zeroed();+ registry_events.version = pw_sys::PW_VERSION_REGISTRY_EVENTS;+ registry_events.global_remove = Some(on_global_remove::<S>);+ let _registry_listener = Listener::add(registry_events, |hook, events| {+ spa_interface_call_method!(+ registry,+ pw_sys::pw_registry_methods,+ add_listener,+ hook,+ events,+ data+ );+ });++ let item = |key: &'static [u8], value: &'static CStr| spa_sys::spa_dict_item {+ key: key.as_ptr().cast(),+ value: value.as_ptr(),+ };+ let items = [+ item(pw_sys::PW_KEY_MEDIA_TYPE, c"Video"),+ item(pw_sys::PW_KEY_MEDIA_CATEGORY, c"Capture"),+ item(pw_sys::PW_KEY_MEDIA_ROLE, c"Screen"),+ ];+ let props = spa_sys::spa_dict {+ flags: 0,+ n_items: items.len() as u32,+ items: items.as_ptr(),+ };+ // The stream takes ownership of the properties.+ let props = (pw.pw_properties_new_dict)(&props);+ let stream = (pw.pw_stream_new)(core, c"cua-driver-capture".as_ptr(), props);+ if stream.is_null() {+ return Err(creation_failed("Stream::new"));+ }+ let _stream = Release(move || (pw.pw_stream_destroy)(stream));+ pump.borrow_mut().stream = stream;++ let mut stream_events: pw_sys::pw_stream_events = std::mem::zeroed();+ stream_events.version = pw_sys::PW_VERSION_STREAM_EVENTS;+ stream_events.state_changed = Some(on_state_changed::<S>);+ stream_events.param_changed = Some(on_param_changed::<S>);+ stream_events.process = Some(on_process::<S>);+ let _stream_listener = Listener::add(stream_events, |hook, events| {+ (pw.pw_stream_add_listener)(stream, hook, events, data);+ });++ // `DONT_RECONNECT` binds the stream to the portal's node so the session+ // manager never relinks it to an unrelated video source once that node+ // is gone; the registry watch above reports the removal itself.+ let mut params = [enum_format.as_raw_ptr().cast_const()];+ let res = (pw.pw_stream_connect)(+ stream,+ spa_sys::SPA_DIRECTION_INPUT,+ node_id,+ pw_sys::pw_stream_flags_PW_STREAM_FLAG_AUTOCONNECT+ | pw_sys::pw_stream_flags_PW_STREAM_FLAG_MAP_BUFFERS+ | pw_sys::pw_stream_flags_PW_STREAM_FLAG_DONT_RECONNECT,+ params.as_mut_ptr(),+ params.len() as u32,+ );+ if res < 0 {+ anyhow::bail!(+ "pipewire stream.connect failed: {}",+ std::io::Error::from_raw_os_error(-res)+ );+ }++ let utils: *mut spa_sys::spa_interface = ptr::addr_of_mut!((*(*loop_).utils).iface);+ let ticker: *mut spa_sys::spa_source = spa_interface_call_method!(+ utils,+ spa_sys::spa_loop_utils_methods,+ add_timer,+ Some(on_tick::<S>),+ data+ );+ if ticker.is_null() {+ return Err(creation_failed("timer source"));+ }+ let _ticker = Release(move || {+ spa_interface_call_method!(+ utils,+ spa_sys::spa_loop_utils_methods,+ destroy_source,+ ticker+ )+ });+ let (mut value, mut interval) = (+ timespec(options.tick_interval),+ timespec(options.tick_interval),+ );+ let res = spa_interface_call_method!(+ utils,+ spa_sys::spa_loop_utils_methods,+ update_timer,+ ticker,+ &mut value,+ &mut interval,+ false+ );+ if res < 0 {+ anyhow::bail!(+ "pipewire timer source failed: {}",+ std::io::Error::from_raw_os_error(-res)+ );+ }++ (pw.pw_main_loop_run)(mainloop);+ // Leaving this block tears the stream down before the sink is handed+ // back, so the producer cannot touch buffers the sink may reference.+ }++ let pump = (*pump).into_inner();+ match pump.outcome {+ Some(Ok(())) | None => Ok(pump.sink),+ Some(Err(error)) => Err(error),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn frame_rejects_rows_narrower_than_its_width() {+ let pixels = [0u8; 8];+ let error = Frame::new(2, 1, 4, VideoFormat::BGRx, &pixels)+ .err()+ .expect("stride 4 cannot hold two 4-byte pixels");+ assert!(error.to_string().contains("stride 4"), "{error}");+ }++ #[test]+ fn frame_rejects_payloads_shorter_than_its_geometry() {+ let pixels = [0u8; 15];+ let error = Frame::new(2, 2, 8, VideoFormat::BGRx, &pixels)+ .err()+ .expect("15 bytes cannot hold 2 rows of 8");+ let message = error.to_string();+ assert!(message.contains("holds 15 bytes"), "{message}");+ assert!(message.contains("need 16"), "{message}");+ }++ #[test]+ fn frame_rejects_formats_outside_the_negotiated_set() {+ let pixels = [0u8; 4];+ let error = Frame::new(1, 1, 4, VideoFormat::NV12, &pixels)+ .err()+ .expect("NV12 is never offered to the producer");+ assert!(error.to_string().contains("NV12"), "{error}");+ assert!(Frame::new(0, 1, 4, VideoFormat::BGRx, &pixels).is_err());+ assert!(Frame::new(1, 0, 4, VideoFormat::BGRx, &pixels).is_err());+ }++ #[test]+ fn packing_drops_row_padding_and_trailing_bytes() {+ // Two 2-pixel rows with 4 bytes of padding each, plus a trailing byte+ // the producer left in the buffer.+ let pixels: Vec<u8> = (1u8..=25).collect();+ let frame = Frame::new(2, 2, 12, VideoFormat::BGRA, &pixels).unwrap();+ let mut packed = Vec::new();+ frame.pack_rows(&mut packed);+ assert_eq!(+ packed,+ [1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 16, 17, 18, 19, 20]+ );+ }++ #[test]+ fn only_the_cast_node_leaving_the_registry_ends_the_capture() {+ let reason = source_removed(44, 44).expect("the cast node was removed");+ assert!(reason.contains("removed the source"), "{reason}");+ assert_eq!(source_removed(47, 44), None, "other globals come and go");+ }++ #[test]+ fn stream_errors_and_disconnects_end_the_capture() {+ let error = stream_loss(&StreamState::Error("target not found".into()), None)+ .expect("server-sent node errors are terminal");+ assert!(error.contains("target not found"), "{error}");++ let removed = stream_loss(&StreamState::Unconnected, None)+ .expect("a stream that drops to Unconnected never reconnects");+ assert!(removed.contains("removed the source"), "{removed}");++ let lost = stream_loss(&StreamState::Unconnected, Some("connection error (-32)"))+ .expect("core errors explain the disconnect");+ assert!(lost.contains("connection error (-32)"), "{lost}");+ }++ #[test]+ fn pauses_and_connection_progress_keep_the_capture_alive() {+ for state in [+ StreamState::Connecting,+ StreamState::Paused,+ StreamState::Streaming,+ ] {+ assert_eq!(stream_loss(&state, Some("stale core error")), None);+ }+ }+}diff --git a/nix/cua-driver/package.nix b/nix/cua-driver/package.nixindex 6ebcefc9cc..1363262737 100644--- a/nix/cua-driver/package.nix+++ b/nix/cua-driver/package.nix@@ -69,8 +69,9 @@ pkgs.rustPlatform.buildRustPackage {# The `x11` crate (raw Xlib FFI for MPX multi-cursor drags) needs# libX11/libXi/libXtst via pkg-config. The Wayland-parity work# (round 2/3 — wayland::portal_screencast / wayland::libei) adds:- # pipewire 0.8 -> needs libpipewire-0.3 + libspa headers via pkg-config- # + bindgen (clang) for SPA pod generation+ # pipewire-sys 0.10 -> needs libpipewire-0.3 + libspa headers via+ # pkg-config + bindgen (clang); libpipewire is loaded at+ # runtime, not linked# reis 0.7 -> pure Rust libei binding, but the workspace pulls# libei-dev transitively through ashpd's tokio featurenativeBuildInputs = with pkgs; [@@ -95,6 +96,16 @@ pkgs.rustPlatform.buildRustPackage {libxkbcommon];+ # The portal video route dlopens libpipewire instead of linking it, so the+ # fixup's RUNPATH shrink would drop PipeWire; put it back.+ postFixup = ''+ patchelf --add-rpath ${pkgs.lib.makeLibraryPath [ pkgs.pipewire ]} $out/bin/cua-driver+ if ''${READELF:-readelf} -d $out/bin/cua-driver | grep NEEDED | grep -q libpipewire; then+ echo "cua-driver links libpipewire; it must load it at runtime" >&2+ exit 1+ fi+ '';+# Skip tests that require a running X11 display or AT-SPI busdoCheck = false;diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.jsonindex 9556c6535b..20121914df 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json@@ -2994,7 +2994,7 @@"read_only": false},{- "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",+ "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux X11 use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\n**Linux Wayland routes by compositor**: GNOME uses the trusted Shell helper's frames, wlroots compositors use `wf-recorder`, and compositors without wlr-screencopy (KDE/KWin) record the monitor the user grants through the xdg-desktop-portal ScreenCast (one consent dialog per install; requires a build with the `portal-capture` feature and ffmpeg on PATH). Unsupported combinations report the exact limitation in `last_error`.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.","destructive": false,"idempotent": true,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 71baa73494..0d3eda5fd5 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -2722,7 +2722,7 @@"read_only": false},{- "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",+ "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux X11 use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\n**Linux Wayland routes by compositor**: GNOME uses the trusted Shell helper's frames, wlroots compositors use `wf-recorder`, and compositors without wlr-screencopy (KDE/KWin) record the monitor the user grants through the xdg-desktop-portal ScreenCast (one consent dialog per install; requires a build with the `portal-capture` feature and ffmpeg on PATH). Unsupported combinations report the exact limitation in `last_error`.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.","destructive": false,"idempotent": true,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.jsonindex 78ca75b102..816f386afd 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json@@ -2688,7 +2688,7 @@"read_only": false},{- "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",+ "description": "Start trajectory recording for the calling session. Each action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) from that session writes a turn folder under `output_dir`. Without `session`, every call on the same connection is recorded, including named-session calls. Other connections and session lifecycle calls (`start_session` / `end_session`) are not recorded. CLI recordings started with `cua-driver recording start` are daemon-wide.\n\nEach turn folder holds:\n\n- `before_state.json` / `after_state.json` — application AX/UIA/AT-SPI state immediately before and after the action.\n- `before.png` / `after.png` — target-window screenshots immediately before and after the action.\n- `evidence.json` — capture status and a stable classification when an expected artifact could not be captured.\n- `app_state.json` — post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` — compatibility alias of `after.png`.\n- `action.json` — tool name, full input arguments, result summary, result-error flag, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` — for dispatched click-family actions only, `before.png` with a red marker at the click point. A call refused before target resolution is explicitly not applicable instead.\n\nThe per-turn accessibility walk is bounded like `get_window_state`: `state_timeout_ms` (default 1000) caps each before/after walk, a walk that runs out of budget records the PARTIAL tree, and `evidence.json` carries `truncated`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `timeout_ms` for that phase. A provider that stops answering is abandoned after the budget plus a short grace and the phase is classified `state_capture_timeout`. Actions refused before dispatch (for example an unknown or expired `capture_id`) skip the state walk; their state is classified `not_applicable` / `action_refused_before_dispatch`. Pass `include_accessibility_tree: false` to record screenshots and actions without state.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (daemon-owned SCStream + SCRecordingOutput) under the daemon's Screen Recording grant, with no ffmpeg subprocess. Requires macOS 15.0+. On macOS 26 (Tahoe), the first direct capture can also show a one-time consent asking to let Cua Driver bypass the system private window picker and directly access your screen and audio; choose Allow, or run `cua-driver permissions grant` beforehand to answer it up front. The recorder captures screen video only and does not enable system-audio capture.\n\n**Windows + Linux X11 use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\n**Linux Wayland routes by compositor**: GNOME uses the trusted Shell helper's frames, wlroots compositors use `wf-recorder`, and compositors without wlr-screencopy (KDE/KWin) record the monitor the user grants through the xdg-desktop-portal ScreenCast (one consent dialog per install; requires a build with the `portal-capture` feature and ffmpeg on PATH). Unsupported combinations report the exact limitation in `last_error`.\n\nState persists for the life of the daemon; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.","destructive": false,"idempotent": true,"input_schema": {